Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Limit update webhook triggers (#15349) (#15404)
Marcin Gębala1cc7c1c90a9f
diff --git a/saleor/graphql/context.py b/saleor/graphql/context.pyindex e0eef80ff8..79702cbcd2 100644--- a/saleor/graphql/context.py+++ b/saleor/graphql/context.py@@ -16,9 +16,10 @@ from .core import SaleorContextdef get_context_value(request: HttpRequest) -> SaleorContext:request = cast(SaleorContext, request)- request.dataloaders = {}+ if not hasattr(request, "dataloaders"):+ request.dataloaders = {}request.allow_replica = getattr(request, "allow_replica", True)- request.request_time = timezone.now()+ request.request_time = getattr(request, "request_time", timezone.now())set_app_on_context(request)set_auth_on_context(request)set_decoded_auth_token(request)diff --git a/saleor/graphql/core/context.py b/saleor/graphql/core/context.pyindex b98ba6e030..61e63576ff 100644--- a/saleor/graphql/core/context.py+++ b/saleor/graphql/core/context.py@@ -22,6 +22,11 @@ class SaleorContext(HttpRequest):requestor: Union[App, User, None]request_time: datetime.datetime+ def __init__(self, *args, **kwargs):+ if "dataloaders" in kwargs:+ self.dataloaders = kwargs.pop("dataloaders")+ super().__init__(*args, **kwargs)+def disallow_replica_in_context(context: SaleorContext) -> None:"""Set information in context to use database replicas or not.diff --git a/saleor/graphql/core/tests/test_context.py b/saleor/graphql/core/tests/test_context.pyindex f6cf25af45..78fc1296de 100644--- a/saleor/graphql/core/tests/test_context.py+++ b/saleor/graphql/core/tests/test_context.py@@ -1,6 +1,7 @@from django.urls import reversefrom ...context import set_app_on_context+from ..context import SaleorContextdef test_app_middleware_accepts_app_requests(app, rf):@@ -42,3 +43,14 @@ def test_app_middleware_skips_when_token_length_is_different_than_30(# thenassert not request.app+++def test_saleor_context_init_dataloaders():+ # given+ dataloaders = {}++ # when+ context = SaleorContext(dataloaders=dataloaders)++ # then+ assert context.dataloaders is dataloadersdiff --git a/saleor/graphql/page/dataloaders.py b/saleor/graphql/page/dataloaders.pyindex 06651079f3..e542e68ac6 100644--- a/saleor/graphql/page/dataloaders.py+++ b/saleor/graphql/page/dataloaders.py@@ -4,10 +4,8 @@ from promise import Promisefrom ...attribute.models import AssignedPageAttributeValue, AttributePagefrom ...page.models import Page, PageType-from ...permission.enums import PagePermissionsfrom ..attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdLoaderfrom ..core.dataloaders import DataLoader-from ..utils import get_user_or_app_from_contextclass PageByIdLoader(DataLoader):@@ -43,24 +41,16 @@ class PagesByPageTypeIdLoader(DataLoader):return [pagetype_to_pages[key] for key in keys]-class PageAttributesByPageTypeIdLoader(DataLoader):+class BasePageAttributesByPageTypeIdLoader(DataLoader):"""Loads page attributes by page type ID."""context_key = "page_attributes_by_pagetype"- def batch_load(self, keys):- requestor = get_user_or_app_from_context(self.context)- if (- requestor- and requestor.is_active- and requestor.has_perm(PagePermissions.MANAGE_PAGES)- ):- qs = AttributePage.objects.using(self.database_connection_name).all()- else:- qs = AttributePage.objects.using(self.database_connection_name).filter(- attribute__visible_in_storefront=True- )+ def get_queryset(self):+ raise NotImplementedError()+ def batch_load(self, keys):+ qs = self.get_queryset()page_type_attribute_pairs = qs.filter(page_type_id__in=keys).values_list("page_type_id", "attribute_id")@@ -86,8 +76,31 @@ class PageAttributesByPageTypeIdLoader(DataLoader):)-class AttributeValuesByPageIdLoader(DataLoader):- context_key = "attributevalues_by_page"+class PageAttributesAllByPageTypeIdLoader(BasePageAttributesByPageTypeIdLoader):+ """Loads page attributes by page type ID."""++ context_key = "page_attributes_all_by_pagetype"++ def get_queryset(self):+ return AttributePage.objects.using(self.database_connection_name).all()+++class PageAttributesVisibleInStorefrontByPageTypeIdLoader(+ BasePageAttributesByPageTypeIdLoader+):+ """Loads page attributes by page type ID."""++ context_key = "page_attributes_visible_in_storefront_by_pagetype"++ def get_queryset(self):+ return AttributePage.objects.using(self.database_connection_name).filter(+ attribute__visible_in_storefront=True+ )+++class BaseAttributeValuesByPageIdLoader(DataLoader):+ def get_page_attributes_dataloader(self):+ raise NotImplementedError()def batch_load(self, keys):# Using list + iterator is a small optimisation because iterator causes@@ -133,17 +146,40 @@ class AttributeValuesByPageIdLoader(DataLoader):)return [assigned_page_map[key] for key in keys]- attributes = PageAttributesByPageTypeIdLoader(self.context).load_many(- page_type_ids- )+ 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 SelectedAttributesByPageIdLoader(DataLoader):- context_key = "selectedattributes_by_page"+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 SelectedAttributesAllByPageIdLoader(DataLoader):+ context_key = "selectedattributes_all_by_page"++ def batch_load(self, page_ids):+ return AttributeValuesAllByPageIdLoader(self.context).load_many(page_ids)+++class SelectedAttributesVisibleInStorefrontPageIdLoader(DataLoader):+ context_key = "selectedattributes_visible_in_storefront_by_page"def batch_load(self, page_ids):- return AttributeValuesByPageIdLoader(self.context).load_many(page_ids)+ return AttributeValuesVisibleInStorefrontByPageIdLoader(self.context).load_many(+ page_ids+ )diff --git a/saleor/graphql/page/tests/queries/test_page.py b/saleor/graphql/page/tests/queries/test_page.pyindex bd6fef40d0..0d0a091d0d 100644--- a/saleor/graphql/page/tests/queries/test_page.py+++ b/saleor/graphql/page/tests/queries/test_page.py@@ -1,4 +1,5 @@import graphene+import pytestfrom .....attribute.models import AttributeValuefrom .....attribute.tests.model_helpers import (@@ -22,6 +23,7 @@ PAGE_QUERY = """contentJsonattributes {attribute {+ idslug}values {@@ -64,6 +66,7 @@ def test_query_published_page(user_api_client, page):expected_attributes = []for attr in page_type.page_attributes.all():+ attr_id = graphene.Node.to_global_id("Attribute", attr.pk)values = ([{@@ -76,7 +79,9 @@ def test_query_published_page(user_api_client, page):if attr.slug == page_attr.slugelse [])- expected_attributes.append({"attribute": {"slug": attr.slug}, "values": values})+ expected_attributes.append(+ {"attribute": {"id": attr_id, "slug": attr.slug}, "values": values}+ )for attr_data in page_data["attributes"]:assert attr_data in expected_attributes@@ -313,3 +318,115 @@ def test_get_page_with_sorted_attribute_values(assert [value["id"] for value in values] == [graphene.Node.to_global_id("AttributeValue", val.pk) for val in attr_values]+++def test_page_attribute_not_visible_in_storefront_for_customer_is_not_returned(+ user_api_client, page+):+ # given+ attribute = page.page_type.page_attributes.first()+ attribute.visible_in_storefront = False+ attribute.save(update_fields=["visible_in_storefront"])+ visible_attrs_count = page.page_type.page_attributes.filter(+ visible_in_storefront=True+ ).count()++ # when+ variables = {+ "id": graphene.Node.to_global_id("Page", page.pk),+ }+ response = user_api_client.post_graphql(+ PAGE_QUERY,+ variables,+ )++ # then+ content = get_graphql_content(response)+ assert len(content["data"]["page"]["attributes"]) == visible_attrs_count+ attr_data = {}+ for attr in content["data"]["page"]["attributes"]:+ if attr["attribute"]["id"] == graphene.Node.to_global_id(+ "Attribute", attribute.pk+ ):+ attr_data = attr+ attr_data.pop("values", None)+ break++ assert attr_data == {}+++def test_page_attribute_visible_in_storefront_for_customer_is_returned(+ user_api_client, page+):+ # given+ attribute = page.page_type.page_attributes.first()+ attribute.visible_in_storefront = True+ attribute.save(update_fields=["visible_in_storefront"])++ # when+ variables = {+ "id": graphene.Node.to_global_id("Page", page.pk),+ }+ response = user_api_client.post_graphql(+ PAGE_QUERY,+ variables,+ )++ # then+ content = get_graphql_content(response)+ attr_data = {}+ for attr in content["data"]["page"]["attributes"]:+ if attr["attribute"]["id"] == graphene.Node.to_global_id(+ "Attribute", attribute.pk+ ):+ attr_data = attr+ attr_data.pop("values", None)+ break++ assert attr_data == {+ "attribute": {+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),+ "slug": attribute.slug,+ }+ }++[email protected]("visible_in_storefront", [False, True])+def test_page_attribute_visible_in_storefront_for_staff_is_always_returned(+ visible_in_storefront,+ staff_api_client,+ page,+ permission_manage_pages,+):+ # given+ attribute = page.page_type.page_attributes.first()+ attribute.visible_in_storefront = visible_in_storefront+ attribute.save(update_fields=["visible_in_storefront"])++ # when+ variables = {+ "id": graphene.Node.to_global_id("Page", page.pk),+ }+ staff_api_client.user.user_permissions.add(permission_manage_pages)+ response = staff_api_client.post_graphql(+ PAGE_QUERY,+ variables,+ )++ # then+ content = get_graphql_content(response)+ attr_data = {}+ for attr in content["data"]["page"]["attributes"]:+ if attr["attribute"]["id"] == graphene.Node.to_global_id(+ "Attribute", attribute.pk+ ):+ attr_data = attr+ attr_data.pop("values", None)+ break++ assert attr_data == {+ "attribute": {+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),+ "slug": attribute.slug,+ }+ }diff --git a/saleor/graphql/page/tests/queries/test_page_type.py b/saleor/graphql/page/tests/queries/test_page_type.pyindex 6d5affef59..7c93a7e715 100644--- a/saleor/graphql/page/tests/queries/test_page_type.py+++ b/saleor/graphql/page/tests/queries/test_page_type.py@@ -1,4 +1,5 @@import graphene+import pytestfrom ....tests.utils import (assert_no_permission,@@ -300,3 +301,102 @@ def test_query_page_types_for_federation(api_client, page_type):"name": page_type.name,}]+++PAGE_TYPE_ATTRIBUTES_QUERY = """+ query PageType($id: ID!) {+ pageType(id: $id) {+ attributes {+ id+ slug+ }+ }+ }+"""+++def test_page_type_attribute_not_visible_in_storefront_for_customer_is_not_returned(+ user_api_client, page_type+):+ # given+ attribute = page_type.page_attributes.first()+ attribute.visible_in_storefront = False+ attribute.save(update_fields=["visible_in_storefront"])+ visible_attrs_count = page_type.page_attributes.filter(+ visible_in_storefront=True+ ).count()++ # when+ variables = {+ "id": graphene.Node.to_global_id("PageType", page_type.pk),+ }+ response = user_api_client.post_graphql(+ PAGE_TYPE_ATTRIBUTES_QUERY,+ variables,+ )++ # then+ content = get_graphql_content(response)+ assert len(content["data"]["pageType"]["attributes"]) == visible_attrs_count+ attr_data = {+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),+ "slug": attribute.slug,+ }+ assert attr_data not in content["data"]["pageType"]["attributes"]+++def test_page_type_attribute_visible_in_storefront_for_customer_is_returned(+ user_api_client, page_type+):+ # given+ attribute = page_type.page_attributes.first()+ attribute.visible_in_storefront = True+ attribute.save(update_fields=["visible_in_storefront"])++ # when+ variables = {+ "id": graphene.Node.to_global_id("PageType", page_type.pk),+ }+ response = user_api_client.post_graphql(+ PAGE_TYPE_ATTRIBUTES_QUERY,+ variables,+ )++ # then+ content = get_graphql_content(response)+ attr_data = {+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),+ "slug": attribute.slug,+ }+ assert attr_data in content["data"]["pageType"]["attributes"]++[email protected]("visible_in_storefront", [False, True])+def test_page_type_attribute_visible_in_storefront_for_staff_is_always_returned(+ visible_in_storefront,+ staff_api_client,+ page_type,+ permission_manage_pages,+):+ # given+ attribute = page_type.page_attributes.first()+ attribute.visible_in_storefront = visible_in_storefront+ attribute.save(update_fields=["visible_in_storefront"])++ # when+ variables = {+ "id": graphene.Node.to_global_id("PageType", page_type.pk),+ }+ staff_api_client.user.user_permissions.add(permission_manage_pages)+ response = staff_api_client.post_graphql(+ PAGE_TYPE_ATTRIBUTES_QUERY,+ variables,+ )++ # then+ content = get_graphql_content(response)+ attr_data = {+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),+ "slug": attribute.slug,+ }+ assert attr_data in content["data"]["pageType"]["attributes"]diff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.pyindex 8ff322eb7e..69830747a7 100644--- a/saleor/graphql/page/types.py+++ b/saleor/graphql/page/types.py@@ -21,11 +21,14 @@ from ..core.types import ModelObjectType, NonNullListfrom ..meta.types import ObjectWithMetadatafrom ..translations.fields import TranslationFieldfrom ..translations.types import PageTranslation+from ..utils import get_user_or_app_from_contextfrom .dataloaders import (- PageAttributesByPageTypeIdLoader,+ PageAttributesAllByPageTypeIdLoader,+ PageAttributesVisibleInStorefrontByPageTypeIdLoader,PagesByPageTypeIdLoader,PageTypeByIdLoader,- SelectedAttributesByPageIdLoader,+ SelectedAttributesAllByPageIdLoader,+ SelectedAttributesVisibleInStorefrontPageIdLoader,)@@ -70,7 +73,17 @@ class PageType(ModelObjectType[models.PageType]):@staticmethoddef resolve_attributes(root: models.PageType, info: ResolveInfo):- return PageAttributesByPageTypeIdLoader(info.context).load(root.pk)+ requestor = get_user_or_app_from_context(info.context)+ if (+ requestor+ and requestor.is_active+ and requestor.has_perm(PagePermissions.MANAGE_PAGES)+ ):+ return PageAttributesAllByPageTypeIdLoader(info.context).load(root.pk)+ else:+ return PageAttributesVisibleInStorefrontByPageTypeIdLoader(+ info.context+ ).load(root.pk)@staticmethoddef resolve_available_attributes(@@ -165,7 +178,17 @@ class Page(ModelObjectType[models.Page]):@staticmethoddef resolve_attributes(root: models.Page, info: ResolveInfo):- return SelectedAttributesByPageIdLoader(info.context).load(root.id)+ requestor = get_user_or_app_from_context(info.context)+ if (+ requestor+ and requestor.is_active+ and requestor.has_perm(PagePermissions.MANAGE_PAGES)+ ):+ return SelectedAttributesAllByPageIdLoader(info.context).load(root.id)+ else:+ return SelectedAttributesVisibleInStorefrontPageIdLoader(info.context).load(+ root.id+ )class PageCountableConnection(CountableConnection):diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.pyindex b2ac71ccad..cdd20a1f3d 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py@@ -4,6 +4,7 @@ from typing import castimport graphenefrom django.core.exceptions import ValidationErrorfrom django.db.models import F+from django.utils import timezonefrom graphene.utils.str_converters import to_camel_casefrom ....core.tracing import traced_atomic_transaction@@ -23,6 +24,8 @@ from ...core.scalars import PositiveDecimalfrom ...core.types import BaseInputObjectType, NonNullList, ProductVariantBulkErrorfrom ...core.utils import get_duplicated_valuesfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...utils import get_user_or_app_from_context+from ...webhook.subscription_payload import generate_pre_save_payloadsfrom ..mutations.channels import ProductVariantChannelListingAddInputfrom ..mutations.product.product_create import StockInput, StockUpdateInputfrom ..utils import clean_variant_sku, get_used_variants_attribute_values@@ -696,7 +699,9 @@ class ProductVariantBulkUpdate(BaseMutation):).delete()@classmethod- def post_save_actions(cls, info, instances, product):+ def post_save_actions(+ cls, info, instances, product, webhooks, pre_save_payloads, request_time+ ):manager = get_plugin_manager_promise(info.context).get()# Recalculate the "discounted price" for the parent product@@ -706,15 +711,20 @@ class ProductVariantBulkUpdate(BaseMutation):product.search_index_dirty = Trueproduct.save(update_fields=["search_index_dirty"])- webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED)for instance in instances:cls.call_event(- manager.product_variant_updated, instance.node, webhooks=webhooks+ manager.product_variant_updated,+ instance.node,+ webhooks=webhooks,+ pre_save_payloads=pre_save_payloads,+ request_time=request_time,)@classmethod@traced_atomic_transaction()def perform_mutation(cls, _root, info, **data):+ request_time = timezone.now()+index_error_map: dict = defaultdict(list)error_policy = data.get("error_policy", ErrorPolicyEnum.REJECT_EVERYTHING.value)product = cast(@@ -735,6 +745,11 @@ class ProductVariantBulkUpdate(BaseMutation):index_error_map,)+ webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED)+ pre_save_payloads = cls.generate_pre_save_payloads(+ info, request_time, cleaned_inputs_map, webhooks+ )+instances_data_with_errors_list = cls.update_variants(info, cleaned_inputs_map, index_error_map)@@ -758,6 +773,31 @@ class ProductVariantBulkUpdate(BaseMutation):instances = [result.product_variant for result in results if result.product_variant]- cls.post_save_actions(info, instances, product)+ cls.post_save_actions(+ info, instances, product, webhooks, pre_save_payloads, request_time+ )return ProductVariantBulkCreate(count=len(instances), results=results)++ @classmethod+ def generate_pre_save_payloads(+ cls, info, request_time, cleaned_inputs_map, webhooks+ ):+ # Take instances from cleaned_inputs_map to be updated in the mutation.+ instances = [+ clean_data["id"]+ for clean_data in cleaned_inputs_map.values()+ if clean_data and clean_data.get("id")+ ]++ requestor = get_user_or_app_from_context(info.context)+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED++ pre_save_payloads = generate_pre_save_payloads(+ webhooks=webhooks,+ instances=instances,+ event_type=event_type,+ requestor=requestor,+ request_time=request_time,+ )+ return pre_save_payloadsdiff --git a/saleor/graphql/product/dataloaders/__init__.py b/saleor/graphql/product/dataloaders/__init__.pyindex 7bdd7c8329..7a51246495 100644--- a/saleor/graphql/product/dataloaders/__init__.py+++ b/saleor/graphql/product/dataloaders/__init__.py@@ -1,8 +1,11 @@from .attributes import (- ProductAttributesByProductTypeIdLoader,- SelectedAttributesByProductIdLoader,+ ProductAttributesAllByProductTypeIdLoader,+ ProductAttributesVisibleInStorefrontByProductTypeIdLoader,+ SelectedAttributesAllByProductIdLoader,SelectedAttributesByProductVariantIdLoader,- VariantAttributesByProductTypeIdLoader,+ SelectedAttributesVisibleInStorefrontByProductIdLoader,+ VariantAttributesAllByProductTypeIdLoader,+ VariantAttributesVisibleInStorefrontByProductTypeIdLoader,)from .products import (AvailableProductVariantsByProductIdAndChannel,@@ -53,7 +56,8 @@ __all__ = ["ImagesByProductIdLoader","ImagesByProductVariantIdLoader","MediaByProductIdLoader",- "ProductAttributesByProductTypeIdLoader",+ "ProductAttributesAllByProductTypeIdLoader",+ "ProductAttributesVisibleInStorefrontByProductTypeIdLoader","ProductByIdLoader","ProductByVariantIdLoader","ProductTypeByProductIdLoader",@@ -67,12 +71,14 @@ __all__ = ["ProductVariantsByProductIdLoader","ProductMediaByIdLoader","MediaByProductVariantIdLoader",- "SelectedAttributesByProductIdLoader",+ "SelectedAttributesAllByProductIdLoader","SelectedAttributesByProductVariantIdLoader",+ "SelectedAttributesVisibleInStorefrontByProductIdLoader","ThumbnailByCategoryIdSizeAndFormatLoader","ThumbnailByCollectionIdSizeAndFormatLoader","ThumbnailByProductMediaIdSizeAndFormatLoader",- "VariantAttributesByProductTypeIdLoader",+ "VariantAttributesAllByProductTypeIdLoader",+ "VariantAttributesVisibleInStorefrontByProductTypeIdLoader","VariantChannelListingByVariantIdAndChannelSlugLoader","VariantChannelListingByVariantIdAndChannelIdLoader","VariantChannelListingByVariantIdLoader",diff --git a/saleor/graphql/product/dataloaders/attributes.py b/saleor/graphql/product/dataloaders/attributes.pyindex 6ced57dcf7..c502788f5d 100644--- a/saleor/graphql/product/dataloaders/attributes.py+++ b/saleor/graphql/product/dataloaders/attributes.py@@ -22,24 +22,16 @@ class BaseProductAttributesByProductTypeIdLoader(DataLoader):model_name = Noneextra_fields = None+ def get_queryset(self):+ raise NotImplementedError()+def batch_load(self, keys):if not self.model_name:raise ValueError("Provide a model_name for this dataloader.")if not self.extra_fields:self.extra_fields = []- requestor = get_user_or_app_from_context(self.context)- if (- requestor- and requestor.is_active- and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)- ):- qs = self.model_name.objects.using(self.database_connection_name).all()- else:- qs = self.model_name.objects.using(self.database_connection_name).filter(- attribute__visible_in_storefront=True- )-+ qs = self.get_queryset()product_type_attribute_pairs = qs.filter(product_type_id__in=keys).values_list("product_type_id", "attribute_id", *self.extra_fields)@@ -69,24 +61,55 @@ class BaseProductAttributesByProductTypeIdLoader(DataLoader):)-class ProductAttributesByProductTypeIdLoader(+class ProductAttributesAllByProductTypeIdLoader(BaseProductAttributesByProductTypeIdLoader):- """Loads product attributes by product type ID."""+ context_key = "product_attributes_all_by_producttype"+ model_name = AttributeProduct++ def get_queryset(self):+ return self.model_name.objects.using(self.database_connection_name).all()- context_key = "product_attributes_by_producttype"++class ProductAttributesVisibleInStorefrontByProductTypeIdLoader(+ BaseProductAttributesByProductTypeIdLoader+):+ context_key = "product_attributes_visible_in_storefront_by_producttype"model_name = AttributeProduct+ def get_queryset(self):+ return self.model_name.objects.using(self.database_connection_name).filter(+ attribute__visible_in_storefront=True+ )+++class VariantAttributesAllByProductTypeIdLoader(+ BaseProductAttributesByProductTypeIdLoader+):+ """Loads variant attributes by product type ID."""++ context_key = "variant_attributes_all_by_producttype"+ model_name = AttributeVariant+ extra_fields = ["variant_selection"]++ def get_queryset(self):+ return self.model_name.objects.using(self.database_connection_name).all()-class VariantAttributesByProductTypeIdLoader(++class VariantAttributesVisibleInStorefrontByProductTypeIdLoader(BaseProductAttributesByProductTypeIdLoader):"""Loads variant attributes by product type ID."""- context_key = "variant_attributes_by_producttype"+ context_key = "variant_attributes_visible_in_storefront_by_producttype"model_name = AttributeVariantextra_fields = ["variant_selection"]+ def get_queryset(self):+ return self.model_name.objects.using(self.database_connection_name).filter(+ attribute__visible_in_storefront=True+ )+class AttributeVariantsByProductTypeIdLoader(DataLoader):context_key = "attributevariants_by_producttype"@@ -167,8 +190,9 @@ class AttributeValuesByAssignedVariantAttributeIdLoader(DataLoader):)-class AttributeValuesByProductIdLoader(DataLoader):- context_key = "attributevalues_by_productid"+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@@ -216,7 +240,7 @@ class AttributeValuesByProductIdLoader(DataLoader):)return [assigned_product_map[key] for key in keys]- attributes = ProductAttributesByProductTypeIdLoader(self.context).load_many(+ attributes = self.get_product_attributes_dataloader().load_many(product_type_ids)values = AttributeValueByIdLoader(self.context).load_many(value_ids)@@ -225,11 +249,36 @@ class AttributeValuesByProductIdLoader(DataLoader):return ProductByIdLoader(self.context).load_many(keys).then(with_products)-class SelectedAttributesByProductIdLoader(DataLoader):- context_key = "selectedattributes_by_product"+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 SelectedAttributesAllByProductIdLoader(DataLoader):+ context_key = "selectedattributes_all_by_product"def batch_load(self, product_ids):- return AttributeValuesByProductIdLoader(self.context).load_many(product_ids)+ return AttributeValuesAllByProductIdLoader(self.context).load_many(product_ids)+++class SelectedAttributesVisibleInStorefrontByProductIdLoader(DataLoader):+ context_key = "selectedattributes_visible_in_storefront_by_product"++ def batch_load(self, product_ids):+ return AttributeValuesVisibleInStorefrontByProductIdLoader(+ self.context+ ).load_many(product_ids)class SelectedAttributesByProductVariantIdLoader(DataLoader):diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.pyindex f29b6376f3..568ff05a18 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py@@ -1,10 +1,15 @@+from unittest import mockfrom unittest.mock import patchimport graphene+from django.test import override_settings+from .....graphql.webhook.subscription_payload import get_pre_save_payload_keyfrom .....product.error_codes import ProductVariantBulkErrorCodefrom .....product.models import ProductChannelListingfrom .....tests.utils import flush_post_commit_hooks+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.models import Webhookfrom ....tests.utils import get_graphql_contentPRODUCT_VARIANT_BULK_UPDATE_MUTATION = """@@ -634,3 +639,54 @@ def test_product_variant_bulk_update_when_variant_not_exists(assert error["path"] == "id"assert error["field"] == "id"assert error["code"] == ProductVariantBulkErrorCode.INVALID.name+++@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=True)+ "saleor.graphql.product.bulk_mutations.product_variant_bulk_update.ProductVariantBulkUpdate.call_event"+)+def test_generate_pre_save_payloads(+ mocked_call_event,+ staff_api_client,+ variant,+ permission_manage_products,+ webhook_app,+):+ # given+ SUBSCRIPTION_QUERY = """+ subscription {+ event {+ issuedAt+ ... on ProductVariantUpdated {+ productVariant {+ name+ }+ }+ }+ }+ """+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ subscription_query=SUBSCRIPTION_QUERY,+ )+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED+ webhook.events.create(event_type=event_type)++ product_id = graphene.Node.to_global_id("Product", variant.product.pk)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variants = [{"id": variant_id, "sku": "NewSku"}]+ variables = {"productId": product_id, "variants": variants}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ staff_api_client.post_graphql(PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables)+ flush_post_commit_hooks()++ # then+ payload_key = get_pre_save_payload_key(webhook, variant)+ request_time = mocked_call_event.call_args[1]["request_time"]+ assert request_time+ pre_save_payload = mocked_call_event.call_args[1]["pre_save_payloads"]+ assert payload_key in pre_save_payload+ assert request_time.isoformat() == pre_save_payload[payload_key]["issuedAt"]diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.pyindex 01d7f9b676..1cee3df1a6 100644--- a/saleor/graphql/product/tests/queries/test_product_query.py+++ b/saleor/graphql/product/tests/queries/test_product_query.py@@ -2285,16 +2285,22 @@ def test_query_product_media_sorting_default_and_one_sort_order_null(QUERY_PRODUCT_WITH_ATTRIBUTE = """-query Product($id: ID!, $channel: String, $slug: String!){- product(id: $id, channel: $channel){- attribute(slug: $slug){- attribute{+query Product($id: ID!, $channel: String, $slug: String!) {+ product(id: $id, channel: $channel) {+ attribute(slug: $slug) {+ attribute {+ id+ slug+ }+ }+ attributes {+ attribute {idslug}- }}}+}"""@@ -2344,6 +2350,99 @@ def test_product_attribute_field_filtering_not_found(assert content["data"]["product"]["attribute"] is None+def test_product_attribute_not_visible_in_storefront_for_customer_is_not_returned(+ user_api_client, product, channel_USD+):+ # given+ attribute = product.product_type.product_attributes.first()+ attribute.visible_in_storefront = False+ attribute.save(update_fields=["visible_in_storefront"])+ visible_attrs_count = product.product_type.product_attributes.filter(+ visible_in_storefront=True+ ).count()++ # when+ variables = {+ "id": graphene.Node.to_global_id("Product", product.pk),+ "slug": attribute.slug,+ "channel": channel_USD.slug,+ }+ response = user_api_client.post_graphql(+ QUERY_PRODUCT_WITH_ATTRIBUTE,+ variables,+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["product"]["attribute"] is None+ assert len(content["data"]["product"]["attributes"]) == visible_attrs_count+ attr_data = {+ "attribute": {+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),+ "slug": attribute.slug,+ }+ }+ assert attr_data not in content["data"]["product"]["attributes"]+++def test_product_attribute_visible_in_storefront_for_customer_is_returned(+ user_api_client, product, channel_USD+):+ # given+ attribute = product.product_type.product_attributes.first()+ attribute.visible_in_storefront = True+ attribute.save(update_fields=["visible_in_storefront"])++ # when+ variables = {+ "id": graphene.Node.to_global_id("Product", product.pk),+ "slug": attribute.slug,+ "channel": channel_USD.slug,+ }+ response = user_api_client.post_graphql(+ QUERY_PRODUCT_WITH_ATTRIBUTE,+ variables,+ )++ # then+ content = get_graphql_content(response)+ assert (+ content["data"]["product"]["attribute"]["attribute"]["slug"] == attribute.slug+ )++[email protected]("visible_in_storefront", [False, True])+def test_product_attribute_visible_in_storefront_for_staff_is_always_returned(+ visible_in_storefront,+ staff_api_client,+ product,+ channel_USD,+ permission_manage_products,+):+ # given+ attribute = product.product_type.product_attributes.first()+ attribute.visible_in_storefront = visible_in_storefront+ attribute.save(update_fields=["visible_in_storefront"])++ # when+ variables = {+ "id": graphene.Node.to_global_id("Product", product.pk),+ "slug": attribute.slug,+ "channel": channel_USD.slug,+ }+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ QUERY_PRODUCT_WITH_ATTRIBUTE,+ variables,+ )++ # then+ content = get_graphql_content(response)+ assert (+ content["data"]["product"]["attribute"]["attribute"]["slug"] == attribute.slug+ )++QUERY_PRODUCTS_AVAILABILITY = """query ($channel:String){products(first: 10, channel: $channel) {diff --git a/saleor/graphql/product/tests/queries/test_product_type_query.py b/saleor/graphql/product/tests/queries/test_product_type_query.pyindex 7125b5f953..345a81040a 100644--- a/saleor/graphql/product/tests/queries/test_product_type_query.py+++ b/saleor/graphql/product/tests/queries/test_product_type_query.py@@ -593,3 +593,211 @@ def test_product_type_tax_class_query_by_staff(staff_api_client, product_type):assert data["productType"]assert data["productType"]["id"]assert data["productType"]["taxClass"]["id"]+++QUERY_PRODUCT_TYPE_ATTRIBUTES = """+ query ProductType($id: ID!) {+ productType(id: $id) {+ id+ productAttributes {+ id+ slug+ }+ variantAttributes {+ id+ slug+ }+ assignedVariantAttributes {+ attribute {+ id+ slug+ }+ }+ }+ }+"""+++def test_product_type_attribute_not_visible_in_storefront_for_customer_is_not_returned(+ user_api_client, product_type+):+ # given+ prod_attribute = product_type.product_attributes.first()+ prod_attribute.visible_in_storefront = False+ prod_attribute.save(update_fields=["visible_in_storefront"])+ visible_prod_attrs_count = product_type.product_attributes.filter(+ visible_in_storefront=True+ ).count()++ variant_attribute = product_type.variant_attributes.first()+ variant_attribute.visible_in_storefront = False+ variant_attribute.save(update_fields=["visible_in_storefront"])+ visible_variant_attrs_count = product_type.variant_attributes.filter(+ visible_in_storefront=True+ ).count()++ # when+ variables = {+ "id": graphene.Node.to_global_id("ProductType", product_type.pk),+ }+ response = user_api_client.post_graphql(+ QUERY_PRODUCT_TYPE_ATTRIBUTES,+ variables,+ )++ # then+ content = get_graphql_content(response)++ assert (+ len(content["data"]["productType"]["productAttributes"])+ == visible_prod_attrs_count+ )+ assert (+ len(content["data"]["productType"]["variantAttributes"])+ == visible_variant_attrs_count+ )+ assert (+ len(content["data"]["productType"]["assignedVariantAttributes"])+ == visible_variant_attrs_count+ )++ prod_attr_data = {+ "id": graphene.Node.to_global_id("Attribute", prod_attribute.pk),+ "slug": prod_attribute.slug,+ }+ assert prod_attr_data not in content["data"]["productType"]["productAttributes"]++ variant_attr_data = {+ "id": graphene.Node.to_global_id("Attribute", variant_attribute.pk),+ "slug": variant_attribute.slug,+ }+ assert variant_attr_data not in content["data"]["productType"]["variantAttributes"]++ assert {"attribute": variant_attr_data} not in content["data"]["productType"][+ "assignedVariantAttributes"+ ]+++def test_product_type_attribute_visible_in_storefront_for_customer_is_returned(+ user_api_client, product_type+):+ # given+ prod_attribute = product_type.product_attributes.first()+ prod_attribute.visible_in_storefront = True+ prod_attribute.save(update_fields=["visible_in_storefront"])+ visible_prod_attrs_count = product_type.product_attributes.filter(+ visible_in_storefront=True+ ).count()++ variant_attribute = product_type.variant_attributes.first()+ variant_attribute.visible_in_storefront = True+ variant_attribute.save(update_fields=["visible_in_storefront"])+ visible_variant_attrs_count = product_type.variant_attributes.filter(+ visible_in_storefront=True+ ).count()++ # when+ variables = {+ "id": graphene.Node.to_global_id("ProductType", product_type.pk),+ }+ response = user_api_client.post_graphql(+ QUERY_PRODUCT_TYPE_ATTRIBUTES,+ variables,+ )++ # then+ content = get_graphql_content(response)++ assert (+ len(content["data"]["productType"]["productAttributes"])+ == visible_prod_attrs_count+ )+ assert (+ len(content["data"]["productType"]["variantAttributes"])+ == visible_variant_attrs_count+ )+ assert (+ len(content["data"]["productType"]["assignedVariantAttributes"])+ == visible_variant_attrs_count+ )++ prod_attr_data = {+ "id": graphene.Node.to_global_id("Attribute", prod_attribute.pk),+ "slug": prod_attribute.slug,+ }+ assert prod_attr_data in content["data"]["productType"]["productAttributes"]++ variant_attr_data = {+ "id": graphene.Node.to_global_id("Attribute", variant_attribute.pk),+ "slug": variant_attribute.slug,+ }+ assert variant_attr_data in content["data"]["productType"]["variantAttributes"]++ assert {"attribute": variant_attr_data} in content["data"]["productType"][+ "assignedVariantAttributes"+ ]++[email protected]("visible_in_storefront", [False, True])+def test_product_type_attribute_visible_in_storefront_for_staff_is_always_returned(+ visible_in_storefront,+ staff_api_client,+ product_type,+ permission_manage_products,+):+ # given+ prod_attribute = product_type.product_attributes.first()+ prod_attribute.visible_in_storefront = visible_in_storefront+ prod_attribute.save(update_fields=["visible_in_storefront"])+ visible_prod_attrs_count = product_type.product_attributes.filter(+ visible_in_storefront=visible_in_storefront+ ).count()++ variant_attribute = product_type.variant_attributes.first()+ variant_attribute.visible_in_storefront = visible_in_storefront+ variant_attribute.save(update_fields=["visible_in_storefront"])+ visible_variant_attrs_count = product_type.variant_attributes.filter(+ visible_in_storefront=visible_in_storefront+ ).count()++ # when+ variables = {+ "id": graphene.Node.to_global_id("ProductType", product_type.pk),+ }+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ QUERY_PRODUCT_TYPE_ATTRIBUTES,+ variables,+ )++ # then+ content = get_graphql_content(response)++ assert (+ len(content["data"]["productType"]["productAttributes"])+ == visible_prod_attrs_count+ )+ assert (+ len(content["data"]["productType"]["variantAttributes"])+ == visible_variant_attrs_count+ )+ assert (+ len(content["data"]["productType"]["assignedVariantAttributes"])+ == visible_variant_attrs_count+ )++ prod_attr_data = {+ "id": graphene.Node.to_global_id("Attribute", prod_attribute.pk),+ "slug": prod_attribute.slug,+ }+ assert prod_attr_data in content["data"]["productType"]["productAttributes"]++ variant_attr_data = {+ "id": graphene.Node.to_global_id("Attribute", variant_attribute.pk),+ "slug": variant_attribute.slug,+ }+ assert variant_attr_data in content["data"]["productType"]["variantAttributes"]++ assert {"attribute": variant_attr_data} in content["data"]["productType"][+ "assignedVariantAttributes"+ ]diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 441e85a0bd..a77e206f9b 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -127,17 +127,20 @@ from ..dataloaders import (ImagesByProductVariantIdLoader,MediaByProductIdLoader,MediaByProductVariantIdLoader,- ProductAttributesByProductTypeIdLoader,+ ProductAttributesAllByProductTypeIdLoader,+ ProductAttributesVisibleInStorefrontByProductTypeIdLoader,ProductByIdLoader,ProductChannelListingByProductIdAndChannelSlugLoader,ProductChannelListingByProductIdLoader,ProductTypeByIdLoader,ProductVariantByIdLoader,ProductVariantsByProductIdLoader,- SelectedAttributesByProductIdLoader,+ SelectedAttributesAllByProductIdLoader,SelectedAttributesByProductVariantIdLoader,+ SelectedAttributesVisibleInStorefrontByProductIdLoader,ThumbnailByProductMediaIdSizeAndFormatLoader,- VariantAttributesByProductTypeIdLoader,+ VariantAttributesAllByProductTypeIdLoader,+ VariantAttributesVisibleInStorefrontByProductTypeIdLoader,VariantChannelListingByVariantIdAndChannelSlugLoader,VariantChannelListingByVariantIdLoader,VariantsChannelListingByProductIdAndChannelSlugLoader,@@ -1277,15 +1280,39 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):None,)- return (- SelectedAttributesByProductIdLoader(info.context)- .load(root.node.id)- .then(get_selected_attribute_by_slug)- )+ requestor = get_user_or_app_from_context(info.context)+ if (+ requestor+ and requestor.is_active+ and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)+ ):+ return (+ SelectedAttributesAllByProductIdLoader(info.context)+ .load(root.node.id)+ .then(get_selected_attribute_by_slug)+ )+ else:+ return (+ SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)+ .load(root.node.id)+ .then(get_selected_attribute_by_slug)+ )@staticmethoddef resolve_attributes(root: ChannelContext[models.Product], info):- return SelectedAttributesByProductIdLoader(info.context).load(root.node.id)+ requestor = get_user_or_app_from_context(info.context)+ if (+ requestor+ and requestor.is_active+ and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)+ ):+ return SelectedAttributesAllByProductIdLoader(info.context).load(+ root.node.id+ )+ else:+ return SelectedAttributesVisibleInStorefrontByProductIdLoader(+ info.context+ ).load(root.node.id)@staticmethoddef resolve_media_by_id(root: ChannelContext[models.Product], info, *, id):@@ -1694,11 +1721,23 @@ class ProductType(ModelObjectType[models.ProductType]):def unpack_attributes(attributes):return [attr for attr, *_ in attributes]- return (- ProductAttributesByProductTypeIdLoader(info.context)- .load(root.pk)- .then(unpack_attributes)- )+ requestor = get_user_or_app_from_context(info.context)+ if (+ requestor+ and requestor.is_active+ and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)+ ):+ return (+ ProductAttributesAllByProductTypeIdLoader(info.context)+ .load(root.pk)+ .then(unpack_attributes)+ )+ else:+ return (+ ProductAttributesVisibleInStorefrontByProductTypeIdLoader(info.context)+ .load(root.pk)+ .then(unpack_attributes)+ )@staticmethod@traced_resolver@@ -1719,11 +1758,23 @@ class ProductType(ModelObjectType[models.ProductType]):if (attr, variant_selection) not in variant_selection_attrs]- return (- VariantAttributesByProductTypeIdLoader(info.context)- .load(root.pk)- .then(apply_variant_selection_filter)- )+ requestor = get_user_or_app_from_context(info.context)+ if (+ requestor+ and requestor.is_active+ and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)+ ):+ return (+ VariantAttributesAllByProductTypeIdLoader(info.context)+ .load(root.pk)+ .then(apply_variant_selection_filter)+ )+ else:+ return (+ VariantAttributesVisibleInStorefrontByProductTypeIdLoader(info.context)+ .load(root.pk)+ .then(apply_variant_selection_filter)+ )@staticmethod@traced_resolver@@ -1750,11 +1801,23 @@ class ProductType(ModelObjectType[models.ProductType]):if (attr, variant_selection) not in variant_selection_attrs]- return (- VariantAttributesByProductTypeIdLoader(info.context)- .load(root.pk)- .then(apply_variant_selection_filter)- )+ requestor = get_user_or_app_from_context(info.context)+ if (+ requestor+ and requestor.is_active+ and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)+ ):+ return (+ VariantAttributesAllByProductTypeIdLoader(info.context)+ .load(root.pk)+ .then(apply_variant_selection_filter)+ )+ else:+ return (+ VariantAttributesVisibleInStorefrontByProductTypeIdLoader(info.context)+ .load(root.pk)+ .then(apply_variant_selection_filter)+ )@staticmethoddef resolve_products(root: models.ProductType, info, *, channel=None, **kwargs):diff --git a/saleor/graphql/tests/test_context.py b/saleor/graphql/tests/test_context.pyindex 37c5b4c366..81bfccb84d 100644--- a/saleor/graphql/tests/test_context.py+++ b/saleor/graphql/tests/test_context.py@@ -1,7 +1,9 @@from unittest import mockimport graphene+from django.utils import timezone+from ..context import get_context_valuefrom .utils import get_graphql_contentQUERY_ORDER_BY_ID = """@@ -41,3 +43,31 @@ def test_user_is_cached_on_request(data = content["data"]["order"]assert len(data["lines"]) > 1mocked_authenticate_user.assert_called_once()+++def test_get_context_value_not_override_dataloaders_if_passed_already(rf):+ # given+ request = rf.request()+ dataloaders = {}+ dataloaders_id = id(dataloaders)+ request.dataloaders = dataloaders++ # when+ context = get_context_value(request)++ # then+ assert context.dataloaders is dataloaders+ assert id(context.dataloaders) == dataloaders_id+++def test_get_context_value_uses_request_time_if_passed_already(rf):+ # given+ request = rf.request()+ request_time = timezone.now()+ request.request_time = request_time++ # when+ context = get_context_value(request)++ # then+ assert context.request_time == request_timediff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.pyindex 5b6d6548be..59bbce2f7d 100644--- a/saleor/graphql/translations/tests/test_translations.py+++ b/saleor/graphql/translations/tests/test_translations.py@@ -3928,6 +3928,89 @@ def test_nested_product_attribute_translation(assert attribute_response["translation"]["name"] == text+def test_product_attribute_not_visible_in_storefront_translation_not_returned_no_page_permission(+ staff_api_client,+ plain_text_attribute,+ product,+ permission_manage_translations,+):+ # given+ product_type = product.product_type+ product_type.product_attributes.set([plain_text_attribute])+ plain_text_attribute.visible_in_storefront = False+ plain_text_attribute.save(update_fields=["visible_in_storefront"])+ product_type.product_attributes.set([plain_text_attribute])+ attribute_value = plain_text_attribute.values.first()++ associate_attribute_values_to_instance(+ product, {plain_text_attribute.pk: [attribute_value]}+ )++ text = "Test attribute translation"+ plain_text_attribute.translations.create(language_code="pl", name=text)++ product_id = graphene.Node.to_global_id("Product", product.id)++ query = PRODUCT_ATTRIBUTE_VALUES_TRANSLATION_QUERY+ variables = {+ "id": product_id,+ "kind": TranslatableKinds.PRODUCT.name,+ "languageCode": LanguageCodeEnum.PL.name,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_translations]+ )++ # then+ data = get_graphql_content(response)["data"]+ assert data["translation"]["attributeValues"] == []+++def test_product_attribute_not_visible_in_storefront_translation_returned_with_product_permission(+ staff_api_client,+ plain_text_attribute,+ product,+ permission_manage_translations,+ permission_manage_products,+):+ # given+ product_type = product.product_type+ plain_text_attribute.visible_in_storefront = False+ plain_text_attribute.save(update_fields=["visible_in_storefront"])+ product_type.product_attributes.set([plain_text_attribute])+ attribute_value = plain_text_attribute.values.first()++ associate_attribute_values_to_instance(+ product, {plain_text_attribute.pk: [attribute_value]}+ )++ text = "Test attribute translation"+ plain_text_attribute.translations.create(language_code="pl", name=text)++ product_id = graphene.Node.to_global_id("Product", product.id)++ query = PRODUCT_ATTRIBUTE_VALUES_TRANSLATION_QUERY+ variables = {+ "id": product_id,+ "kind": TranslatableKinds.PRODUCT.name,+ "languageCode": LanguageCodeEnum.PL.name,+ }++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_translations]+ )++ # then+ data = get_graphql_content(response)["data"]+ attribute_response = data["translation"]["attributeValues"][0]["attribute"]+ assert attribute_response["name"] == plain_text_attribute.name+ assert attribute_response["translation"]["name"] == text++PRODUCT_VARIANT_ATTRIBUTE_VALUES_TRANSLATION_QUERY = """query translation($kind: TranslatableKinds!@@ -4223,6 +4306,88 @@ def test_nested_page_attribute_translation(assert attribute_response["translation"]["name"] == text+def test_page_attribute_not_visible_in_storefront_translation_not_returned_no_page_permission(+ staff_api_client,+ plain_text_attribute_page_type,+ page,+ permission_manage_translations,+):+ # given+ page_type = page.page_type+ plain_text_attribute_page_type.visible_in_storefront = False+ plain_text_attribute_page_type.save(update_fields=["visible_in_storefront"])+ page_type.page_attributes.set([plain_text_attribute_page_type])+ attribute_value = plain_text_attribute_page_type.values.first()++ associate_attribute_values_to_instance(+ page, {plain_text_attribute_page_type.pk: [attribute_value]}+ )++ text = "Test attribute translation"+ plain_text_attribute_page_type.translations.create(language_code="pl", name=text)++ page_id = graphene.Node.to_global_id("Page", page.id)++ query = PAGE_ATTRIBUTE_VALUES_TRANSLATION_QUERY+ variables = {+ "id": page_id,+ "kind": TranslatableKinds.PAGE.name,+ "languageCode": LanguageCodeEnum.PL.name,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_translations]+ )++ # then+ data = get_graphql_content(response)["data"]+ assert data["translation"]["attributeValues"] == []+++def test_page_attribute_not_visible_in_storefront_translation_returned_with_page_permission(+ staff_api_client,+ plain_text_attribute_page_type,+ page,+ permission_manage_translations,+ permission_manage_pages,+):+ # given+ page_type = page.page_type+ plain_text_attribute_page_type.visible_in_storefront = False+ plain_text_attribute_page_type.save(update_fields=["visible_in_storefront"])+ page_type.page_attributes.set([plain_text_attribute_page_type])+ attribute_value = plain_text_attribute_page_type.values.first()++ associate_attribute_values_to_instance(+ page, {plain_text_attribute_page_type.pk: [attribute_value]}+ )++ text = "Test attribute translation"+ plain_text_attribute_page_type.translations.create(language_code="pl", name=text)++ page_id = graphene.Node.to_global_id("Page", page.id)++ query = PAGE_ATTRIBUTE_VALUES_TRANSLATION_QUERY+ variables = {+ "id": page_id,+ "kind": TranslatableKinds.PAGE.name,+ "languageCode": LanguageCodeEnum.PL.name,+ }++ # when+ staff_api_client.user.user_permissions.add(permission_manage_pages)+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_translations]+ )++ # then+ data = get_graphql_content(response)["data"]+ attribute_response = data["translation"]["attributeValues"][0]["attribute"]+ assert attribute_response["name"] == plain_text_attribute_page_type.name+ assert attribute_response["translation"]["name"] == text++QUERY_TRANSLATION_PROMOTION = """query translation($kind: TranslatableKinds!, $id: ID!, $languageCode: LanguageCodeEnum!diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.pyindex d59f4ec54a..7bad3b2d4b 100644--- a/saleor/graphql/translations/types.py+++ b/saleor/graphql/translations/types.py@@ -10,7 +10,12 @@ from ...attribute.models import AttributeValuefrom ...discount import models as discount_modelsfrom ...menu import models as menu_modelsfrom ...page import models as page_models-from ...permission.enums import DiscountPermissions, ShippingPermissions+from ...permission.enums import (+ DiscountPermissions,+ PagePermissions,+ ProductPermissions,+ ShippingPermissions,+)from ...product import models as product_modelsfrom ...shipping import models as shipping_modelsfrom ...site import models as site_models@@ -29,11 +34,16 @@ from ..core.fields import JSONString, PermissionsFieldfrom ..core.tracing import traced_resolverfrom ..core.types import LanguageDisplay, ModelObjectType, NonNullListfrom ..core.utils import str_to_enum-from ..page.dataloaders import SelectedAttributesByPageIdLoader+from ..page.dataloaders import (+ SelectedAttributesAllByPageIdLoader,+ SelectedAttributesVisibleInStorefrontPageIdLoader,+)from ..product.dataloaders import (- SelectedAttributesByProductIdLoader,+ SelectedAttributesAllByProductIdLoader,SelectedAttributesByProductVariantIdLoader,+ SelectedAttributesVisibleInStorefrontByProductIdLoader,)+from ..utils import get_user_or_app_from_contextfrom .fields import TranslationField@@ -320,11 +330,23 @@ class ProductTranslatableContent(ModelObjectType[product_models.Product]):@staticmethoddef resolve_attribute_values(root: product_models.Product, info):- return (- SelectedAttributesByProductIdLoader(info.context)- .load(root.id)- .then(get_translatable_attribute_values)- )+ requestor = get_user_or_app_from_context(info.context)+ if (+ requestor+ and requestor.is_active+ and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)+ ):+ return (+ SelectedAttributesAllByProductIdLoader(info.context)+ .load(root.id)+ .then(get_translatable_attribute_values)+ )+ else:+ return (+ SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)+ .load(root.id)+ .then(get_translatable_attribute_values)+ )class CollectionTranslation(BaseTranslationType[product_models.CollectionTranslation]):@@ -554,11 +576,23 @@ class PageTranslatableContent(ModelObjectType[page_models.Page]):@staticmethoddef resolve_attribute_values(root: page_models.Page, info):- return (- SelectedAttributesByPageIdLoader(info.context)- .load(root.id)- .then(get_translatable_attribute_values)- )+ requestor = get_user_or_app_from_context(info.context)+ if (+ requestor+ and requestor.is_active+ and requestor.has_perm(PagePermissions.MANAGE_PAGES)+ ):+ return (+ SelectedAttributesAllByPageIdLoader(info.context)+ .load(root.id)+ .then(get_translatable_attribute_values)+ )+ else:+ return (+ SelectedAttributesVisibleInStorefrontPageIdLoader(info.context)+ .load(root.id)+ .then(get_translatable_attribute_values)+ )class VoucherTranslation(BaseTranslationType[discount_models.VoucherTranslation]):diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.pyindex 7a185c5762..f84ecf4d91 100644--- a/saleor/graphql/webhook/subscription_payload.py+++ b/saleor/graphql/webhook/subscription_payload.py@@ -1,17 +1,23 @@-from typing import Any, Optional+from collections.abc import Iterable+from datetime import datetime+from typing import Any, Optional, Unionfrom celery.utils.log import get_task_loggerfrom django.conf import settings+from django.db import modelsfrom django.utils import timezonefrom django.utils.functional import SimpleLazyObjectfrom graphql import get_default_backend, parsefrom graphql.error import GraphQLErrorfrom promise import Promise+from ...account.models import Userfrom ...app.models import Appfrom ...core.exceptions import PermissionDeniedfrom ...core.utils import get_domain+from ...webhook.models import Webhookfrom ..core import SaleorContext+from ..core.dataloaders import DataLoaderfrom ..utils import format_errorlogger = get_task_logger(__name__)@@ -22,6 +28,8 @@ def initialize_request(sync_event=False,allow_replica=False,event_type: Optional[str] = None,+ request_time: Optional[datetime] = None,+ dataloaders: Optional[dict] = None,) -> SaleorContext:"""Prepare a request object for webhook subscription.@@ -29,9 +37,9 @@ def initialize_request(return: HttpRequest"""-- request_time = timezone.now()- request = SaleorContext()+ if dataloaders is None:+ dataloaders = {}+ request = SaleorContext(dataloaders=dataloaders)request.path = "/graphql/"request.path_info = "/graphql/"request.method = "GET"@@ -43,7 +51,7 @@ def initialize_request(setattr(request, "sync_event", sync_event)setattr(request, "event_type", event_type)request.requestor = requestor- request.request_time = request_time+ request.request_time = request_time or timezone.now()request.allow_replica = allow_replicareturn request@@ -60,7 +68,7 @@ def get_event_payload(event):def generate_payload_from_subscription(event_type: str,subscribable_object,- subscription_query: Optional[str],+ subscription_query: str,request: SaleorContext,app: Optional[App] = None,) -> Optional[dict[str, Any]]:@@ -84,7 +92,7 @@ def generate_payload_from_subscription(from ..context import get_context_valuegraphql_backend = get_default_backend()- ast = parse(subscription_query) # type: ignore+ ast = parse(subscription_query)document = graphql_backend.document_from_string(schema,ast,@@ -124,3 +132,51 @@ def generate_payload_from_subscription(]return event_payload+++def get_pre_save_payload_key(webhook, instance):+ return f"{webhook.pk}_{instance.pk}"+++def generate_pre_save_payloads(+ webhooks: Iterable[Webhook],+ instances: Iterable[models.Model],+ event_type: str,+ requestor: Union[User, App, None],+ request_time: datetime,+):+ if not settings.ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS:+ return {}++ pre_save_payloads = {}++ # Dataloaders are shared between calls to generate_payload_from_subscription to+ # reuse their cache. This avoids unnecessary DB queries when different webhooks+ # need to resolve the same data.+ dataloaders: dict[str, type[DataLoader]] = {}++ request = initialize_request(+ requestor=requestor,+ sync_event=False,+ allow_replica=True,+ event_type=event_type,+ request_time=request_time,+ dataloaders=dataloaders,+ )++ for webhook in webhooks:+ if not webhook.subscription_query:+ continue++ for instance in instances:+ instance_payload = generate_payload_from_subscription(+ event_type=event_type,+ subscribable_object=instance,+ subscription_query=webhook.subscription_query,+ request=request,+ app=webhook.app,+ )+ key = get_pre_save_payload_key(webhook, instance)+ pre_save_payloads[key] = instance_payload++ return pre_save_payloadsdiff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex ce2a16668f..ace7ca3131 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -1,5 +1,4 @@import graphene-from django.utils import timezonefrom graphene import AbstractType, Unionfrom rx import Observable@@ -138,8 +137,8 @@ class Event(graphene.Interface):return cls.get_type(type_str)@staticmethod- def resolve_issued_at(_root, _info: ResolveInfo):- return timezone.now()+ def resolve_issued_at(_root, info: ResolveInfo):+ return info.context.request_time@staticmethoddef resolve_version(_root, _info: ResolveInfo):diff --git a/saleor/graphql/webhook/tests/test_subscription_payload.py b/saleor/graphql/webhook/tests/test_subscription_payload.pynew file mode 100644index 0000000000..08c97df52a--- /dev/null+++ b/saleor/graphql/webhook/tests/test_subscription_payload.py@@ -0,0 +1,119 @@+from django.test import override_settings+from django.utils import timezone++from ....webhook.event_types import WebhookEventAsyncType+from ....webhook.models import Webhook+from ..subscription_payload import (+ generate_pre_save_payloads,+ get_pre_save_payload_key,+ initialize_request,+)+++def test_initialize_request():+ # when+ request = initialize_request()++ # then+ assert request.dataloaders == {}+ assert request.request_time is not None+++def test_initialize_request_pass_params():+ # given+ dataloaders = {"test": "test"}+ request_time = timezone.now()++ # when+ request = initialize_request(dataloaders=dataloaders, request_time=request_time)++ # then+ assert request.dataloaders is dataloaders+ assert request.request_time is request_time+++SUBSCRIPTION_QUERY = """+ subscription {+ event {+ ... on ProductVariantUpdated {+ productVariant {+ name+ }+ }+ }+ }+"""+++@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=False)+def test_generate_pre_save_payloads_disabled_with_env(webhook_app, variant):+ # given+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ subscription_query=SUBSCRIPTION_QUERY,+ )+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED+ webhook.events.create(event_type=event_type)++ # when+ pre_save_payloads = generate_pre_save_payloads(+ [webhook],+ [variant],+ WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED,+ None,+ timezone.now(),+ )++ # then+ assert pre_save_payloads == {}+++@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=True)+def test_generate_pre_save_payloads_no_subscription_query(webhook_app, variant):+ # given+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ subscription_query=None,+ )+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED+ webhook.events.create(event_type=event_type)++ # when+ pre_save_payloads = generate_pre_save_payloads(+ [webhook],+ [variant],+ WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED,+ None,+ timezone.now(),+ )++ # then+ assert pre_save_payloads == {}+++@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=True)+def test_generate_pre_save_payloads(webhook_app, variant):+ # given+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ subscription_query=SUBSCRIPTION_QUERY,+ )+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED+ webhook.events.create(event_type=event_type)++ # when+ pre_save_payloads = generate_pre_save_payloads(+ [webhook],+ [variant],+ WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED,+ None,+ timezone.now(),+ )++ # then+ key = get_pre_save_payload_key(webhook, variant)+ assert key in pre_save_payloads+ assert pre_save_payloads[key]diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex a8c98b0b5b..3341a85123 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -710,10 +710,16 @@ class PluginsManager(PaymentInterface):"product_variant_created", default_value, product_variant, webhooks=webhooks)- def product_variant_updated(self, product_variant: "ProductVariant", webhooks=None):+ def product_variant_updated(+ self, product_variant: "ProductVariant", webhooks=None, **kwargs+ ):default_value = Nonereturn self.__run_method_on_plugins(- "product_variant_updated", default_value, product_variant, webhooks=webhooks+ "product_variant_updated",+ default_value,+ product_variant,+ webhooks=webhooks,+ **kwargs,)def product_variant_deleted(self, product_variant: "ProductVariant", webhooks=None):diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 510fd6d557..2d984ed6b8 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -1691,7 +1691,11 @@ class WebhookPlugin(BasePlugin):)def product_variant_updated(- self, product_variant: "ProductVariant", previous_value: Any, webhooks=None+ self,+ product_variant: "ProductVariant",+ previous_value: Any,+ webhooks=None,+ **kwargs,) -> Any:if not self.active:return previous_value@@ -1707,6 +1711,7 @@ class WebhookPlugin(BasePlugin):product_variant,self.requestor,legacy_data_generator=product_variant_data_generator,+ **kwargs,)def product_variant_deleted(diff --git a/saleor/settings.py b/saleor/settings.pyindex f63bc01a7b..669ae3e218 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -898,3 +898,11 @@ ORDER_RULES_LIMIT = os.environ.get("ORDER_RULES_LIMIT", 100)# The max number of gits assigned to promotion ruleGIFTS_LIMIT_PER_RULE = os.environ.get("GIFTS_LIMIT_PER_RULE", 500)++# Whether to enable the comparison of pre-save and post-save webhook payloads in+# mutations, in order to limit sending webhooks where the payload has not changed as+# a result of the mutation. Note: this works only for subscriptions webhooks; legacy+# payloads are not supported.+ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS = get_bool_from_env(+ "ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS", False+)diff --git a/saleor/webhook/transport/asynchronous/tests/__init__.py b/saleor/webhook/transport/asynchronous/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/webhook/transport/asynchronous/tests/test_create_deliveries_for_subscriptions.py b/saleor/webhook/transport/asynchronous/tests/test_create_deliveries_for_subscriptions.pynew file mode 100644index 0000000000..b197ab1bbb--- /dev/null+++ b/saleor/webhook/transport/asynchronous/tests/test_create_deliveries_for_subscriptions.py@@ -0,0 +1,156 @@+import json+from unittest import mock++from django.test import override_settings++from .....graphql.webhook.subscription_payload import generate_payload_from_subscription+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.models import Webhook+from ..transport import create_deliveries_for_subscriptions, get_pre_save_payload_key++SUBSCRIPTION_QUERY = """+ subscription {+ event {+ ... on ProductVariantUpdated {+ productVariant {+ name+ }+ }+ }+ }+"""+++@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=True)+def test_create_deliveries_different_pre_save_payloads(webhook_app, variant):+ # given+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ subscription_query=SUBSCRIPTION_QUERY,+ )+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED+ webhook.events.create(event_type=event_type)++ key = get_pre_save_payload_key(webhook, variant)+ pre_save_payloads = {key: {"productVariant": {"name": "Different name"}}}++ # when+ event_deliveries = create_deliveries_for_subscriptions(+ event_type=event_type,+ subscribable_object=variant,+ webhooks=[webhook],+ pre_save_payloads=pre_save_payloads,+ )++ # then+ assert event_deliveries+ event_delivery = event_deliveries[0]+ assert event_delivery+ payload = event_delivery.payload+ assert payload.payload+++@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=True)+def test_skip_delivery_creation_no_payload_changes(webhook_app, variant):+ # given+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ subscription_query=SUBSCRIPTION_QUERY,+ )+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED+ webhook.events.create(event_type=event_type)++ key = get_pre_save_payload_key(webhook, variant)+ pre_save_payloads = {key: {"productVariant": {"name": variant.name}}} # no change++ # when+ event_deliveries = create_deliveries_for_subscriptions(+ event_type=event_type,+ subscribable_object=variant,+ webhooks=[webhook],+ pre_save_payloads=pre_save_payloads,+ )++ # then+ assert event_deliveries == []+++@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=False)+def test_create_deliveries_no_payload_changes_limiting_disabled(webhook_app, variant):+ # given+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ subscription_query=SUBSCRIPTION_QUERY,+ )+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED+ webhook.events.create(event_type=event_type)++ key = get_pre_save_payload_key(webhook, variant)+ pre_payload = {"productVariant": {"name": variant.name}}+ pre_save_payloads = {key: pre_payload} # no change++ # when+ event_deliveries = create_deliveries_for_subscriptions(+ event_type=event_type,+ subscribable_object=variant,+ webhooks=[webhook],+ pre_save_payloads=pre_save_payloads,+ )++ # then+ assert event_deliveries+ event_delivery = event_deliveries[0]+ assert event_delivery+ payload = event_delivery.payload+ assert json.loads(payload.payload) == pre_payload+++@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=True)+ "saleor.webhook.transport.asynchronous.transport.generate_payload_from_subscription",+ wraps=generate_payload_from_subscription,+)+def test_create_deliveries_reuse_request_for_webhooks(+ mock_generate_payload_from_subscription, webhook_app, variant+):+ # given+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED+ webhook_1 = Webhook.objects.create(+ name="Webhook 1",+ app=webhook_app,+ subscription_query=SUBSCRIPTION_QUERY,+ )+ webhook_1.events.create(event_type=event_type)++ webhook_2 = Webhook.objects.create(+ name="Webhook 2",+ app=webhook_app,+ subscription_query=SUBSCRIPTION_QUERY,+ )+ webhook_2.events.create(event_type=event_type)++ key_1 = get_pre_save_payload_key(webhook_1, variant)+ key_2 = get_pre_save_payload_key(webhook_2, variant)++ pre_payload = {"productVariant": {"name": "Different name"}}+ pre_save_payloads = {key_1: pre_payload, key_2: pre_payload}++ # when+ event_deliveries = create_deliveries_for_subscriptions(+ event_type=event_type,+ subscribable_object=variant,+ webhooks=[webhook_1, webhook_2],+ pre_save_payloads=pre_save_payloads,+ )++ # then+ assert len(event_deliveries) == 2+ assert mock_generate_payload_from_subscription.call_count == 2++ request_1 = mock_generate_payload_from_subscription.call_args_list[0][1]["request"]+ request_2 = mock_generate_payload_from_subscription.call_args_list[1][1]["request"]+ assert request_1 is request_2+ assert request_1.dataloaders is request_2.dataloadersdiff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.pyindex 62b8f4a962..83034ebe48 100644--- a/saleor/webhook/transport/asynchronous/transport.py+++ b/saleor/webhook/transport/asynchronous/transport.py@@ -1,7 +1,8 @@+import datetimeimport jsonimport loggingfrom collections.abc import Sequence-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Optionalfrom urllib.parse import urlparsefrom celery import group@@ -13,8 +14,10 @@ from ....core import EventDeliveryStatusfrom ....core.models import EventDelivery, EventPayloadfrom ....core.tracing import webhooks_opentracing_tracefrom ....core.utils import get_domain+from ....graphql.core.dataloaders import DataLoaderfrom ....graphql.webhook.subscription_payload import (generate_payload_from_subscription,+ get_pre_save_payload_key,initialize_request,)from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP@@ -42,7 +45,13 @@ task_logger = get_task_logger(__name__)def create_deliveries_for_subscriptions(- event_type, subscribable_object, webhooks, requestor=None, allow_replica=False+ event_type,+ subscribable_object,+ webhooks,+ requestor=None,+ allow_replica=False,+ pre_save_payloads: Optional[dict] = None,+ request_time: Optional[datetime.datetime] = None,) -> list[EventDelivery]:"""Create a list of event deliveries with payloads based on subscription query.@@ -64,24 +73,51 @@ def create_deliveries_for_subscriptions(event_payloads = []event_deliveries = []++ # Dataloaders are shared between calls to generate_payload_from_subscription to+ # reuse their cache. This avoids unnecessary DB queries when different webhooks+ # need to resolve the same data.+ dataloaders: dict[str, type[DataLoader]] = {}++ request = initialize_request(+ requestor,+ event_type in WebhookEventSyncType.ALL,+ event_type=event_type,+ allow_replica=allow_replica,+ request_time=request_time,+ dataloaders=dataloaders,+ )+for webhook in webhooks:data = generate_payload_from_subscription(event_type=event_type,subscribable_object=subscribable_object,subscription_query=webhook.subscription_query,- request=initialize_request(- requestor,- event_type in WebhookEventSyncType.ALL,- event_type=event_type,- allow_replica=allow_replica,- ),+ request=request,app=webhook.app,)+if not data:logger.info("No payload was generated with subscription for event: %s" % event_type)continue++ if (+ settings.ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS+ and pre_save_payloads+ ):+ key = get_pre_save_payload_key(webhook, subscribable_object)+ pre_save_payload = pre_save_payloads.get(key)+ if pre_save_payload and pre_save_payload == data:+ logger.info(+ "[Webhook ID:%r] No data changes for event %r, skip delivery to %r",+ webhook.id,+ event_type,+ webhook.target_url,+ )+ continue+event_payload = EventPayload(payload=json.dumps({**data}))event_payloads.append(event_payload)event_deliveries.append(@@ -131,6 +167,8 @@ def trigger_webhooks_async(requestor=None,legacy_data_generator=None,allow_replica=False,+ pre_save_payloads=None,+ request_time=None,):"""Trigger async webhooks - both regular and subscription.@@ -141,7 +179,7 @@ def trigger_webhooks_async(:param webhooks: used in both webhook types, queryset of async webhooks.:param allow_replica: use a replica database.:param subscribable_object: subscribable object used in subscription webhooks.- :param requestor: used in subscription webhooks to generate mžeta data for payload.+ :param requestor: used in subscription webhooks to generate metadata for payload.:param legacy_data_generator: used to generate payload for regular webhooks."""regular_webhooks, subscription_webhooks = group_webhooks_by_subscription(webhooks)@@ -168,6 +206,8 @@ def trigger_webhooks_async(webhooks=subscription_webhooks,requestor=requestor,allow_replica=allow_replica,+ pre_save_payloads=pre_save_payloads,+ request_time=request_time,))