Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add ChannelContext to Attribtue related types (#17919)
Maciej Korycinski94492e45d9d2
diff --git a/saleor/graphql/attribute/mutations/attribute_bulk_create.py b/saleor/graphql/attribute/mutations/attribute_bulk_create.pyindex fbee35f938..72a31df3b3 100644--- a/saleor/graphql/attribute/mutations/attribute_bulk_create.py+++ b/saleor/graphql/attribute/mutations/attribute_bulk_create.py@@ -14,6 +14,7 @@ from ....permission.enums import PageTypePermissions, ProductTypePermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_eventfrom ...core import ResolveInfo+from ...core.context import ChannelContextfrom ...core.doc_category import DOC_CATEGORY_ATTRIBUTESfrom ...core.enums import ErrorPolicyEnumfrom ...core.mutations import BaseMutation, DeprecatedModelMutation@@ -197,13 +198,21 @@ class AttributeBulkCreateResult(BaseObjectType):def get_results(instances_data_with_errors_list: list[dict], reject_everything: bool = False) -> list[AttributeBulkCreateResult]:- return [- AttributeBulkCreateResult(- attribute=None if reject_everything else data.get("instance"),- errors=data.get("errors"),+ results = []+ for data in instances_data_with_errors_list:+ if reject_everything:+ attribute = None+ else:+ attribute = data.get("instance")+ if attribute:+ attribute = ChannelContext(attribute, None)+ results.append(+ AttributeBulkCreateResult(+ attribute=attribute,+ errors=data.get("errors"),+ ))- for data in instances_data_with_errors_list- ]+ return resultsclass AttributeBulkCreate(BaseMutation):diff --git a/saleor/graphql/attribute/mutations/attribute_bulk_update.py b/saleor/graphql/attribute/mutations/attribute_bulk_update.pyindex d85a130307..a92338f23b 100644--- a/saleor/graphql/attribute/mutations/attribute_bulk_update.py+++ b/saleor/graphql/attribute/mutations/attribute_bulk_update.py@@ -14,6 +14,7 @@ from ....core.tracing import traced_atomic_transactionfrom ....permission.enums import PageTypePermissions, ProductTypePermissionsfrom ....webhook.utils import get_webhooks_for_eventfrom ...core import ResolveInfo+from ...core.context import ChannelContextfrom ...core.doc_category import DOC_CATEGORY_ATTRIBUTESfrom ...core.enums import ErrorPolicyEnumfrom ...core.mutations import BaseMutation, DeprecatedModelMutation@@ -52,13 +53,21 @@ class AttributeBulkUpdateResult(BaseObjectType):def get_results(instances_data_with_errors_list: list[dict], reject_everything: bool = False) -> list[AttributeBulkUpdateResult]:- return [- AttributeBulkUpdateResult(- attribute=None if reject_everything else data.get("instance"),- errors=data.get("errors"),+ results = []+ for data in instances_data_with_errors_list:+ if reject_everything:+ attribute = None+ else:+ attribute = data.get("instance")+ if attribute:+ attribute = ChannelContext(attribute, None)+ results.append(+ AttributeBulkUpdateResult(+ attribute=attribute,+ errors=data.get("errors"),+ ))- for data in instances_data_with_errors_list- ]+ return resultsclass AttributeBulkUpdateInput(BaseInputObjectType):diff --git a/saleor/graphql/attribute/mutations/attribute_create.py b/saleor/graphql/attribute/mutations/attribute_create.pyindex 03405c2733..a51c7a0a16 100644--- a/saleor/graphql/attribute/mutations/attribute_create.py+++ b/saleor/graphql/attribute/mutations/attribute_create.py@@ -8,6 +8,7 @@ from ....core.exceptions import PermissionDeniedfrom ....permission.enums import PageTypePermissions, ProductTypePermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfo+from ...core.context import ChannelContextfrom ...core.descriptions import DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_ATTRIBUTESfrom ...core.enums import MeasurementUnitsEnum@@ -174,7 +175,7 @@ class AttributeCreate(AttributeMixin, DeprecatedModelMutation):cls._save_m2m(info, instance, cleaned_input)cls.post_save_action(info, instance, cleaned_input)# Return the attribute that was created- return AttributeCreate(attribute=instance)+ return AttributeCreate(attribute=ChannelContext(instance, None))@classmethoddef post_save_action(cls, info: ResolveInfo, instance, cleaned_input):diff --git a/saleor/graphql/attribute/mutations/attribute_delete.py b/saleor/graphql/attribute/mutations/attribute_delete.pyindex b47f783b67..6d52623b7e 100644--- a/saleor/graphql/attribute/mutations/attribute_delete.py+++ b/saleor/graphql/attribute/mutations/attribute_delete.py@@ -4,6 +4,7 @@ from ....attribute import models as modelsfrom ....permission.enums import ProductTypePermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfo+from ...core.context import ChannelContextfrom ...core.mutations import ModelDeleteMutation, ModelWithExtRefMutationfrom ...core.types import AttributeErrorfrom ...core.utils import WebhookEventInfo@@ -33,6 +34,12 @@ class AttributeDelete(ModelDeleteMutation, ModelWithExtRefMutation):),]+ @classmethod+ def success_response(cls, instance):+ response = super().success_response(instance)+ response.attribute = ChannelContext(instance, None)+ return response+@classmethoddef post_save_action(cls, info: ResolveInfo, instance, cleaned_input):manager = get_plugin_manager_promise(info.context).get()diff --git a/saleor/graphql/attribute/mutations/attribute_reorder_values.py b/saleor/graphql/attribute/mutations/attribute_reorder_values.pyindex f7313540ca..48b4315e91 100644--- a/saleor/graphql/attribute/mutations/attribute_reorder_values.py+++ b/saleor/graphql/attribute/mutations/attribute_reorder_values.py@@ -7,6 +7,7 @@ from ....core.tracing import traced_atomic_transactionfrom ....permission.enums import ProductTypePermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfo+from ...core.context import ChannelContextfrom ...core.doc_category import DOC_CATEGORY_ATTRIBUTESfrom ...core.inputs import ReorderInputfrom ...core.mutations import BaseMutation@@ -100,4 +101,4 @@ class AttributeReorderValues(BaseMutation):cls.call_event(manager.attribute_value_updated, value)cls.call_event(manager.attribute_updated, attribute)- return AttributeReorderValues(attribute=attribute)+ return AttributeReorderValues(attribute=ChannelContext(attribute, None))diff --git a/saleor/graphql/attribute/mutations/attribute_update.py b/saleor/graphql/attribute/mutations/attribute_update.pyindex 312d154f1c..2232b9dd72 100644--- a/saleor/graphql/attribute/mutations/attribute_update.py+++ b/saleor/graphql/attribute/mutations/attribute_update.py@@ -6,6 +6,7 @@ from ....attribute.error_codes import AttributeErrorCodefrom ....permission.enums import ProductTypePermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfo+from ...core.context import ChannelContextfrom ...core.descriptions import DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_ATTRIBUTESfrom ...core.enums import MeasurementUnitsEnum@@ -152,7 +153,7 @@ class AttributeUpdate(AttributeMixin, ModelWithExtRefMutation):cls.post_save_action(info, instance, cleaned_input)# Return the attribute that was created- return AttributeUpdate(attribute=instance)+ return AttributeUpdate(attribute=ChannelContext(instance, None))@classmethoddef post_save_action(cls, info: ResolveInfo, instance, cleaned_input):diff --git a/saleor/graphql/attribute/mutations/attribute_value_create.py b/saleor/graphql/attribute/mutations/attribute_value_create.pyindex 6b8f001347..7b46c8035c 100644--- a/saleor/graphql/attribute/mutations/attribute_value_create.py+++ b/saleor/graphql/attribute/mutations/attribute_value_create.py@@ -8,6 +8,7 @@ from ....core.utils import generate_unique_slugfrom ....permission.enums import ProductPermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfo+from ...core.context import ChannelContextfrom ...core.mutations import DeprecatedModelMutationfrom ...core.types import AttributeErrorfrom ...core.utils import WebhookEventInfo@@ -103,7 +104,10 @@ class AttributeValueCreate(AttributeMixin, DeprecatedModelMutation):instance.save()cls._save_m2m(info, instance, cleaned_input)cls.post_save_action(info, instance, cleaned_input)- return AttributeValueCreate(attribute=attribute, attributeValue=instance)+ return AttributeValueCreate(+ attribute=ChannelContext(attribute, None),+ attributeValue=ChannelContext(instance, None),+ )@classmethoddef post_save_action(cls, info: ResolveInfo, instance, cleaned_input):diff --git a/saleor/graphql/attribute/mutations/attribute_value_delete.py b/saleor/graphql/attribute/mutations/attribute_value_delete.pyindex 38666e2671..a62df49c21 100644--- a/saleor/graphql/attribute/mutations/attribute_value_delete.py+++ b/saleor/graphql/attribute/mutations/attribute_value_delete.py@@ -6,6 +6,7 @@ from ....permission.enums import ProductTypePermissionsfrom ....product import models as product_modelsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfo+from ...core.context import ChannelContextfrom ...core.mutations import ModelDeleteMutation, ModelWithExtRefMutationfrom ...core.types import AttributeErrorfrom ...core.utils import WebhookEventInfo@@ -72,5 +73,6 @@ class AttributeValueDelete(ModelDeleteMutation, ModelWithExtRefMutation):@classmethoddef success_response(cls, instance):response = super().success_response(instance)- response.attribute = instance.attribute+ response.attribute = ChannelContext(instance.attribute, None)+ response.attributeValue = ChannelContext(instance, None)return responsediff --git a/saleor/graphql/attribute/mutations/attribute_value_update.py b/saleor/graphql/attribute/mutations/attribute_value_update.pyindex 10dec7e098..4cd317f325 100644--- a/saleor/graphql/attribute/mutations/attribute_value_update.py+++ b/saleor/graphql/attribute/mutations/attribute_value_update.py@@ -7,6 +7,7 @@ from ....permission.enums import ProductTypePermissionsfrom ....product import models as product_modelsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfo+from ...core.context import ChannelContextfrom ...core.mutations import ModelWithExtRefMutationfrom ...core.types import AttributeErrorfrom ...core.utils import WebhookEventInfo@@ -87,7 +88,8 @@ class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):@classmethoddef success_response(cls, instance):response = super().success_response(instance)- response.attribute = instance.attribute+ response.attribute = ChannelContext(instance.attribute, None)+ response.attributeValue = ChannelContext(instance, None)return response@classmethoddiff --git a/saleor/graphql/attribute/schema.py b/saleor/graphql/attribute/schema.pyindex 46f3dfaa41..75b7a5bdf4 100644--- a/saleor/graphql/attribute/schema.py+++ b/saleor/graphql/attribute/schema.py@@ -3,6 +3,7 @@ import graphenefrom ...attribute import modelsfrom ..core import ResolveInfofrom ..core.connection import create_connection_slice, filter_connection_queryset+from ..core.context import ChannelContext, ChannelQsContextfrom ..core.descriptions import DEPRECATED_IN_3X_INPUTfrom ..core.doc_category import DOC_CATEGORY_ATTRIBUTESfrom ..core.fields import BaseField, FilterConnectionField@@ -69,14 +70,18 @@ class AttributeQueries(graphene.ObjectType):)if search:qs = filter_attribute_search(qs, None, search)+ qs = ChannelQsContext(qs=qs, channel_slug=None)return create_connection_slice(qs, info, kwargs, AttributeCountableConnection)def resolve_attribute(self, info: ResolveInfo, *, id=None, slug=None, external_reference=None):- return resolve_by_global_id_slug_or_ext_ref(+ attribute = resolve_by_global_id_slug_or_ext_ref(info, models.Attribute, id, slug, external_reference)+ if attribute:+ return ChannelContext(node=attribute, channel_slug=None)+ return Noneclass AttributeMutations(graphene.ObjectType):diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.pyindex f66080d790..a4ae695c10 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py@@ -64,36 +64,56 @@ def test_get_single_attribute_by_slug_as_customer(QUERY_ATTRIBUTE = """- query($id: ID!, $query: String) {- attribute(id: $id) {- id- slug- name- inputType- entityType- type- unit- choices(first: 10, filter: {search: $query}) {- edges {- node {- slug- inputType- value- file {- url- contentType- }- }- }- }- valueRequired- visibleInStorefront- filterableInStorefront- filterableInDashboard- availableInGrid- storefrontSearchPosition+query ($id: ID!, $query: String) {+ attribute(id: $id) {+ id+ slug+ name+ inputType+ entityType+ type+ unit+ choices(first: 10, filter: {search: $query}) {+ edges {+ node {+ slug+ inputType+ value+ file {+ url+ contentType+ }}+ }}+ valueRequired+ visibleInStorefront+ filterableInStorefront+ filterableInDashboard+ availableInGrid+ storefrontSearchPosition+ translation(languageCode: PL) {+ id+ name+ }+ withChoices+ productTypes(first: 1) {+ edges {+ node {+ id+ }+ }+ }+ productVariantTypes(first: 1) {+ edges {+ node {+ id+ }+ }+ }+ externalReference+ }+}"""@@ -417,9 +437,11 @@ def test_get_single_swatch_attribute_by_staff("slug": value.slug,"value": value.value,"inputType": value.input_type.upper(),- "file": {"url": value.file_url, "contentType": value.content_type}- if value.file_url- else None,+ "file": (+ {"url": value.file_url, "contentType": value.content_type}+ if value.file_url+ else None+ ),}}attribute_value_data.append(data)@@ -439,9 +461,29 @@ QUERY_ATTRIBUTES = """choices(first: 10) {edges {node {+ id+ name+ slug+ inputType+ value+ file {+ url+ contentType+ }+ translation(languageCode: PL) {idname- slug+ translatableContent {+ id+ }+ }+ reference+ richText+ plainText+ boolean+ date+ dateTime+ externalReference}}}diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex e4fcd908f9..50f35e13bb 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -13,7 +13,11 @@ from ..core.connection import (create_connection_slice,filter_connection_queryset,)-from ..core.context import ChannelContext, get_database_connection_name+from ..core.context import (+ ChannelContext,+ ChannelQsContext,+ get_database_connection_name,+)from ..core.descriptions import (ADDED_IN_322,DEFAULT_DEPRECATION_REASON,@@ -30,9 +34,9 @@ from ..core.types import (DateTimeRangeInput,File,IntRangeInput,- ModelObjectType,NonNullList,)+from ..core.types.context import ChannelContextType, ChannelContextTypeForObjectTypefrom ..decorators import check_attribute_required_permissionsfrom ..meta.types import ObjectWithMetadatafrom ..page.dataloaders import PageByIdLoader@@ -59,13 +63,15 @@ def get_reference_pk(attribute, root: models.AttributeValue) -> None | int:return reference_pk-class AttributeValue(ModelObjectType[models.AttributeValue]):+class AttributeValue(ChannelContextType[models.AttributeValue]):id = graphene.GlobalID(required=True, description="The ID of the attribute value.")name = graphene.String(description=AttributeValueDescriptions.NAME)slug = graphene.String(description=AttributeValueDescriptions.SLUG)value = graphene.String(description=AttributeValueDescriptions.VALUE)translation = TranslationField(- AttributeValueTranslation, type_name="attribute value"+ AttributeValueTranslation,+ type_name="attribute value",+ resolver=ChannelContextType.resolve_translation,)input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)reference = graphene.ID(description="The ID of the referenced object.")@@ -96,22 +102,27 @@ class AttributeValue(ModelObjectType[models.AttributeValue]):)class Meta:+ default_resolver = ChannelContextType.resolver_with_contextdescription = "Represents a value of an attribute."interfaces = [graphene.relay.Node]model = models.AttributeValue@staticmethod- def resolve_referenced_object(root: models.AttributeValue, info: ResolveInfo):+ def resolve_referenced_object(+ root: ChannelContext[models.AttributeValue], info: ResolveInfo+ ):+ attr_value = root.node+def prepare_referenced_object(attribute):if not attribute:return None- reference_pk = get_reference_pk(attribute, root)+ reference_pk = get_reference_pk(attribute, attr_value)if reference_pk is None:return Nonedef wrap_with_channel_context(_object):- return ChannelContext(node=_object, channel_slug=None)+ return ChannelContext(node=_object, channel_slug=root.channel_slug)if attribute.entity_type == AttributeEntityType.PRODUCT:return (@@ -131,61 +142,76 @@ class AttributeValue(ModelObjectType[models.AttributeValue]):return (AttributesByAttributeId(info.context)- .load(root.attribute_id)+ .load(attr_value.attribute_id).then(prepare_referenced_object))- @staticmethod- def resolve_input_type(root: models.AttributeValue, info: ResolveInfo):+ def resolve_input_type(+ root: ChannelContext[models.AttributeValue], info: ResolveInfo+ ):+ attr_value = root.nodereturn (AttributesByAttributeId(info.context)- .load(root.attribute_id)+ .load(attr_value.attribute_id).then(lambda attribute: attribute.input_type))@staticmethod- def resolve_file(root: models.AttributeValue, _info: ResolveInfo) -> None | File:- if not root.file_url:+ def resolve_file(+ root: ChannelContext[models.AttributeValue], _info: ResolveInfo+ ) -> None | File:+ attr_value = root.node+ if not attr_value.file_url:return None- return File(url=root.file_url, content_type=root.content_type)+ return File(url=attr_value.file_url, content_type=attr_value.content_type)@staticmethod- def resolve_reference(root: models.AttributeValue, info: ResolveInfo):+ def resolve_reference(+ root: ChannelContext[models.AttributeValue], info: ResolveInfo+ ):+ attr_value = root.node+def prepare_reference(attribute) -> None | str:- reference_pk = get_reference_pk(attribute, root)+ reference_pk = get_reference_pk(attribute, attr_value)if reference_pk is None:return Nonereturn graphene.Node.to_global_id(attribute.entity_type, reference_pk)return (AttributesByAttributeId(info.context)- .load(root.attribute_id)+ .load(attr_value.attribute_id).then(prepare_reference))@staticmethod- def resolve_date_time(root: models.AttributeValue, info: ResolveInfo):+ def resolve_date_time(+ root: ChannelContext[models.AttributeValue], info: ResolveInfo+ ):+ attr_value = root.node+def _resolve_date(attribute):if attribute.input_type == AttributeInputType.DATE_TIME:- return root.date_time+ return attr_value.date_timereturn Nonereturn (AttributesByAttributeId(info.context)- .load(root.attribute_id)+ .load(attr_value.attribute_id).then(_resolve_date))@staticmethod- def resolve_date(root: models.AttributeValue, info: ResolveInfo):+ def resolve_date(root: ChannelContext[models.AttributeValue], info: ResolveInfo):+ attr_value = root.node+def _resolve_date(attribute):if attribute.input_type == AttributeInputType.DATE:- return root.date_time+ return attr_value.date_timereturn Nonereturn (AttributesByAttributeId(info.context)- .load(root.attribute_id)+ .load(attr_value.attribute_id).then(_resolve_date))@@ -196,7 +222,7 @@ class AttributeValueCountableConnection(CountableConnection):node = AttributeValue-class Attribute(ModelObjectType[models.Attribute]):+class Attribute(ChannelContextType[models.Attribute]):id = graphene.GlobalID(required=True, description="The ID of the attribute.")input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)entity_type = AttributeEntityTypeEnum(@@ -279,7 +305,11 @@ class Attribute(ModelObjectType[models.Attribute]):required=True,deprecation_reason=DEFAULT_DEPRECATION_REASON,)- translation = TranslationField(AttributeTranslation, type_name="attribute")+ translation = TranslationField(+ AttributeTranslation,+ type_name="attribute",+ resolver=ChannelContextType.resolve_translation,+ )with_choices = graphene.Boolean(description=AttributeDescriptions.WITH_CHOICES, required=True)@@ -304,6 +334,7 @@ class Attribute(ModelObjectType[models.Attribute]):)class Meta:+ default_resolver = ChannelContextType.resolver_with_contextdescription = ("Custom attribute of a product. Attributes can be assigned to products and ""variants at the product type level."@@ -312,67 +343,89 @@ class Attribute(ModelObjectType[models.Attribute]):model = models.Attribute@staticmethod- def resolve_choices(root: models.Attribute, info: ResolveInfo, **kwargs):- if root.input_type in AttributeInputType.TYPES_WITH_CHOICES:- qs = root.values.using(get_database_connection_name(info.context)).all()+ def resolve_choices(+ root: ChannelContext[models.Attribute], info: ResolveInfo, **kwargs+ ):+ attr = root.node+ if attr.input_type in AttributeInputType.TYPES_WITH_CHOICES:+ qs = attr.values.using(get_database_connection_name(info.context)).all()else:qs = models.AttributeValue.objects.none()- qs = filter_connection_queryset(- qs, kwargs, allow_replica=info.context.allow_replica+ channel_context_qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)+ channel_context_qs = filter_connection_queryset(+ channel_context_qs, kwargs, allow_replica=info.context.allow_replica)return create_connection_slice(- qs, info, kwargs, AttributeValueCountableConnection+ channel_context_qs, info, kwargs, AttributeValueCountableConnection)@staticmethod@check_attribute_required_permissions()- def resolve_value_required(root: models.Attribute, _info: ResolveInfo):- return root.value_required+ def resolve_value_required(+ root: ChannelContext[models.Attribute], _info: ResolveInfo+ ):+ return root.node.value_required@staticmethod@check_attribute_required_permissions()- def resolve_visible_in_storefront(root: models.Attribute, _info: ResolveInfo):- return root.visible_in_storefront+ def resolve_visible_in_storefront(+ root: ChannelContext[models.Attribute], _info: ResolveInfo+ ):+ return root.node.visible_in_storefront@staticmethod@check_attribute_required_permissions()- def resolve_filterable_in_storefront(root: models.Attribute, _info: ResolveInfo):- return root.filterable_in_storefront+ def resolve_filterable_in_storefront(+ root: ChannelContext[models.Attribute], _info: ResolveInfo+ ):+ return root.node.filterable_in_storefront@staticmethod@check_attribute_required_permissions()- def resolve_filterable_in_dashboard(root: models.Attribute, _info: ResolveInfo):- return root.filterable_in_dashboard+ def resolve_filterable_in_dashboard(+ root: ChannelContext[models.Attribute], _info: ResolveInfo+ ):+ return root.node.filterable_in_dashboard@staticmethod@check_attribute_required_permissions()- def resolve_storefront_search_position(root: models.Attribute, _info: ResolveInfo):- return root.storefront_search_position+ def resolve_storefront_search_position(+ root: ChannelContext[models.Attribute], _info: ResolveInfo+ ):+ return root.node.storefront_search_position@staticmethod@check_attribute_required_permissions()- def resolve_available_in_grid(root: models.Attribute, _info: ResolveInfo):- return root.available_in_grid+ def resolve_available_in_grid(+ root: ChannelContext[models.Attribute], _info: ResolveInfo+ ):+ return root.node.available_in_grid@staticmethod- def resolve_with_choices(root: models.Attribute, _info: ResolveInfo):- return root.input_type in AttributeInputType.TYPES_WITH_CHOICES+ def resolve_with_choices(+ root: ChannelContext[models.Attribute], _info: ResolveInfo+ ):+ return root.node.input_type in AttributeInputType.TYPES_WITH_CHOICES@staticmethod- def resolve_product_types(root: models.Attribute, info: ResolveInfo, **kwargs):+ def resolve_product_types(+ root: ChannelContext[models.Attribute], info: ResolveInfo, **kwargs+ ):from ..product.types import ProductTypeCountableConnection- qs = root.product_types.using(get_database_connection_name(info.context)).all()+ qs = root.node.product_types.using(+ get_database_connection_name(info.context)+ ).all()return create_connection_slice(qs, info, kwargs, ProductTypeCountableConnection)@staticmethoddef resolve_product_variant_types(- root: models.Attribute, info: ResolveInfo, **kwargs+ root: ChannelContext[models.Attribute], info: ResolveInfo, **kwargs):from ..product.types import ProductTypeCountableConnection- qs = root.product_variant_types.using(+ qs = root.node.product_variant_types.using(get_database_connection_name(info.context)).all()return create_connection_slice(qs, info, kwargs, ProductTypeCountableConnection)@@ -405,7 +458,7 @@ class AssignedVariantAttribute(BaseObjectType):doc_category = DOC_CATEGORY_ATTRIBUTES-class SelectedAttribute(BaseObjectType):+class SelectedAttribute(ChannelContextTypeForObjectType):attribute = graphene.Field(Attribute,default_value=None,diff --git a/saleor/graphql/core/context.py b/saleor/graphql/core/context.pyindex 19850f061a..81305c1611 100644--- a/saleor/graphql/core/context.py+++ b/saleor/graphql/core/context.py@@ -4,7 +4,6 @@ from typing import TYPE_CHECKING, Any, Generic, TypeVarfrom django.conf import settingsfrom django.db.models import QuerySet-from django.db.models.base import Modelfrom django.http import HttpRequestfrom django.utils.functional import empty@@ -85,11 +84,8 @@ class SyncWebhookControlContext(BaseContext[N]):self.allow_sync_webhooks = allow_sync_webhooks-C = TypeVar("C", bound=Model)--@dataclass-class ChannelContext(BaseContext[C]):+class ChannelContext(BaseContext[N]):channel_slug: str | Nonediff --git a/saleor/graphql/core/types/context.py b/saleor/graphql/core/types/context.pyindex 0daa5ef243..25fc162b9e 100644--- a/saleor/graphql/core/types/context.py+++ b/saleor/graphql/core/types/context.py@@ -1,4 +1,4 @@-from typing import TypeVar, cast+from typing import Generic, TypeVar, castfrom django.db.models import Modelfrom graphene.types.resolver import get_default_resolver@@ -6,12 +6,13 @@ from graphene.types.resolver import get_default_resolverfrom ...translations.resolvers import resolve_translationfrom .. import ResolveInfofrom ..context import ChannelContext+from .base import BaseObjectTypefrom .model import ModelObjectType-T = TypeVar("T", bound=Model)+N = TypeVar("N", bound=Model)-class ChannelContextTypeForObjectType(ModelObjectType[T]):+class ChannelContextTypeForObjectType(Generic[N], BaseObjectType):"""A Graphene type that supports resolvers' root as ChannelContext objects."""class Meta:@@ -19,29 +20,32 @@ class ChannelContextTypeForObjectType(ModelObjectType[T]):@staticmethoddef resolver_with_context(- attname, default_value, root: ChannelContext, info: ResolveInfo, **args+ attname, default_value, root: ChannelContext[N], info: ResolveInfo, **args):resolver = get_default_resolver()return resolver(attname, default_value, root.node, info, **args)- @staticmethod- def resolve_id(root: ChannelContext[T], _info: ResolveInfo):- return root.node.pk-@staticmethoddef resolve_translation(- root: ChannelContext[T], info: ResolveInfo, *, language_code+ root: ChannelContext[N], info: ResolveInfo, *, language_code):# Resolver for TranslationField; needs to be manually specified.return resolve_translation(root.node, info, language_code=language_code)-class ChannelContextType(ChannelContextTypeForObjectType[T]):+T = TypeVar("T", bound=Model)+++class ChannelContextType(ChannelContextTypeForObjectType[T], ModelObjectType[T]):"""A Graphene type that supports resolvers' root as ChannelContext objects."""class Meta:abstract = True+ @staticmethod+ def resolve_id(root: ChannelContext[T], _info: ResolveInfo):+ return root.node.pk+@classmethoddef is_type_of(cls, root: ChannelContext[T] | T, _info: ResolveInfo) -> bool:# Unwrap node from ChannelContext if it didn't happen already@@ -55,5 +59,4 @@ class ChannelContextType(ChannelContextTypeForObjectType[T]):model = root._meta.modelelse:model = cast(type[Model], root._meta.model._meta.concrete_model)-return model == cls._meta.modeldiff --git a/saleor/graphql/decorators.py b/saleor/graphql/decorators.pyindex 07746e68ea..bfb4de0d6a 100644--- a/saleor/graphql/decorators.py+++ b/saleor/graphql/decorators.py@@ -5,6 +5,7 @@ from functools import wrapsfrom graphene import ResolveInfofrom ..attribute import AttributeType+from ..attribute.models import Attributefrom ..core.exceptions import PermissionDeniedfrom ..permission.auth_filters import is_app, is_staff_userfrom ..permission.enums import (@@ -19,6 +20,7 @@ from ..permission.utils import (one_of_permissions_or_auth_filter_required,)from ..permission.utils import permission_required as core_permission_required+from .core.context import ChannelContextfrom .utils import get_user_or_app_from_context@@ -119,7 +121,8 @@ def check_attribute_required_permissions():different permissions need to be checked."""- def check_perms(context, attribute):+ def check_perms(context, root: ChannelContext[Attribute]):+ attribute = root.noderequestor = get_user_or_app_from_context(context)permissions: list[BasePermissionEnum]if attribute.type == AttributeType.PAGE_TYPE:diff --git a/saleor/graphql/meta/mutations/base.py b/saleor/graphql/meta/mutations/base.pyindex f9c821e91d..4c0e880e1a 100644--- a/saleor/graphql/meta/mutations/base.py+++ b/saleor/graphql/meta/mutations/base.py@@ -2,6 +2,7 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom graphql.error.base import GraphQLError+from ....attribute import models as attribute_modelsfrom ....checkout import models as checkout_modelsfrom ....core import modelsfrom ....core.db.connection import allow_writer@@ -256,8 +257,11 @@ class BaseMetadataMutation(BaseMutation):| product_models.Product| product_models.ProductVariant| shipping_models.ShippingMethod- | shipping_models.ShippingZone,+ | shipping_models.ShippingZone+ | attribute_models.Attribute+ | attribute_models.AttributeValue,)+use_channel_context = use_channel_context or (# For old sales migrated into promotionsisinstance(instance, Promotion) and instance.old_sale_iddiff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.pyindex 054d7c4bf8..7553a1c6cc 100644--- a/saleor/graphql/page/types.py+++ b/saleor/graphql/page/types.py@@ -15,7 +15,11 @@ from ..core.connection import (create_connection_slice,filter_connection_queryset,)-from ..core.context import get_database_connection_name+from ..core.context import (+ ChannelContext,+ ChannelQsContext,+ get_database_connection_name,+)from ..core.descriptions import DEPRECATED_IN_3X_INPUT, RICH_CONTENTfrom ..core.doc_category import DOC_CATEGORY_PAGESfrom ..core.federation import federated_entity, resolve_federation_references@@ -85,15 +89,24 @@ class PageType(ModelObjectType[models.PageType]):@staticmethoddef resolve_attributes(root: models.PageType, info: ResolveInfo):+ def wrap_with_channel_context(attributes):+ return [ChannelContext(attribute, None) for attribute in attributes]+requestor = get_user_or_app_from_context(info.context)if (requestorand requestor.is_activeand requestor.has_perm(PagePermissions.MANAGE_PAGES)):- return PageAttributesAllByPageTypeIdLoader(info.context).load(root.pk)- return PageAttributesVisibleInStorefrontByPageTypeIdLoader(info.context).load(- root.pk+ return (+ PageAttributesAllByPageTypeIdLoader(info.context)+ .load(root.pk)+ .then(wrap_with_channel_context)+ )+ return (+ PageAttributesVisibleInStorefrontByPageTypeIdLoader(info.context)+ .load(root.pk)+ .then(wrap_with_channel_context))@staticmethod@@ -108,6 +121,7 @@ class PageType(ModelObjectType[models.PageType]):)if search:qs = filter_attribute_search(qs, None, search)+ qs = ChannelQsContext(qs=qs, channel_slug=None)return create_connection_slice(qs, info, kwargs, AttributeCountableConnection)@staticmethod@@ -200,31 +214,68 @@ class Page(ModelObjectType[models.Page]):@staticmethoddef resolve_attributes(root: models.Page, info: ResolveInfo):+ def wrap_with_channel_context(+ attributes: list[dict[str, list]] | None,+ ) -> list[SelectedAttribute] | None:+ if attributes is None:+ return None+ return [+ SelectedAttribute(+ attribute=ChannelContext(attribute["attribute"], None),+ values=[+ ChannelContext(value, None) for value in attribute["values"]+ ],+ )+ for attribute in attributes+ ]+requestor = get_user_or_app_from_context(info.context)if (requestorand requestor.is_activeand requestor.has_perm(PagePermissions.MANAGE_PAGES)):- return SelectedAttributesAllByPageIdLoader(info.context).load(root.id)- return SelectedAttributesVisibleInStorefrontPageIdLoader(info.context).load(- root.id+ return (+ SelectedAttributesAllByPageIdLoader(info.context)+ .load(root.id)+ .then(wrap_with_channel_context)+ )+ return (+ SelectedAttributesVisibleInStorefrontPageIdLoader(info.context)+ .load(root.id)+ .then(wrap_with_channel_context))@staticmethoddef resolve_attribute(root: models.Page, info: ResolveInfo, slug: str):+ def wrap_with_channel_context(+ attribute_data: dict[str, dict | list[dict]] | None,+ ) -> SelectedAttribute | None:+ if attribute_data is None:+ return None+ return SelectedAttribute(+ attribute=ChannelContext(attribute_data["attribute"], None),+ values=[+ ChannelContext(value, None) for value in attribute_data["values"]+ ],+ )+requestor = get_user_or_app_from_context(info.context)if (requestorand requestor.is_activeand requestor.has_perm(PagePermissions.MANAGE_PAGES)):- return SelectedAttributeAllByPageIdAttributeSlugLoader(info.context).load(- (root.id, slug)+ return (+ SelectedAttributeAllByPageIdAttributeSlugLoader(info.context)+ .load((root.id, slug))+ .then(wrap_with_channel_context))- return SelectedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(- info.context- ).load((root.id, slug))+ return (+ SelectedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(info.context)+ .load((root.id, slug))+ .then(wrap_with_channel_context)+ )class PageCountableConnection(CountableConnection):diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 663f5464d6..a73a5d51c5 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -2,6 +2,7 @@ import sysfrom collections import defaultdictfrom dataclasses import asdictfrom decimal import Decimal+from typing import castimport graphenefrom graphene import relay@@ -584,27 +585,55 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):info,variant_selection: str | None = None,):- def apply_variant_selection_filter(selected_attributes):+ def apply_variant_selection_filter(+ selected_attributes,+ ) -> list[SelectedAttribute]:if not variant_selection or variant_selection == VariantAttributeScope.ALL:- return selected_attributes+ return [+ SelectedAttribute(+ 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:- return [- selected_attribute- for selected_attribute in selected_attributes- if selected_attribute["attribute"] in variant_selection_attrs+ 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+ ]+return [- selected_attribute- for selected_attribute in selected_attributes- if selected_attribute["attribute"] not in variant_selection_attrs+ SelectedAttribute(+ 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 (@@ -1303,12 +1332,33 @@ class Product(ChannelContextType[models.Product]):@staticmethoddef resolve_attribute(root: ChannelContext[models.Product], info, slug):def get_selected_attribute_by_slug(- attributes: list[SelectedAttribute],+ attributes: (+ list[+ dict[+ str,+ attribute_models.Attribute+ | list[attribute_models.AttributeValue],+ ]+ ]+ | None+ ),) -> SelectedAttribute | None:- return next(- (atr for atr in attributes if atr["attribute"].slug == slug),- 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 SelectedAttribute(+ attribute=ChannelContext(attribute, root.channel_slug),+ values=[+ ChannelContext(value, root.channel_slug) for value in values+ ],+ )+ return Nonerequestor = get_user_or_app_from_context(info.context)if (@@ -1329,18 +1379,53 @@ class Product(ChannelContextType[models.Product]):@staticmethoddef resolve_attributes(root: ChannelContext[models.Product], info):+ def wrap_with_channel_context(+ attributes: (+ list[+ dict[+ str,+ attribute_models.Attribute+ | list[attribute_models.AttributeValue],+ ]+ ]+ | None+ ),+ ) -> list[SelectedAttribute] | 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(+ SelectedAttribute(+ attribute=ChannelContext(attribute, root.channel_slug),+ values=[+ ChannelContext(value, root.channel_slug) for value in values+ ],+ )+ )+ return response+requestor = get_user_or_app_from_context(info.context)if (requestorand requestor.is_activeand requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)):- return SelectedAttributesAllByProductIdLoader(info.context).load(- root.node.id+ return (+ SelectedAttributesAllByProductIdLoader(info.context)+ .load(root.node.id)+ .then(wrap_with_channel_context))- return SelectedAttributesVisibleInStorefrontByProductIdLoader(- info.context- ).load(root.node.id)+ return (+ SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)+ .load(root.node.id)+ .then(wrap_with_channel_context)+ )@staticmethoddef resolve_media_by_id(root: ChannelContext[models.Product], info, *, id):@@ -1787,7 +1872,7 @@ class ProductType(ModelObjectType[models.ProductType]):@staticmethoddef resolve_product_attributes(root: models.ProductType, info):def unpack_attributes(attributes):- return [attr for attr, *_ in attributes]+ return [ChannelContext(attr, None) for attr, *_ in attributes]requestor = get_user_or_app_from_context(info.context)if (@@ -1815,12 +1900,14 @@ class ProductType(ModelObjectType[models.ProductType]):):def apply_variant_selection_filter(attributes):if not variant_selection or variant_selection == VariantAttributeScope.ALL:- return [attr for attr, *_ in attributes]+ return [ChannelContext(attr, None) for attr, *_ in attributes]variant_selection_attrs = get_variant_selection_attributes(attributes)if variant_selection == VariantAttributeScope.VARIANT_SELECTION:- return [attr for attr, *_ in variant_selection_attrs]+ return [+ ChannelContext(attr, None) for attr, *_ in variant_selection_attrs+ ]return [- attr+ ChannelContext(attr, None)for attr, variant_selection in attributesif (attr, variant_selection) not in variant_selection_attrs]@@ -1852,17 +1939,26 @@ class ProductType(ModelObjectType[models.ProductType]):def apply_variant_selection_filter(attributes):if not variant_selection or variant_selection == VariantAttributeScope.ALL:return [- {"attribute": attr, "variant_selection": variant_selection}+ {+ "attribute": ChannelContext(attr, None),+ "variant_selection": variant_selection,+ }for attr, variant_selection in attributes]variant_selection_attrs = get_variant_selection_attributes(attributes)if variant_selection == VariantAttributeScope.VARIANT_SELECTION:return [- {"attribute": attr, "variant_selection": variant_selection}+ {+ "attribute": ChannelContext(attr, None),+ "variant_selection": variant_selection,+ }for attr, variant_selection in variant_selection_attrs]return [- {"attribute": attr, "variant_selection": variant_selection}+ {+ "attribute": ChannelContext(attr, None),+ "variant_selection": variant_selection,+ }for attr, variant_selection in attributesif (attr, variant_selection) not in variant_selection_attrs]@@ -1922,6 +2018,7 @@ class ProductType(ModelObjectType[models.ProductType]):)if search:qs = filter_attribute_search(qs, None, search)+ qs = ChannelQsContext(qs=qs, channel_slug=None)return create_connection_slice(qs, info, kwargs, AttributeCountableConnection)@staticmethoddiff --git a/saleor/graphql/translations/mutations/attribute_translate.py b/saleor/graphql/translations/mutations/attribute_translate.pyindex 9fb78ad258..2bd48c6c23 100644--- a/saleor/graphql/translations/mutations/attribute_translate.py+++ b/saleor/graphql/translations/mutations/attribute_translate.py@@ -3,6 +3,7 @@ import graphenefrom ....attribute import models as attribute_modelsfrom ....permission.enums import SitePermissionsfrom ...attribute.types import Attribute+from ...core.context import ChannelContextfrom ...core.enums import LanguageCodeEnumfrom ...core.types import TranslationErrorfrom .utils import BaseTranslateMutation, NameTranslationInput@@ -29,3 +30,9 @@ class AttributeTranslate(BaseTranslateMutation):error_type_class = TranslationErrorerror_type_field = "translation_errors"permissions = (SitePermissions.MANAGE_TRANSLATIONS,)++ @classmethod+ def perform_mutation(cls, *args, **kwargs):+ response = super().perform_mutation(*args, **kwargs)+ response.attribute = ChannelContext(response.attribute, None)+ return responsediff --git a/saleor/graphql/translations/mutations/attribute_value_translate.py b/saleor/graphql/translations/mutations/attribute_value_translate.pyindex 171d4fdc83..9bccbf6944 100644--- a/saleor/graphql/translations/mutations/attribute_value_translate.py+++ b/saleor/graphql/translations/mutations/attribute_value_translate.py@@ -6,6 +6,7 @@ from ....attribute import models as attribute_modelsfrom ....core.utils.editorjs import clean_editor_jsfrom ....permission.enums import SitePermissionsfrom ...attribute.types import AttributeValue+from ...core.context import ChannelContextfrom ...core.descriptions import RICH_CONTENTfrom ...core.enums import LanguageCodeEnumfrom ...core.fields import JSONString@@ -50,3 +51,9 @@ class AttributeValueTranslate(BaseTranslateMutation):elif instance.attribute.input_type == AttributeInputType.PLAIN_TEXT:input_data["name"] = truncatechars(input_data["plain_text"], 250)return input_data++ @classmethod+ def perform_mutation(cls, *args, **kwargs):+ response = super().perform_mutation(*args, **kwargs)+ response.attributeValue = ChannelContext(response.attributeValue, None)+ return responsediff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.pyindex 8e73ab6118..b62e507a1f 100644--- a/saleor/graphql/translations/types.py+++ b/saleor/graphql/translations/types.py@@ -21,11 +21,7 @@ from ...shipping import models as shipping_modelsfrom ...site import models as site_modelsfrom ..attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdLoaderfrom ..core.context import ChannelContext, get_database_connection_name-from ..core.descriptions import (- ADDED_IN_321,- DEPRECATED_IN_3X_TYPE,- RICH_CONTENT,-)+from ..core.descriptions import ADDED_IN_321, DEPRECATED_IN_3X_TYPE, RICH_CONTENTfrom ..core.enums import LanguageCodeEnumfrom ..core.fields import JSONString, PermissionsFieldfrom ..core.tracing import traced_resolver@@ -173,7 +169,7 @@ class AttributeTranslatableContent(ModelObjectType[attribute_models.Attribute]):@staticmethoddef resolve_attribute(root: attribute_models.Attribute, _info):- return root+ return ChannelContext(node=root, channel_slug=None)@staticmethoddef resolve_attribute_id(root: attribute_models.Attribute, _info):@@ -219,7 +215,7 @@ class AttributeValueTranslatableContent(@staticmethoddef resolve_attribute_value(root: attribute_models.AttributeValue, _info):- return root+ return ChannelContext(node=root, channel_slug=None)@staticmethoddef resolve_attribute(root: attribute_models.AttributeValue, info):diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex cb0bc1b3bc..75db47d2cd 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -360,7 +360,7 @@ class AttributeBase(AbstractType):@staticmethoddef resolve_attribute(root, _info: ResolveInfo):_, attribute = root- return attribute+ return ChannelContext(attribute, None)class AttributeCreated(SubscriptionObjectType, AttributeBase):@@ -395,8 +395,8 @@ class AttributeValueBase(AbstractType):@staticmethoddef resolve_attribute_value(root, _info: ResolveInfo):- _, attribute = root- return attribute+ _, attribute_value = root+ return ChannelContext(attribute_value, None)class AttributeValueCreated(SubscriptionObjectType, AttributeValueBase):