Skip to content

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

Introduce `AssignedAttribute` as a replacement for `SelectedAttribute` (#18067)

Maciej Korycinskif7a1563b85bc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e7dc29220..b97e25faad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -94,6 +94,10 @@ Like `reference`, the `single-reference` type can target entities defined in the
- Added support for filtering by associated reference objects (e.g., `products`, `pages`, `variants`)
- Added `fractionalAmount` and `fractionDigits` fields to the `Money` type. These fields allow monetary values to be represented as a pair of integers, which is often required when integrating with payment service providers.
- Add support for filtering `productVariants` by associated attributes
+- You can now use the `AssignedAttribute` interface and the `assignedAttribute`, `assignedAttributes` fields on `Page`, `Product`, and `ProductVariant` to fetch assigned attributes and their values in a cleaner, more focused shape.
+ - `attribute` and `attributes` fields on Page, Product, and ProductVariant are deprecated.
+
+
### Webhooks
- Transaction webhooks responsible for processing payments can now return payment method details`, which will be associated with the corresponding transaction. See [docs](https://docs.saleor.io/developer/extending/webhooks/synchronous-events/transaction#response-4) to learn more.
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index d1322bc736..50791968a7 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -20,6 +20,7 @@ from ..graphql.notifications.schema import ExternalNotificationMutations
from .account.schema import AccountMutations, AccountQueries
from .app.schema import AppMutations, AppQueries
from .attribute.schema import AttributeMutations, AttributeQueries
+from .attribute.types import ASSIGNED_ATTRIBUTE_TYPES
from .channel.schema import ChannelMutations, ChannelQueries
from .checkout.schema import CheckoutMutations, CheckoutQueries
from .core.enums import unit_enums
@@ -123,6 +124,7 @@ GraphQLDocDirective = graphql.GraphQLDirective(
graphql.DirectiveLocation.FIELD_DEFINITION,
graphql.DirectiveLocation.INPUT_OBJECT,
graphql.DirectiveLocation.OBJECT,
+ graphql.DirectiveLocation.INTERFACE,
],
)
@@ -176,7 +178,12 @@ GraphQLWebhookEventsInfoDirective = graphql.GraphQLDirective(
schema = build_federated_schema(
Query,
mutation=Mutation,
- types=unit_enums + list(WEBHOOK_TYPES_MAP.values()) + PAYMENT_ADDITIONAL_TYPES,
+ types=(
+ unit_enums
+ + list(WEBHOOK_TYPES_MAP.values())
+ + PAYMENT_ADDITIONAL_TYPES
+ + ASSIGNED_ATTRIBUTE_TYPES
+ ),
subscription=Subscription,
directives=graphql.specified_directives
+ [GraphQLDocDirective, GraphQLWebhookEventsInfoDirective],
diff --git a/saleor/graphql/attribute/tests/queries/test_selected_attribute.py b/saleor/graphql/attribute/tests/queries/test_selected_attribute.py
index 687efe0581..9583343896 100644
--- a/saleor/graphql/attribute/tests/queries/test_selected_attribute.py
+++ b/saleor/graphql/attribute/tests/queries/test_selected_attribute.py
@@ -1,8 +1,16 @@
+from datetime import UTC, datetime
+
import graphene
-from .....attribute.models.base import AttributeValue
+from .....attribute import AttributeEntityType, AttributeInputType, AttributeType
+from .....attribute.models.base import AttributeValue, AttributeValueTranslation
from .....attribute.utils import associate_attribute_values_to_instance
from ....tests.utils import get_graphql_content
+from ...types import (
+ ASSIGNED_ATTRIBUTE_MAP,
+ ASSIGNED_MULTI_REFERENCE_MAP,
+ ASSIGNED_SINGLE_REFERENCE_MAP,
+)
PAGE_QUERY = """
query PageQuery($id: ID) {
@@ -138,3 +146,1583 @@ def test_attribute_value_name_when_referenced_page_was_changed(
assert len(content["data"]["page"]["attributes"][0]["values"]) == 1
data = content["data"]["page"]["attributes"][0]["values"][0]
assert data["name"] == new_page_title
+
+
+ASSIGNED_NUMERIC_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ... on AssignedNumericAttribute {
+ attribute {
+ id
+ }
+ value
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_numeric_attribute(staff_api_client, page, numeric_attribute):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([numeric_attribute])
+
+ attr_value = numeric_attribute.values.first()
+
+ associate_attribute_values_to_instance(page, {numeric_attribute.pk: [attr_value]})
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_NUMERIC_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"] == attr_value.numeric
+ )
+
+
+ASSIGNED_TEXT_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ...on AssignedTextAttribute{
+ value
+ translation(languageCode:FR)
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_text_attribute_translation(
+ staff_api_client,
+ page,
+ rich_text_attribute_page_type,
+ translated_page_unique_attribute_value,
+):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([rich_text_attribute_page_type])
+
+ attr_value = rich_text_attribute_page_type.values.first()
+ assert attr_value.id == translated_page_unique_attribute_value.attribute_value_id
+
+ associate_attribute_values_to_instance(
+ page, {rich_text_attribute_page_type.pk: [attr_value]}
+ )
+
+ assert attr_value.rich_text is not None
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_TEXT_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["translation"]
+ == translated_page_unique_attribute_value.rich_text
+ )
+
+
+def test_assigned_text_attribute(staff_api_client, page, rich_text_attribute):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([rich_text_attribute])
+
+ attr_value = rich_text_attribute.values.first()
+
+ associate_attribute_values_to_instance(page, {rich_text_attribute.pk: [attr_value]})
+
+ assert attr_value.rich_text is not None
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_TEXT_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"]
+ == attr_value.rich_text
+ )
+
+
+ASSIGNED_PLAIN_TEXT_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ...on AssignedPlainTextAttribute{
+ value
+ translation(languageCode:FR)
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_plain_text_attribute_translation(
+ staff_api_client,
+ page,
+ plain_text_attribute_page_type,
+ translated_page_unique_attribute_value,
+):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([plain_text_attribute_page_type])
+
+ attr_value = plain_text_attribute_page_type.values.first()
+ translation = AttributeValueTranslation.objects.create(
+ language_code="fr",
+ attribute_value=attr_value,
+ plain_text="French description.",
+ )
+
+ assert attr_value.id == translation.attribute_value_id
+
+ associate_attribute_values_to_instance(
+ page, {plain_text_attribute_page_type.pk: [attr_value]}
+ )
+
+ assert attr_value.plain_text is not None
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_PLAIN_TEXT_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["translation"]
+ == translation.plain_text
+ )
+
+
+def test_assigned_plain_text_attribute(staff_api_client, page, plain_text_attribute):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([plain_text_attribute])
+
+ attr_value = plain_text_attribute.values.first()
+
+ associate_attribute_values_to_instance(
+ page, {plain_text_attribute.pk: [attr_value]}
+ )
+
+ assert attr_value.plain_text is not None
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_PLAIN_TEXT_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"]
+ == attr_value.plain_text
+ )
+
+
+ASSIGNED_FILE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ...on AssignedFileAttribute{
+ value {
+ url
+ contentType
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_file_attribute(staff_api_client, page, file_attribute):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([file_attribute])
+
+ attr_value = file_attribute.values.first()
+ attr_value.file_url = "https://example.com/file.pdf"
+ attr_value.save()
+
+ associate_attribute_values_to_instance(page, {file_attribute.pk: [attr_value]})
+
+ assert attr_value.file_url is not None
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_FILE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"]["url"]
+ == attr_value.file_url
+ )
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"]["contentType"]
+ == attr_value.content_type
+ )
+
+
+ASSIGNED_SINGLE_PAGE_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ __typename
+ ...on AssignedSinglePageReferenceAttribute{
+ value{
+ __typename
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_single_page_reference_attribute(
+ staff_api_client,
+ page,
+ page_list,
+ page_type_page_reference_attribute,
+):
+ # given
+ referenced_page = page_list[0]
+ expected_reference_slug = "referenced-page-slug"
+ referenced_page.slug = expected_reference_slug
+ referenced_page.save(update_fields=["slug"])
+
+ page_type_page_reference_attribute.input_type = AttributeInputType.SINGLE_REFERENCE
+ page_type_page_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_page_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_page_reference_attribute,
+ name=referenced_page.title,
+ slug=f"{page.pk}_{referenced_page.pk}",
+ reference_page_id=referenced_page.pk,
+ )
+ associate_attribute_values_to_instance(
+ page, {page_type_page_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_SINGLE_PAGE_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert data["__typename"] == "Page"
+ assert data["slug"] == expected_reference_slug
+
+
+ASSIGNED_SINGLE_PRODUCT_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ __typename
+ ...on AssignedSingleProductReferenceAttribute{
+ value{
+ __typename
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_single_product_reference_attribute(
+ staff_api_client,
+ page,
+ product,
+ page_type_product_reference_attribute,
+):
+ # given
+ referenced_product = product
+ expected_reference_slug = "referenced-product-slug"
+ referenced_product.slug = expected_reference_slug
+ referenced_product.save(update_fields=["slug"])
+
+ page_type_product_reference_attribute.input_type = (
+ AttributeInputType.SINGLE_REFERENCE
+ )
+ page_type_product_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_product_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_product_reference_attribute,
+ slug=f"{page.pk}_{referenced_product.pk}",
+ reference_product_id=referenced_product.pk,
+ )
+ associate_attribute_values_to_instance(
+ page, {page_type_product_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_SINGLE_PRODUCT_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert data["__typename"] == "Product"
+ assert data["slug"] == expected_reference_slug
+
+
+ASSIGNED_SINGLE_PRODUCT_VARIANT_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ __typename
+ ...on AssignedSingleProductVariantReferenceAttribute{
+ value{
+ __typename
+ sku
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_single_product_variant_reference_attribute(
+ staff_api_client,
+ page,
+ variant,
+ page_type_variant_reference_attribute,
+):
+ # given
+ referenced_variant = variant
+ expected_reference_sku = "referenced-variant-sku"
+ referenced_variant.sku = expected_reference_sku
+ referenced_variant.save(update_fields=["sku"])
+
+ page_type_variant_reference_attribute.input_type = (
+ AttributeInputType.SINGLE_REFERENCE
+ )
+ page_type_variant_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_variant_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_variant_reference_attribute,
+ slug=f"{page.pk}_{referenced_variant.pk}",
+ reference_variant_id=referenced_variant.pk,
+ )
+ associate_attribute_values_to_instance(
+ page, {page_type_variant_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_SINGLE_PRODUCT_VARIANT_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert data["__typename"] == "ProductVariant"
+ assert data["sku"] == expected_reference_sku
+
+
+ASSIGNED_SINGLE_CATEGORY_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ __typename
+ ...on AssignedSingleCategoryReferenceAttribute{
+ value{
+ __typename
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_single_category_reference_attribute(
+ staff_api_client,
+ page,
+ category,
+ page_type_category_reference_attribute,
+):
+ # given
+ referenced_category = category
+ expected_reference_slug = "referenced-category-slug"
+ referenced_category.slug = expected_reference_slug
+ referenced_category.save(update_fields=["slug"])
+
+ page_type_category_reference_attribute.input_type = (
+ AttributeInputType.SINGLE_REFERENCE
+ )
+ page_type_category_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_category_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_category_reference_attribute,
+ slug=f"{page.pk}_{referenced_category.pk}",
+ reference_category_id=referenced_category.pk,
+ )
+ associate_attribute_values_to_instance(
+ page, {page_type_category_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_SINGLE_CATEGORY_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert data["__typename"] == "Category"
+ assert data["slug"] == expected_reference_slug
+
+
+ASSIGNED_SINGLE_COLLECTION_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ __typename
+ ...on AssignedSingleCollectionReferenceAttribute{
+ value{
+ __typename
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_single_collection_reference_attribute(
+ staff_api_client,
+ page,
+ collection,
+ page_type_collection_reference_attribute,
+):
+ # given
+ referenced_collection = collection
+ expected_reference_slug = "referenced-collection-slug"
+ referenced_collection.slug = expected_reference_slug
+ referenced_collection.save(update_fields=["slug"])
+
+ page_type_collection_reference_attribute.input_type = (
+ AttributeInputType.SINGLE_REFERENCE
+ )
+ page_type_collection_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_collection_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_collection_reference_attribute,
+ slug=f"{page.pk}_{referenced_collection.pk}",
+ reference_collection_id=referenced_collection.pk,
+ )
+ associate_attribute_values_to_instance(
+ page, {page_type_collection_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_SINGLE_COLLECTION_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert data["__typename"] == "Collection"
+ assert data["slug"] == expected_reference_slug
+
+
+ASSIGNED_MULTIPLE_PAGE_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ...on AssignedMultiPageReferenceAttribute{
+ __typename
+ value{
+ __typename
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_multi_page_reference_attribute(
+ staff_api_client,
+ page,
+ page_list,
+ page_type_page_reference_attribute,
+):
+ # given
+ referenced_page = page_list[0]
+ expected_reference_slug = "referenced-page-slug"
+ referenced_page.slug = expected_reference_slug
+ referenced_page.save(update_fields=["slug"])
+
+ page_type_page_reference_attribute.input_type = AttributeInputType.REFERENCE
+ page_type_page_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_page_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_page_reference_attribute,
+ name=referenced_page.title,
+ slug=f"{page.pk}_{referenced_page.pk}",
+ reference_page_id=referenced_page.pk,
+ )
+ associate_attribute_values_to_instance(
+ page, {page_type_page_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTIPLE_PAGE_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert len(data) == 1
+ single_page_data = data[0]
+ assert single_page_data["__typename"] == "Page"
+ assert single_page_data["slug"] == expected_reference_slug
+
+
+ASSIGNED_MULTIPLE_PRODUCT_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID, $valueLimit: PositiveInt) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ...on AssignedMultiProductReferenceAttribute{
+ __typename
+ value(limit: $valueLimit) {
+ __typename
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_multi_product_reference_attribute(
+ staff_api_client,
+ page,
+ product,
+ page_type_product_reference_attribute,
+):
+ # given
+ referenced_product = product
+ expected_reference_slug = "referenced-product-slug"
+ referenced_product.slug = expected_reference_slug
+ referenced_product.save(update_fields=["slug"])
+
+ page_type_product_reference_attribute.input_type = AttributeInputType.REFERENCE
+ page_type_product_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_product_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_product_reference_attribute,
+ slug=f"{page.pk}_{referenced_product.pk}",
+ reference_product_id=referenced_product.pk,
+ )
+
+ associate_attribute_values_to_instance(
+ page, {page_type_product_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTIPLE_PRODUCT_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert len(data) == 1
+ single_page_data = data[0]
+ assert single_page_data["__typename"] == "Product"
+ assert single_page_data["slug"] == expected_reference_slug
+
+
+def test_applies_limit_to_multi_product_references(
+ staff_api_client,
+ page,
+ product_list,
+ page_type_product_reference_attribute,
+):
+ # given
+ page_type = page.page_type
+
+ # make sure that our attribute is on first position
+ page_type.page_attributes.update(storefront_search_position=10)
+ page_type.page_attributes.set([page_type_product_reference_attribute])
+ page_type_product_reference_attribute.input_type = AttributeInputType.REFERENCE
+ page_type_product_reference_attribute.storefront_search_position = 1
+ page_type_product_reference_attribute.save()
+
+ first_reference = AttributeValue.objects.create(
+ attribute=page_type_product_reference_attribute,
+ slug=f"{page.pk}_{product_list[0].pk}",
+ reference_product_id=product_list[0].pk,
+ )
+ second_reference = AttributeValue.objects.create(
+ attribute=page_type_product_reference_attribute,
+ slug=f"{page.pk}_{product_list[1].pk}",
+ reference_product_id=product_list[1].pk,
+ )
+
+ associate_attribute_values_to_instance(
+ page,
+ {page_type_product_reference_attribute.pk: [first_reference, second_reference]},
+ )
+ assert page.attributevalues.count() == 3
+
+ expected_value_limit = 1
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTIPLE_PRODUCT_REFERENCE_ATTRIBUTE_QUERY,
+ variables={
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "valueLimit": expected_value_limit,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ len(content["data"]["page"]["assignedAttributes"][0]["value"])
+ == expected_value_limit
+ )
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"][0]["slug"]
+ == first_reference.reference_product.slug
+ )
+
+
+ASSIGNED_MULTIPLE_PRODUCT_VARIANT_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID, $valueLimit: PositiveInt) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ...on AssignedMultiProductVariantReferenceAttribute{
+ __typename
+ value(limit: $valueLimit) {
+ __typename
+ sku
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_multi_product_variant_reference_attribute(
+ staff_api_client,
+ page,
+ variant,
+ page_type_variant_reference_attribute,
+):
+ # given
+ referenced_variant = variant
+ expected_reference_sku = "referenced-variant-sku"
+ referenced_variant.sku = expected_reference_sku
+ referenced_variant.save(update_fields=["sku"])
+
+ page_type_variant_reference_attribute.input_type = AttributeInputType.REFERENCE
+ page_type_variant_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_variant_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_variant_reference_attribute,
+ slug=f"{page.pk}_{referenced_variant.pk}",
+ reference_variant_id=referenced_variant.pk,
+ )
+
+ associate_attribute_values_to_instance(
+ page, {page_type_variant_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTIPLE_PRODUCT_VARIANT_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert len(data) == 1
+ single_page_data = data[0]
+ assert single_page_data["__typename"] == "ProductVariant"
+ assert single_page_data["sku"] == expected_reference_sku
+
+
+def test_applies_limit_to_multi_variant_references(
+ staff_api_client,
+ page,
+ product_variant_list,
+ page_type_variant_reference_attribute,
+):
+ # given
+ page_type = page.page_type
+
+ # make sure that our attribute is on first position
+ page_type.page_attributes.update(storefront_search_position=10)
+ page_type.page_attributes.set([page_type_variant_reference_attribute])
+ page_type_variant_reference_attribute.storefront_search_position = 1
+ page_type_variant_reference_attribute.input_type = AttributeInputType.REFERENCE
+ page_type_variant_reference_attribute.save()
+
+ first_reference = AttributeValue.objects.create(
+ attribute=page_type_variant_reference_attribute,
+ slug=f"{page.pk}_{product_variant_list[0].pk}",
+ reference_variant_id=product_variant_list[0].pk,
+ )
+ second_reference = AttributeValue.objects.create(
+ attribute=page_type_variant_reference_attribute,
+ slug=f"{page.pk}_{product_variant_list[1].pk}",
+ reference_variant_id=product_variant_list[1].pk,
+ )
+
+ associate_attribute_values_to_instance(
+ page,
+ {page_type_variant_reference_attribute.pk: [first_reference, second_reference]},
+ )
+
+ assert page.attributevalues.count() == 3
+ expected_value_limit = 1
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTIPLE_PRODUCT_VARIANT_REFERENCE_ATTRIBUTE_QUERY,
+ variables={
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "valueLimit": expected_value_limit,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ len(content["data"]["page"]["assignedAttributes"][0]["value"])
+ == expected_value_limit
+ )
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"][0]["sku"]
+ == first_reference.reference_variant.sku
+ )
+
+
+ASSIGNED_MULTIPLE_CATEGORY_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID, $valueLimit: PositiveInt) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ...on AssignedMultiCategoryReferenceAttribute{
+ __typename
+ value(limit: $valueLimit) {
+ __typename
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_multi_category_reference_attribute(
+ staff_api_client,
+ page,
+ category,
+ page_type_category_reference_attribute,
+):
+ # given
+ referenced_category = category
+ expected_reference_slug = "referenced-category-slug"
+ referenced_category.slug = expected_reference_slug
+ referenced_category.save(update_fields=["slug"])
+
+ page_type_category_reference_attribute.input_type = AttributeInputType.REFERENCE
+ page_type_category_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_category_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_category_reference_attribute,
+ slug=f"{page.pk}_{referenced_category.pk}",
+ reference_category_id=referenced_category.pk,
+ )
+
+ associate_attribute_values_to_instance(
+ page, {page_type_category_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTIPLE_CATEGORY_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert len(data) == 1
+ single_page_data = data[0]
+ assert single_page_data["__typename"] == "Category"
+ assert single_page_data["slug"] == expected_reference_slug
+
+
+def test_applies_limit_to_multi_category_references(
+ staff_api_client,
+ page,
+ categories,
+ page_type_category_reference_attribute,
+):
+ # given
+ page_type = page.page_type
+
+ # make sure that our attribute is on first position
+ page_type.page_attributes.update(storefront_search_position=10)
+ page_type.page_attributes.set([page_type_category_reference_attribute])
+ page_type_category_reference_attribute.input_type = AttributeInputType.REFERENCE
+ page_type_category_reference_attribute.storefront_search_position = 1
+ page_type_category_reference_attribute.save()
+
+ first_reference = AttributeValue.objects.create(
+ attribute=page_type_category_reference_attribute,
+ slug=f"{page.pk}_{categories[0].pk}",
+ reference_category_id=categories[0].pk,
+ )
+ second_reference = AttributeValue.objects.create(
+ attribute=page_type_category_reference_attribute,
+ slug=f"{page.pk}_{categories[1].pk}",
+ reference_category_id=categories[1].pk,
+ )
+
+ associate_attribute_values_to_instance(
+ page,
+ {
+ page_type_category_reference_attribute.pk: [
+ first_reference,
+ second_reference,
+ ]
+ },
+ )
+
+ assert page.attributevalues.count() == 3
+ expected_value_limit = 1
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTIPLE_CATEGORY_REFERENCE_ATTRIBUTE_QUERY,
+ variables={
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "valueLimit": expected_value_limit,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ len(content["data"]["page"]["assignedAttributes"][0]["value"])
+ == expected_value_limit
+ )
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"][0]["slug"]
+ == first_reference.reference_category.slug
+ )
+
+
+ASSIGNED_MULTIPLE_COLLECTION_REFERENCE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID, $valueLimit: PositiveInt) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ...on AssignedMultiCollectionReferenceAttribute{
+ __typename
+ value(limit: $valueLimit) {
+ __typename
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_multi_collection_reference_attribute(
+ staff_api_client,
+ page,
+ collection,
+ page_type_collection_reference_attribute,
+):
+ # given
+ referenced_collection = collection
+ expected_reference_slug = "referenced-collection-slug"
+ referenced_collection.slug = expected_reference_slug
+ referenced_collection.save(update_fields=["slug"])
+
+ page_type_collection_reference_attribute.input_type = AttributeInputType.REFERENCE
+ page_type_collection_reference_attribute.save()
+ page_type = page.page_type
+ page_type.page_attributes.set([page_type_collection_reference_attribute])
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_collection_reference_attribute,
+ slug=f"{page.pk}_{referenced_collection.pk}",
+ reference_collection_id=referenced_collection.pk,
+ )
+
+ associate_attribute_values_to_instance(
+ page, {page_type_collection_reference_attribute.pk: [attr_value]}
+ )
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTIPLE_COLLECTION_REFERENCE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+
+ data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert len(data) == 1
+ single_page_data = data[0]
+ assert single_page_data["__typename"] == "Collection"
+ assert single_page_data["slug"] == expected_reference_slug
+
+
+def test_applies_limit_to_multi_collection_references(
+ staff_api_client,
+ page,
+ published_collections,
+ page_type_collection_reference_attribute,
+):
+ # given
+ page_type = page.page_type
+ # make sure that our attribute is on first position
+ page_type.page_attributes.update(storefront_search_position=10)
+ page_type.page_attributes.set([page_type_collection_reference_attribute])
+ page_type_collection_reference_attribute.input_type = AttributeInputType.REFERENCE
+ page_type_collection_reference_attribute.storefront_search_position = 1
+ page_type_collection_reference_attribute.save()
+
+ first_reference = AttributeValue.objects.create(
+ attribute=page_type_collection_reference_attribute,
+ slug=f"{page.pk}_{published_collections[0].pk}",
+ reference_collection_id=published_collections[0].pk,
+ )
+ second_reference = AttributeValue.objects.create(
+ attribute=page_type_collection_reference_attribute,
+ slug=f"{page.pk}_{published_collections[1].pk}",
+ reference_collection_id=published_collections[1].pk,
+ )
+
+ associate_attribute_values_to_instance(
+ page,
+ {
+ page_type_collection_reference_attribute.pk: [
+ first_reference,
+ second_reference,
+ ]
+ },
+ )
+
+ assert page.attributevalues.count() == 3
+ expected_value_limit = 1
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTIPLE_COLLECTION_REFERENCE_ATTRIBUTE_QUERY,
+ variables={
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "valueLimit": expected_value_limit,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ len(content["data"]["page"]["assignedAttributes"][0]["value"])
+ == expected_value_limit
+ )
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"][0]["slug"]
+ == first_reference.reference_collection.slug
+ )
+
+
+ASSIGNED_SINGLE_CHOICE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ...on AssignedSingleChoiceAttribute{
+ __typename
+ value{
+ name
+ slug
+ translation(languageCode:FR)
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_single_choice_attribute_translation(
+ staff_api_client,
+ page,
+ size_page_attribute,
+):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([size_page_attribute])
+
+ attr_value = size_page_attribute.values.first()
+ translation = AttributeValueTranslation.objects.create(
+ language_code="fr",
+ attribute_value=attr_value,
+ name="French Size Name",
+ )
+
+ associate_attribute_values_to_instance(page, {size_page_attribute.pk: [attr_value]})
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_SINGLE_CHOICE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"]["translation"]
+ == translation.name
+ )
+
+
+def test_assigned_single_choice_attribute(
+ staff_api_client,
+ page,
+ size_page_attribute,
+):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([size_page_attribute])
+
+ attr_value = size_page_attribute.values.first()
+ expected_attr_value_name = "Size M"
+ expected_attr_value_slug = "size-m"
+ attr_value.slug = expected_attr_value_slug
+ attr_value.name = expected_attr_value_name
+ attr_value.save()
+
+ associate_attribute_values_to_instance(page, {size_page_attribute.pk: [attr_value]})
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_SINGLE_CHOICE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ attr_value_data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert attr_value_data["name"] == expected_attr_value_name
+ assert attr_value_data["slug"] == expected_attr_value_slug
+
+
+ASSIGNED_MULTI_CHOICE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID, $valueLimit: PositiveInt) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ... on AssignedMultiChoiceAttribute {
+ __typename
+ value(limit: $valueLimit) {
+ name
+ slug
+ translation(languageCode: FR)
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_multi_choice_attribute_translation(
+ staff_api_client,
+ page,
+ size_page_attribute,
+):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([size_page_attribute])
+
+ size_page_attribute.input_type = AttributeInputType.MULTISELECT
+ size_page_attribute.save()
+
+ attr_value = size_page_attribute.values.first()
+ translation = AttributeValueTranslation.objects.create(
+ language_code="fr",
+ attribute_value=attr_value,
+ name="French Size Name",
+ )
+
+ associate_attribute_values_to_instance(page, {size_page_attribute.pk: [attr_value]})
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTI_CHOICE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert len(content["data"]["page"]["assignedAttributes"][0]["value"]) == 1
+ attr_value_data = content["data"]["page"]["assignedAttributes"][0]["value"][0]
+ assert attr_value_data["translation"] == translation.name
+
+
+def test_applies_limit_to_multi_choices(
+ staff_api_client,
+ page,
+ size_page_attribute,
+):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([size_page_attribute])
+
+ size_page_attribute.input_type = AttributeInputType.MULTISELECT
+ size_page_attribute.save()
+
+ first_choice = size_page_attribute.values.first()
+ second_choice = size_page_attribute.values.last()
+
+ associate_attribute_values_to_instance(
+ page, {size_page_attribute.pk: [first_choice, second_choice]}
+ )
+
+ assert page.attributevalues.count() == 2
+ expected_value_limit = 1
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTI_CHOICE_ATTRIBUTE_QUERY,
+ variables={
+ "id": graphene.Node.to_global_id("Page", page.pk),
+ "valueLimit": expected_value_limit,
+ },
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert (
+ len(content["data"]["page"]["assignedAttributes"][0]["value"])
+ == expected_value_limit
+ )
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["value"][0]["slug"]
+ == first_choice.slug
+ )
+
+
+def test_assigned_multi_choice_attribute(
+ staff_api_client,
+ page,
+ size_page_attribute,
+):
+ # given
+ page_type = page.page_type
+ page_type.page_attributes.set([size_page_attribute])
+
+ size_page_attribute.input_type = AttributeInputType.MULTISELECT
+ size_page_attribute.save()
+
+ attr_value = size_page_attribute.values.first()
+ expected_attr_value_name = "Size M"
+ expected_attr_value_slug = "size-m"
+ attr_value.slug = expected_attr_value_slug
+ attr_value.name = expected_attr_value_name
+ attr_value.save()
+
+ associate_attribute_values_to_instance(page, {size_page_attribute.pk: [attr_value]})
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_MULTI_CHOICE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ assert len(content["data"]["page"]["assignedAttributes"][0]["value"]) == 1
+ attr_value_data = content["data"]["page"]["assignedAttributes"][0]["value"][0]
+ assert attr_value_data["name"] == expected_attr_value_name
+ assert attr_value_data["slug"] == expected_attr_value_slug
+
+
+ASSIGNED_SWATCH_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ... on AssignedSwatchAttribute {
+ value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_swatch_attribute(
+ staff_api_client,
+ page,
+ swatch_attribute,
+):
+ # given
+ swatch_attribute.type = AttributeType.PAGE_TYPE
+ swatch_attribute.save()
+
+ page_type = page.page_type
+ page_type.page_attributes.set([swatch_attribute])
+
+ attr_value = swatch_attribute.values.first()
+ expected_attr_value_name = "Red"
+ expected_attr_value_slug = "red"
+ expected_attr_hex_value = "#5C3030"
+ attr_value.slug = expected_attr_value_slug
+ attr_value.name = expected_attr_value_name
+ attr_value.value = expected_attr_hex_value
+ attr_value.save()
+
+ associate_attribute_values_to_instance(page, {swatch_attribute.pk: [attr_value]})
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_SWATCH_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ attr_value_data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert attr_value_data["name"] == expected_attr_value_name
+ assert attr_value_data["slug"] == expected_attr_value_slug
+ assert attr_value_data["hexColor"] == expected_attr_hex_value
+
+
+def test_assigned_swatch_file_attribute(staff_api_client, page, swatch_attribute):
+ # given
+ swatch_attribute.type = AttributeType.PAGE_TYPE
+ swatch_attribute.save()
+
+ page_type = page.page_type
+ page_type.page_attributes.set([swatch_attribute])
+
+ attr_value = swatch_attribute.values.first()
+
+ attr_value.file_url = "https://example.com/file.pdf"
+ attr_value.content_type = "application/pdf"
+ attr_value.save()
+
+ associate_attribute_values_to_instance(page, {swatch_attribute.pk: [attr_value]})
+
+ assert attr_value.file_url is not None
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_SWATCH_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ attr_value_data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert attr_value_data["name"] == attr_value.name
+ assert attr_value_data["slug"] == attr_value.slug
+ assert attr_value_data["file"]["url"] == attr_value.file_url
+ assert attr_value_data["file"]["contentType"] == attr_value.content_type
+
+
+ASSIGNED_BOOLEAN_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ... on AssignedBooleanAttribute {
+ value
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_boolean_attribute(
+ staff_api_client,
+ page,
+ boolean_attribute,
+):
+ # given
+ boolean_attribute.type = AttributeType.PAGE_TYPE
+ boolean_attribute.save()
+
+ page_type = page.page_type
+ page_type.page_attributes.set([boolean_attribute])
+
+ attr_value = boolean_attribute.values.first()
+ expected_attr_value = True
+ attr_value.boolean = expected_attr_value
+ attr_value.save()
+
+ associate_attribute_values_to_instance(page, {boolean_attribute.pk: [attr_value]})
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_BOOLEAN_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ attr_value_data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert attr_value_data is expected_attr_value
+
+
+ASSIGNED_DATE_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ... on AssignedDateAttribute {
+ value
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_date_attribute(
+ staff_api_client,
+ page,
+ date_attribute,
+):
+ # given
+ date_attribute.type = AttributeType.PAGE_TYPE
+ date_attribute.save()
+
+ page_type = page.page_type
+ page_type.page_attributes.set([date_attribute])
+
+ attr_value = date_attribute.values.first()
+ expected_attr_datetime_value = datetime.now(UTC)
+ attr_value.date_time = expected_attr_datetime_value
+ attr_value.save()
+
+ associate_attribute_values_to_instance(page, {date_attribute.pk: [attr_value]})
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_DATE_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ attr_value_data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert attr_value_data == str(expected_attr_datetime_value.date())
+
+
+ASSIGNED_DATETIME_ATTRIBUTE_QUERY = """
+query PageQuery($id: ID) {
+ page(id: $id) {
+ assignedAttributes(limit:10) {
+ ... on AssignedDateTimeAttribute {
+ value
+ }
+ }
+ }
+}
+"""
+
+
+def test_assigned_datetime_attribute(
+ staff_api_client,
+ page,
+ date_time_attribute,
+):
+ # given
+ date_time_attribute.type = AttributeType.PAGE_TYPE
+ date_time_attribute.save()
+
+ page_type = page.page_type
+ page_type.page_attributes.set([date_time_attribute])
+
+ attr_value = date_time_attribute.values.first()
+ expected_attr_datetime_value = datetime.now(UTC)
+ attr_value.date_time = expected_attr_datetime_value
+ attr_value.save()
+
+ associate_attribute_values_to_instance(page, {date_time_attribute.pk: [attr_value]})
+
+ # when
+ response = staff_api_client.post_graphql(
+ ASSIGNED_DATETIME_ATTRIBUTE_QUERY,
+ variables={"id": graphene.Node.to_global_id("Page", page.pk)},
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["page"]["assignedAttributes"]) == 1
+ attr_value_data = content["data"]["page"]["assignedAttributes"][0]["value"]
+ assert attr_value_data == str(expected_attr_datetime_value.isoformat())
+
+
+def test_all_non_reference_attribute_type_has_own_assigned_types():
+ expected_attribute_types = [value for (value, _) in AttributeInputType.CHOICES]
+ expected_attribute_types.remove(
+ AttributeInputType.SINGLE_REFERENCE,
+ )
+ expected_attribute_types.remove(
+ AttributeInputType.REFERENCE,
+ )
+
+ assert all(ASSIGNED_ATTRIBUTE_MAP.values())
+ assert set(ASSIGNED_ATTRIBUTE_MAP.keys()) == set(expected_attribute_types)
+
+
+def test_all_single_reference_attribute_type_has_own_assigned_types():
+ expected_entity_names = [
+ entity_name for (entity_name, _) in AttributeEntityType.CHOICES
+ ]
+
+ assert all(ASSIGNED_SINGLE_REFERENCE_MAP.values())
+ assert set(ASSIGNED_SINGLE_REFERENCE_MAP.keys()) == set(expected_entity_names)
+
+
+def test_all_multi_reference_attribute_type_has_own_assigned_types():
+ expected_entity_names = [
+ entity_name for (entity_name, _) in AttributeEntityType.CHOICES
+ ]
+
+ assert all(ASSIGNED_MULTI_REFERENCE_MAP.values())
+ assert set(ASSIGNED_MULTI_REFERENCE_MAP.keys()) == set(expected_entity_names)
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 8f4c6599c3..727f734271 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -1,19 +1,25 @@
+from datetime import date, datetime
+from typing import cast
+
import graphene
from promise import Promise
-from ...attribute import AttributeInputType, models
+from ...attribute import AttributeEntityType, AttributeInputType, models
+from ...page import models as page_models
from ...permission.enums import (
PagePermissions,
PageTypePermissions,
ProductPermissions,
ProductTypePermissions,
)
+from ...product import models as product_models
from ..core import ResolveInfo
from ..core.connection import (
CountableConnection,
create_connection_slice,
filter_connection_queryset,
)
+from ..core.const import DEFAULT_NESTED_LIST_LIMIT
from ..core.context import (
ChannelContext,
ChannelQsContext,
@@ -25,11 +31,12 @@ from ..core.descriptions import (
DEPRECATED_IN_3X_INPUT,
)
from ..core.doc_category import DOC_CATEGORY_ATTRIBUTES
-from ..core.enums import MeasurementUnitsEnum
+from ..core.enums import LanguageCodeEnum, MeasurementUnitsEnum
from ..core.fields import ConnectionField, FilterConnectionField, JSONString
-from ..core.scalars import Date, DateTime
+from ..core.scalars import JSON, Date, DateTime, PositiveInt
from ..core.types import (
BaseInputObjectType,
+ BaseInterface,
BaseObjectType,
DateRangeInput,
DateTimeRangeInput,
@@ -41,7 +48,15 @@ from ..core.types.context import ChannelContextType, ChannelContextTypeForObject
from ..decorators import check_attribute_required_permissions
from ..meta.types import ObjectWithMetadata
from ..page.dataloaders import PageByIdLoader
-from ..product.dataloaders.products import ProductByIdLoader, ProductVariantByIdLoader
+from ..product.dataloaders.products import (
+ CategoryByIdLoader,
+ CollectionByIdLoader,
+ ProductByIdLoader,
+ ProductVariantByIdLoader,
+)
+from ..translations.dataloaders import (
+ AttributeValueTranslationByIdAndLanguageCodeLoader,
+)
from ..translations.fields import TranslationField
from ..translations.types import AttributeTranslation, AttributeValueTranslation
from .dataloaders import AttributesByAttributeId
@@ -54,7 +69,7 @@ from .filters import (
)
from .shared_filters import AssignedAttributeValueInput
from .sorters import AttributeChoicesSortingInput
-from .utils.shared import ENTITY_TYPE_MAPPING
+from .utils.shared import ENTITY_TYPE_MAPPING, AssignedAttributeData
def get_reference_pk(attribute, root: models.AttributeValue) -> None | int:
@@ -496,22 +511,6 @@ class AssignedVariantAttribute(BaseObjectType):
doc_category = DOC_CATEGORY_ATTRIBUTES
-class SelectedAttribute(ChannelContextTypeForObjectType):
- attribute = graphene.Field(
- Attribute,
- default_value=None,
- description=AttributeDescriptions.NAME,
- required=True,
- )
- values = NonNullList(
- AttributeValue, description="Values of an attribute.", required=True
- )
-
- class Meta:
- doc_category = DOC_CATEGORY_ATTRIBUTES
- description = "Represents an assigned attribute to an object."
-
-
class AttributeInput(BaseInputObjectType):
slug = graphene.String(required=False, description=AttributeDescriptions.SLUG)
value = AssignedAttributeValueInput(
@@ -656,3 +655,791 @@ class AttributeValueInput(BaseInputObjectType):
class Meta:
doc_category = DOC_CATEGORY_ATTRIBUTES
+
+
+class SelectedAttribute(ChannelContextTypeForObjectType):
+ attribute = graphene.Field(
+ Attribute,
+ default_value=None,
+ description=AttributeDescriptions.NAME,
+ required=True,
+ )
+ values = NonNullList(
+ AttributeValue, description="Values of an attribute.", required=True
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+ description = "Represents an assigned attribute to an object."
+
+
+class AssignedAttribute(BaseInterface):
+ attribute = graphene.Field(
+ Attribute,
+ default_value=None,
+ description="Attribute assigned to an object.",
+ required=True,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+ description = "Represents an attribute assigned to an object." + ADDED_IN_322
+
+ @staticmethod
+ def resolve_type(instance: AssignedAttributeData, _info):
+ if instance.attribute.node.input_type == AttributeInputType.SINGLE_REFERENCE:
+ entity_type = cast(str, instance.attribute.node.entity_type)
+ return ASSIGNED_SINGLE_REFERENCE_MAP.get(entity_type)
+ if instance.attribute.node.input_type == AttributeInputType.REFERENCE:
+ entity_type = cast(str, instance.attribute.node.entity_type)
+ return ASSIGNED_MULTI_REFERENCE_MAP.get(entity_type)
+ attr_type = ASSIGNED_ATTRIBUTE_MAP[instance.attribute.node.input_type]
+ return attr_type
+
+
+class AssignedNumericAttribute(BaseObjectType):
+ value = graphene.Float(
+ required=False,
+ description="The assigned numeric value.",
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents a numeric value of an attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> float | None:
+ if not root.values:
+ return None
+
+ attr_value = root.values[0].node
+ return attr_value.numeric
+
+
+class AssignedTextAttribute(BaseObjectType):
+ value = graphene.Field(
+ JSON,
+ description="The assigned rich text content.",
+ required=False,
+ )
+
+ translation = graphene.Field(
+ JSON,
+ language_code=graphene.Argument(
+ LanguageCodeEnum,
+ required=True,
+ ),
+ description="Translation of the rich text content in the specified language.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents text attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> JSON | None:
+ if not root.values:
+ return None
+ attr_value = root.values[0].node
+ return attr_value.rich_text
+
+ @staticmethod
+ def resolve_translation(
+ root: AssignedAttributeData, info: ResolveInfo, *, language_code
+ ) -> Promise[JSON | None] | None:
+ if not root.values:
+ return None
+
+ def _wrap_translation(
+ translation: AttributeValueTranslation | None,
+ ) -> JSON | None:
+ if translation is None:
+ return None
+ return translation.rich_text
+
+ return (
+ AttributeValueTranslationByIdAndLanguageCodeLoader(info.context)
+ .load((root.values[0].node.id, language_code))
+ .then(_wrap_translation)
+ )
+
+
+class AssignedPlainTextAttribute(BaseObjectType):
+ value = graphene.String(
+ description="The assigned plain text content.",
+ required=False,
+ )
+
+ translation = graphene.Field(
+ graphene.String,
+ language_code=graphene.Argument(
+ LanguageCodeEnum,
+ required=True,
+ ),
+ description="Translation of the plain text content in the specified language.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents plain text attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> str | None:
+ if not root.values:
+ return None
+ attr_value = root.values[0].node
+ return attr_value.plain_text
+
+ @staticmethod
+ def resolve_translation(
+ root: AssignedAttributeData, info: ResolveInfo, *, language_code
+ ) -> Promise[str | None] | None:
+ if not root.values:
+ return None
+
+ def _wrap_translation(
+ translation: AttributeValueTranslation | None,
+ ) -> str | None:
+ if translation is None:
+ return None
+ return translation.plain_text
+
+ return (
+ AttributeValueTranslationByIdAndLanguageCodeLoader(info.context)
+ .load((root.values[0].node.id, language_code))
+ .then(_wrap_translation)
+ )
+
+
+class AssignedFileAttribute(BaseObjectType):
+ value = graphene.Field(File, description="The assigned file.", required=False)
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents file attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> File | None:
+ if not root.values:
+ return None
+ attr_value = root.values[0].node
+ return File(url=attr_value.file_url, content_type=attr_value.content_type)
+
+
+class AssignedSinglePageReferenceAttribute(BaseObjectType):
+ value = graphene.Field(
+ "saleor.graphql.page.types.Page",
+ description="The assigned page reference.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents single page reference attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[ChannelContext[page_models.Page]] | None:
+ if not root.values:
+ return None
+
+ channel_slug = root.attribute.channel_slug
+ attr_value = root.values[0].node
+
+ return (
+ PageByIdLoader(info.context)
+ .load(attr_value.reference_page_id)
+ .then(lambda page: ChannelContext(node=page, channel_slug=channel_slug))
+ )
+
+
+class AssignedSingleProductReferenceAttribute(BaseObjectType):
+ value = graphene.Field(
+ "saleor.graphql.product.types.Product",
+ description="The assigned product reference.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents single product reference attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[ChannelContext[product_models.Product]] | None:
+ if not root.values:
+ return None
+
+ channel_slug = root.attribute.channel_slug
+ attr_value = root.values[0].node
+
+ return (
+ ProductByIdLoader(info.context)
+ .load(attr_value.reference_product_id)
+ .then(
+ lambda product: ChannelContext(node=product, channel_slug=channel_slug)
+ )
+ )
+
+
+class AssignedSingleProductVariantReferenceAttribute(BaseObjectType):
+ value = graphene.Field(
+ "saleor.graphql.product.types.ProductVariant",
+ description="The assigned product variant reference.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = (
+ "Represents single product variant reference attribute." + ADDED_IN_322
+ )
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[ChannelContext[product_models.ProductVariant]] | None:
+ if not root.values:
+ return None
+
+ channel_slug = root.attribute.channel_slug
+ attr_value = root.values[0].node
+
+ return (
+ ProductVariantByIdLoader(info.context)
+ .load(attr_value.reference_variant_id)
+ .then(
+ lambda product_variant: ChannelContext(
+ node=product_variant, channel_slug=channel_slug
+ )
+ )
+ )
+
+
+class AssignedSingleCategoryReferenceAttribute(BaseObjectType):
+ value = graphene.Field(
+ "saleor.graphql.product.types.Category",
+ description="The assigned category reference.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents single category reference attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[product_models.Category] | None:
+ if not root.values:
+ return None
+ attr_value = root.values[0].node
+ return CategoryByIdLoader(info.context).load(attr_value.reference_category_id)
+
+
+class AssignedSingleCollectionReferenceAttribute(BaseObjectType):
+ value = graphene.Field(
+ "saleor.graphql.product.types.Collection",
+ description="The assigned collection reference.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents single collection reference attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> Promise[ChannelContext[product_models.Collection]] | None:
+ if not root.values:
+ return None
+
+ channel_slug = root.attribute.channel_slug
+ attr_value = root.values[0].node
+
+ return (
+ CollectionByIdLoader(info.context)
+ .load(attr_value.reference_collection_id)
+ .then(
+ lambda collection: ChannelContext(
+ node=collection, channel_slug=channel_slug
+ )
+ )
+ )
+
+
+class AssignedMultiPageReferenceAttribute(BaseObjectType):
+ value = NonNullList(
+ "saleor.graphql.page.types.Page",
+ description="List of assigned page references.",
+ required=True,
+ limit=PositiveInt(
+ description=(
+ "Maximum number of referenced pages to return. "
+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}."
+ ),
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents multi page reference attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData,
+ info: ResolveInfo,
+ limit: int = DEFAULT_NESTED_LIST_LIMIT,
+ ) -> Promise[list[ChannelContext[page_models.Page]]]:
+ if not root.values:
+ return Promise.resolve([])
+
+ channel_slug = root.attribute.channel_slug
+ attr_values = [value.node for value in root.values]
+ attr_values = attr_values[:limit]
+
+ def _wrap_with_channel_context(
+ pages: list[page_models.Page],
+ ) -> list[ChannelContext[page_models.Page]]:
+ if not pages:
+ return []
+ return [
+ ChannelContext(node=page, channel_slug=channel_slug) for page in pages
+ ]
+
+ return (
+ PageByIdLoader(info.context)
+ .load_many([value.reference_page_id for value in attr_values])
+ .then(_wrap_with_channel_context)
+ )
+
+
+class AssignedMultiProductReferenceAttribute(BaseObjectType):
+ value = NonNullList(
+ "saleor.graphql.product.types.Product",
+ description="List of assigned product references.",
+ required=True,
+ limit=PositiveInt(
+ description=(
+ "Maximum number of referenced products to return. "
+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}."
+ ),
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents multi product reference attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData,
+ info: ResolveInfo,
+ limit: int = DEFAULT_NESTED_LIST_LIMIT,
+ ) -> Promise[list[ChannelContext[product_models.Product]]]:
+ if not root.values:
+ return Promise.resolve([])
+
+ channel_slug = root.attribute.channel_slug
+ attr_values = [value.node for value in root.values]
+ attr_values = attr_values[:limit]
+
+ def _wrap_with_channel_context(
+ products: list[product_models.Product],
+ ) -> list[ChannelContext[product_models.Product]]:
+ if not products:
+ return []
+ return [
+ ChannelContext(node=product, channel_slug=channel_slug)
+ for product in products
+ ]
+
+ return (
+ ProductByIdLoader(info.context)
+ .load_many([value.reference_product_id for value in attr_values])
+ .then(_wrap_with_channel_context)
+ )
+
+
+class AssignedMultiProductVariantReferenceAttribute(BaseObjectType):
+ value = NonNullList(
+ "saleor.graphql.product.types.ProductVariant",
+ description="List of assigned product variant references.",
+ required=True,
+ limit=PositiveInt(
+ description=(
+ "Maximum number of referenced product variants to return. "
+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}."
+ ),
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = (
+ "Represents multi product variant reference attribute." + ADDED_IN_322
+ )
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData,
+ info: ResolveInfo,
+ limit: int = DEFAULT_NESTED_LIST_LIMIT,
+ ) -> Promise[list[ChannelContext[product_models.ProductVariant]]]:
+ if not root.values:
+ return Promise.resolve([])
+
+ channel_slug = root.attribute.channel_slug
+ attr_values = [value.node for value in root.values]
+ attr_values = attr_values[:limit]
+
+ def _wrap_with_channel_context(
+ variants: list[product_models.ProductVariant],
+ ) -> list[ChannelContext[product_models.ProductVariant]]:
+ if not variants:
+ return []
+ return [
+ ChannelContext(node=variant, channel_slug=channel_slug)
+ for variant in variants
+ ]
+
+ return (
+ ProductVariantByIdLoader(info.context)
+ .load_many([value.reference_variant_id for value in attr_values])
+ .then(_wrap_with_channel_context)
+ )
+
+
+class AssignedMultiCategoryReferenceAttribute(BaseObjectType):
+ value = NonNullList(
+ "saleor.graphql.product.types.Category",
+ description="List of assigned category references.",
+ required=True,
+ limit=PositiveInt(
+ description=(
+ "Maximum number of referenced categories to return. "
+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}."
+ ),
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents multi category reference attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData,
+ info: ResolveInfo,
+ limit: int = DEFAULT_NESTED_LIST_LIMIT,
+ ) -> Promise[list[product_models.Category]]:
+ if not root.values:
+ return Promise.resolve([])
+ attr_values = [value.node for value in root.values]
+ attr_values = attr_values[:limit]
+
+ return CategoryByIdLoader(info.context).load_many(
+ [value.reference_category_id for value in attr_values]
+ )
+
+
+class AssignedMultiCollectionReferenceAttribute(BaseObjectType):
+ value = NonNullList(
+ "saleor.graphql.product.types.Collection",
+ description="List of assigned collection references.",
+ required=True,
+ limit=PositiveInt(
+ description=(
+ "Maximum number of referenced collections to return. "
+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}"
+ ),
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents multi collection reference attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData,
+ info: ResolveInfo,
+ limit: int = DEFAULT_NESTED_LIST_LIMIT,
+ ) -> Promise[list[ChannelContext[product_models.Collection]]]:
+ if not root.values:
+ return Promise.resolve([])
+
+ channel_slug = root.attribute.channel_slug
+ attr_values = [value.node for value in root.values]
+ attr_values = attr_values[:limit]
+
+ def _wrap_with_channel_context(
+ collections: list[product_models.Collection],
+ ) -> list[ChannelContext[product_models.Collection]]:
+ if not collections:
+ return []
+ return [
+ ChannelContext(node=collection, channel_slug=channel_slug)
+ for collection in collections
+ ]
+
+ return (
+ CollectionByIdLoader(info.context)
+ .load_many([value.reference_collection_id for value in attr_values])
+ .then(_wrap_with_channel_context)
+ )
+
+
+class AssignedChoiceAttributeValue(BaseObjectType):
+ name = graphene.String(description=AttributeValueDescriptions.NAME)
+ slug = graphene.String(description=AttributeValueDescriptions.SLUG)
+ translation = graphene.String(
+ language_code=graphene.Argument(
+ LanguageCodeEnum,
+ required=True,
+ ),
+ description="Translation of the name.",
+ required=False,
+ )
+
+ class Meta:
+ description = (
+ "Represents a single choice value of the attribute." + ADDED_IN_322
+ )
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_translation(
+ root: AttributeValue, info: ResolveInfo, *, language_code
+ ) -> Promise[str | None] | None:
+ return (
+ AttributeValueTranslationByIdAndLanguageCodeLoader(info.context)
+ .load((root.id, language_code))
+ .then(lambda translation: translation.name if translation else None)
+ )
+
+
+class AssignedSingleChoiceAttribute(BaseObjectType):
+ value = graphene.Field(
+ AssignedChoiceAttributeValue,
+ required=False,
+ description="The assigned choice value.",
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents a single choice attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ def resolve_value(
+ root: AssignedAttributeData, info: ResolveInfo
+ ) -> models.AttributeValue | None:
+ if not root.values:
+ return None
+ attr_value = root.values[0].node
+ return attr_value
+
+
+class AssignedMultiChoiceAttribute(BaseObjectType):
+ value = NonNullList(
+ AssignedChoiceAttributeValue,
+ required=True,
+ description="List of assigned choice values.",
+ limit=PositiveInt(
+ description=(
+ "Maximum number of choices to return. "
+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}."
+ ),
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents a multi choice attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData,
+ info: ResolveInfo,
+ limit: int = DEFAULT_NESTED_LIST_LIMIT,
+ ) -> list[models.AttributeValue]:
+ values = root.values[:limit]
+ return [value.node for value in values]
+
+
+class AssignedSwatchAttributeValue(BaseObjectType):
+ name = graphene.String(
+ description="Name of the selected swatch value. ",
+ required=False,
+ )
+ slug = graphene.String(
+ description="Slug of the selected swatch value.",
+ required=False,
+ )
+ hex_color = graphene.String(
+ required=False,
+ description="Hex color code.",
+ )
+ file = graphene.Field(
+ File, description="File associated with the attribute.", required=False
+ )
+
+ @staticmethod
+ def resolve_hex_color(
+ root: models.AttributeValue, _info: ResolveInfo
+ ) -> str | None:
+ if not root.value:
+ return None
+ return root.value
+
+ @staticmethod
+ def resolve_file(root: models.AttributeValue, _info: ResolveInfo) -> File | None:
+ if not root.file_url:
+ return None
+ return File(url=root.file_url, content_type=root.content_type)
+
+ class Meta:
+ description = "Represents a single swatch value." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+
+class AssignedSwatchAttribute(BaseObjectType):
+ value = graphene.Field(
+ AssignedSwatchAttributeValue,
+ required=False,
+ description="The assigned swatch value.",
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents a swatch attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData, _info: ResolveInfo
+ ) -> models.AttributeValue | None:
+ if not root.values:
+ return None
+ attr_value = root.values[0].node
+ return attr_value
+
+
+class AssignedBooleanAttribute(BaseObjectType):
+ value = graphene.Boolean(
+ description="The assigned boolean value.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents a boolean attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> bool | None:
+ if not root.values:
+ return None
+ attr_value = root.values[0].node
+ return attr_value.boolean
+
+
+class AssignedDateAttribute(BaseObjectType):
+ value = graphene.Field(
+ Date,
+ description="The assigned date value.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents a date attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(root: AssignedAttributeData, _info: ResolveInfo) -> date | None:
+ if not root.values:
+ return None
+ attr_value = root.values[0].node
+ return attr_value.date_time.date() if attr_value.date_time else None
+
+
+class AssignedDateTimeAttribute(BaseObjectType):
+ value = graphene.Field(
+ DateTime,
+ description="The assigned date time value.",
+ required=False,
+ )
+
+ class Meta:
+ interfaces = [AssignedAttribute]
+ description = "Represents a date time attribute." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ATTRIBUTES
+
+ @staticmethod
+ def resolve_value(
+ root: AssignedAttributeData, _info: ResolveInfo
+ ) -> datetime | None:
+ if not root.values:
+ return None
+ attr_value = root.values[0].node
+ return attr_value.date_time
+
+
+ASSIGNED_SINGLE_REFERENCE_MAP = {
+ AttributeEntityType.PAGE: AssignedSinglePageReferenceAttribute,
+ AttributeEntityType.PRODUCT: AssignedSingleProductReferenceAttribute,
+ AttributeEntityType.PRODUCT_VARIANT: AssignedSingleProductVariantReferenceAttribute,
+ AttributeEntityType.CATEGORY: AssignedSingleCategoryReferenceAttribute,
+ AttributeEntityType.COLLECTION: AssignedSingleCollectionReferenceAttribute,
+}
+ASSIGNED_MULTI_REFERENCE_MAP = {
+ AttributeEntityType.PAGE: AssignedMultiPageReferenceAttribute,
+ AttributeEntityType.PRODUCT: AssignedMultiProductReferenceAttribute,
+ AttributeEntityType.PRODUCT_VARIANT: AssignedMultiProductVariantReferenceAttribute,
+ AttributeEntityType.CATEGORY: AssignedMultiCategoryReferenceAttribute,
+ AttributeEntityType.COLLECTION: AssignedMultiCollectionReferenceAttribute,
+}
+ASSIGNED_ATTRIBUTE_MAP = {
+ AttributeInputType.NUMERIC: AssignedNumericAttribute,
+ AttributeInputType.RICH_TEXT: AssignedTextAttribute,
+ AttributeInputType.PLAIN_TEXT: AssignedPlainTextAttribute,
+ AttributeInputType.FILE: AssignedFileAttribute,
+ AttributeInputType.DROPDOWN: AssignedSingleChoiceAttribute,
+ AttributeInputType.MULTISELECT: AssignedMultiChoiceAttribute,
+ AttributeInputType.SWATCH: AssignedSwatchAttribute,
+ AttributeInputType.BOOLEAN: AssignedBooleanAttribute,
+ AttributeInputType.DATE: AssignedDateAttribute,
+ AttributeInputType.DATE_TIME: AssignedDateTimeAttribute,
+}
+ASSIGNED_ATTRIBUTE_TYPES = (
+ list(ASSIGNED_ATTRIBUTE_MAP.values())
+ + list(ASSIGNED_SINGLE_REFERENCE_MAP.values())
+ + list(ASSIGNED_MULTI_REFERENCE_MAP.values())
+)
diff --git a/saleor/graphql/attribute/utils/shared.py b/saleor/graphql/attribute/utils/shared.py
index c8b5ecc101..34bd767431 100644
--- a/saleor/graphql/attribute/utils/shared.py
+++ b/saleor/graphql/attribute/utils/shared.py
@@ -11,6 +11,7 @@ from ....attribute import AttributeEntityType, AttributeInputType
from ....attribute import models as attribute_models
from ....page import models as page_models
from ....product import models as product_models
+from ...core.context import ChannelContext
from ...product.utils import get_used_attribute_values_for_variant
if TYPE_CHECKING:
@@ -27,6 +28,12 @@ T_REFERENCE = (
)
+@dataclass
+class AssignedAttributeData:
+ attribute: ChannelContext[attribute_models.Attribute]
+ values: list[ChannelContext[attribute_models.AttributeValue]]
+
+
@dataclass
class AttrValuesForSelectableFieldInput:
id: str | None = None
diff --git a/saleor/graphql/core/const.py b/saleor/graphql/core/const.py
new file mode 100644
index 0000000000..8563fb2211
--- /dev/null
+++ b/saleor/graphql/core/const.py
@@ -0,0 +1,2 @@
+# Default value for list with limit argument
+DEFAULT_NESTED_LIST_LIMIT = 100
diff --git a/saleor/graphql/core/tests/test_query_cost_validation.py b/saleor/graphql/core/tests/test_query_cost_validation.py
index 065386ae46..cc998e807a 100644
--- a/saleor/graphql/core/tests/test_query_cost_validation.py
+++ b/saleor/graphql/core/tests/test_query_cost_validation.py
@@ -2,6 +2,8 @@ import graphene
import pytest
from django.test import override_settings
+from ...query_cost_map import COST_MAP
+
@override_settings(GRAPHQL_QUERY_MAX_COMPLEXITY=1)
def test_query_exceeding_cost_limit_fails_validation(
@@ -235,3 +237,234 @@ def test_query_with_fragments_have_same_multiplied_complexity_cost(
assert json_response["data"] == expected_data
query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
assert query_cost == 120
+
+
+QUERY_INLINE_FRAGMENT_BASED_ON_INTERFACE = """
+query Page($assignedAttributeLimit: Int, $assignedMultiProductLimit: Int, $assignedMultiCategoryLimit: Int){
+ page(slug:"about"){
+ assignedAttributes(limit:$assignedAttributeLimit){
+ ...on AssignedAttribute{
+ attribute{
+ id
+ }
+ }
+ ...on AssignedMultiProductReferenceAttribute{
+ value(limit:$assignedMultiProductLimit){
+ id
+ }
+ }
+ ...on AssignedMultiCategoryReferenceAttribute{
+ value(limit:$assignedMultiCategoryLimit){
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_query_cost_for_inline_fragments_on_interface(api_client):
+ assigned_attributes_limit = 10
+ assigned_multi_product_limit = 10
+ assigned_multi_category_limit = 10000
+ variables = {
+ "assignedAttributeLimit": assigned_attributes_limit,
+ "assignedMultiProductLimit": assigned_multi_product_limit,
+ "assignedMultiCategoryLimit": assigned_multi_category_limit,
+ }
+ assert assigned_multi_category_limit > assigned_multi_product_limit
+
+ # when
+ response = api_client.post_graphql(
+ QUERY_INLINE_FRAGMENT_BASED_ON_INTERFACE, variables
+ )
+ json_response = response.json()
+
+ # then
+ query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
+ single_page_cost = COST_MAP["Query"]["page"]["complexity"]
+ single_assigned_attribute_attribute_cost = COST_MAP["AssignedAttribute"][
+ "attribute"
+ ]["complexity"]
+
+ expected_cost = (
+ single_page_cost
+ + single_page_cost * assigned_attributes_limit
+ # Cost of AssignedAttribute interface, as
+ # all responses for child types will include
+ # the fields requested in AssignedInterface
+ # fragment
+ + (
+ single_page_cost
+ * assigned_attributes_limit
+ * single_assigned_attribute_attribute_cost
+ )
+ # max from requested inline fragment is used when requesting
+ # multiple fragments based on the same interface
+ + assigned_attributes_limit * assigned_multi_category_limit
+ )
+ assert query_cost == expected_cost
+
+
+QUERY_SPREAD_FRAGMENTS_BASED_ON_INTERFACE = """
+query Page(
+ $assignedAttributeLimit: Int
+ $assignedMultiProductLimit: Int
+ $assignedMultiCategoryLimit: Int
+) {
+ page(slug: "about") {
+ assignedAttributes(limit: $assignedAttributeLimit) {
+ ...AssignedInterface
+ ...MultiProducts
+ ...MultiCategories
+ }
+ }
+}
+
+fragment AssignedInterface on AssignedAttribute {
+ attribute {
+ id
+ }
+}
+
+fragment MultiProducts on AssignedMultiProductReferenceAttribute {
+ value(limit: $assignedMultiProductLimit) {
+ id
+ }
+}
+
+fragment MultiCategories on AssignedMultiCategoryReferenceAttribute {
+ value(limit: $assignedMultiCategoryLimit) {
+ id
+ }
+}
+"""
+
+
+def test_query_cost_for_spread_fragments_on_interface(api_client):
+ assigned_attributes_limit = 10
+ assigned_multi_product_limit = 10
+ assigned_multi_category_limit = 10000
+ variables = {
+ "assignedAttributeLimit": assigned_attributes_limit,
+ "assignedMultiProductLimit": assigned_multi_product_limit,
+ "assignedMultiCategoryLimit": assigned_multi_category_limit,
+ }
+ assert assigned_multi_category_limit > assigned_multi_product_limit
+
+ # when
+ response = api_client.post_graphql(
+ QUERY_SPREAD_FRAGMENTS_BASED_ON_INTERFACE, variables
+ )
+ json_response = response.json()
+
+ # then
+ query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
+ single_page_cost = COST_MAP["Query"]["page"]["complexity"]
+ single_assigned_attribute_attribute_cost = COST_MAP["AssignedAttribute"][
+ "attribute"
+ ]["complexity"]
+
+ expected_cost = (
+ single_page_cost
+ + single_page_cost * assigned_attributes_limit
+ # Cost of AssignedAttribute interface, as
+ # all responses for child types will include
+ # the fields requested in AssignedInterface
+ # fragment
+ + (
+ single_page_cost
+ * assigned_attributes_limit
+ * single_assigned_attribute_attribute_cost
+ )
+ # max from requested spread fragment is used when requesting
+ # multiple fragments based on the same interface
+ + assigned_attributes_limit * assigned_multi_category_limit
+ )
+ assert query_cost == expected_cost
+
+
+QUERY_SPREAD_AND_INLINE_FRAGMENTS_BASED_ON_INTERFACE = """
+query Page(
+ $assignedAttributeLimit: Int
+ $assignedMultiProductLimit: Int
+ $assignedMultiCategoryLimit: Int
+) {
+ page(slug: "about") {
+ assignedAttributes(limit: $assignedAttributeLimit) {
+ ...AssignedInterface
+ ...MultiProducts
+ ...MultiCategories
+ ...on AssignedMultiCategoryReferenceAttribute{
+ val: value(limit:$assignedMultiCategoryLimit){
+ id
+ }
+ }
+ }
+ }
+}
+
+fragment AssignedInterface on AssignedAttribute {
+ attribute {
+ id
+ }
+}
+
+fragment MultiProducts on AssignedMultiProductReferenceAttribute {
+ value(limit: $assignedMultiProductLimit) {
+ id
+ }
+}
+
+fragment MultiCategories on AssignedMultiCategoryReferenceAttribute {
+ value(limit: $assignedMultiCategoryLimit) {
+ id
+ }
+}
+"""
+
+
+def test_query_cost_for_spread_and_inline_fragments_on_interface(api_client):
+ assigned_attributes_limit = 10
+ assigned_multi_product_limit = 10
+ assigned_multi_category_limit = 10000
+ variables = {
+ "assignedAttributeLimit": assigned_attributes_limit,
+ "assignedMultiProductLimit": assigned_multi_product_limit,
+ "assignedMultiCategoryLimit": assigned_multi_category_limit,
+ }
+ assert assigned_multi_category_limit > assigned_multi_product_limit
+
+ # when
+ response = api_client.post_graphql(
+ QUERY_SPREAD_AND_INLINE_FRAGMENTS_BASED_ON_INTERFACE, variables
+ )
+ json_response = response.json()
+
+ # then
+ query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
+ single_page_cost = COST_MAP["Query"]["page"]["complexity"]
+ single_assigned_attribute_attribute_cost = COST_MAP["AssignedAttribute"][
+ "attribute"
+ ]["complexity"]
+
+ expected_cost = (
+ single_page_cost
+ + single_page_cost * assigned_attributes_limit
+ # Cost of AssignedAttribute interface, as
+ # all responses for child types will include
+ # the fields requested in AssignedInterface
+ # fragment
+ + (
+ single_page_cost
+ * assigned_attributes_limit
+ * single_assigned_attribute_attribute_cost
+ )
+ # max from requested spread/inline fragments is used when requesting
+ # multiple fragments based on the same interface
+ + assigned_attributes_limit * assigned_multi_category_limit
+ # Multiplied by 2 as the same fragment is used with alias
+ + assigned_attributes_limit * assigned_multi_category_limit
+ )
+ assert query_cost == expected_cost
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index 8622732dd2..88745e0dec 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -1,4 +1,10 @@
-from .base import BaseConnection, BaseEnum, BaseInputObjectType, BaseObjectType
+from .base import (
+ BaseConnection,
+ BaseEnum,
+ BaseInputObjectType,
+ BaseInterface,
+ BaseObjectType,
+)
from .common import (
TYPES_WITH_DOUBLE_ID_AVAILABLE,
AccountError,
@@ -91,6 +97,7 @@ __all__ = [
"BaseConnection",
"BaseEnum",
"BaseInputObjectType",
+ "BaseInterface",
"BaseObjectType",
"BulkProductError",
"BulkStockError",
diff --git a/saleor/graphql/core/types/base.py b/saleor/graphql/core/types/base.py
index 496ff56030..61a5aef84c 100644
--- a/saleor/graphql/core/types/base.py
+++ b/saleor/graphql/core/types/base.py
@@ -1,6 +1,7 @@
from graphene.relay.connection import Connection
from graphene.types.enum import Enum
from graphene.types.inputobjecttype import InputObjectType
+from graphene.types.interface import Interface
from graphene.types.objecttype import ObjectType
@@ -55,3 +56,16 @@ class BaseConnection(Connection):
):
cls.doc_category = doc_category
super().__init_subclass_with_meta__(node=node, name=name, **options)
+
+
+class BaseInterface(Interface):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def __init_subclass_with_meta__(cls, _meta=None, doc_category=None, **options):
+ cls.doc_category = doc_category
+ super().__init_subclass_with_meta__(
+ _meta=_meta,
+ **options,
+ )
diff --git a/saleor/graphql/core/validators/query_cost.py b/saleor/graphql/core/validators/query_cost.py
index a2f7b69e7a..3f616635ff 100644
--- a/saleor/graphql/core/validators/query_cost.py
+++ b/saleor/graphql/core/validators/query_cost.py
@@ -1,3 +1,4 @@
+from collections import defaultdict
from functools import reduce
from operator import add, mul
from typing import Any, cast
@@ -66,6 +67,8 @@ class CostValidator(ValidationRule):
if isinstance(type_def, GraphQLObjectType | GraphQLInterfaceType):
fields = type_def.fields
total = 0
+ fragment_map_cost: dict[str, int] = defaultdict(int)
+ fragment_name_to_interface_names: dict[str, set[str]] = defaultdict(set)
for child_node in node.selection_set.selections:
self.operation_multipliers = parent_multipliers[:]
node_cost = self.default_cost
@@ -74,6 +77,7 @@ class CostValidator(ValidationRule):
if not field:
continue
field_type = get_named_type(field.type)
+
try:
field_args: dict[str, Any] = get_argument_values(
field.args,
@@ -97,7 +101,6 @@ class CostValidator(ValidationRule):
node_cost = self.compute_cost(**cost_map_args)
except (TypeError, ValueError) as e:
report_error(self.context, e)
-
child_cost = self.compute_node_cost(
child_node, field_type, self.operation_multipliers
)
@@ -108,19 +111,48 @@ class CostValidator(ValidationRule):
fragment_type = self.context.get_schema().get_type(
fragment.type_condition.name.value
)
- node_cost = self.compute_node_cost(
+ if not fragment_type:
+ continue
+
+ fragment_map_cost[fragment_type.name] += self.compute_node_cost(
fragment, fragment_type, self.operation_multipliers
)
+ if (
+ isinstance(fragment_type, GraphQLObjectType)
+ and fragment_type.interfaces
+ ):
+ fragment_name_to_interface_names[fragment_type.name].update(
+ interface.name for interface in fragment_type.interfaces
+ )
+
if isinstance(child_node, InlineFragment):
inline_fragment_type = type_def
if child_node.type_condition and child_node.type_condition.name:
inline_fragment_type = self.context.get_schema().get_type(
child_node.type_condition.name.value
)
- node_cost = self.compute_node_cost(
+ if not inline_fragment_type:
+ continue
+
+ fragment_map_cost[inline_fragment_type.name] += self.compute_node_cost(
child_node, inline_fragment_type, self.operation_multipliers
)
+ if (
+ isinstance(inline_fragment_type, GraphQLObjectType)
+ and inline_fragment_type.interfaces
+ ):
+ fragment_name_to_interface_names[inline_fragment_type.name].update(
+ interface.name for interface in inline_fragment_type.interfaces
+ )
+
total += node_cost
+ if fragment_map_cost:
+ for fragment_name, interfaces in fragment_name_to_interface_names.items():
+ interfaces_cost = sum(
+ [fragment_map_cost.get(interface, 0) for interface in interfaces], 0
+ )
+ fragment_map_cost[fragment_name] += interfaces_cost
+ total += max(fragment_map_cost.values(), default=0)
return total
def enter_operation_definition(self, node, key, parent, path, ancestors): # pylint: disable=unused-argument
@@ -232,7 +264,9 @@ def validate_cost_map(cost_map: dict[str, dict[str, Any]], schema: GraphQLSchema
f"a type {type_name} that is not defined by the schema."
)
- if not isinstance(type_map[type_name], GraphQLObjectType):
+ if not isinstance(
+ type_map[type_name], GraphQLObjectType | GraphQLInterfaceType
+ ):
raise GraphQLError(
"The query cost could not be calculated because cost map specifies "
f"a type {type_name} that is defined by the schema, but is not an "
diff --git a/saleor/graphql/page/dataloaders.py b/saleor/graphql/page/dataloaders.py
index e08c7a290f..230e79b5ca 100644
--- a/saleor/graphql/page/dataloaders.py
+++ b/saleor/graphql/page/dataloaders.py
@@ -180,15 +180,15 @@ class AttributeValuesVisibleInStorefrontByPageIdLoader(
return PageAttributesVisibleInStorefrontByPageTypeIdLoader(self.context)
-class SelectedAttributesAllByPageIdLoader(DataLoader[int, list[dict]]):
- context_key = "selectedattributes_all_by_page"
+class AssignedAttributesAllByPageIdLoader(DataLoader[int, list[dict]]):
+ context_key = "assignedattributes_all_by_page"
def batch_load(self, page_ids):
return AttributeValuesAllByPageIdLoader(self.context).load_many(page_ids)
-class SelectedAttributesVisibleInStorefrontPageIdLoader(DataLoader[int, list[dict]]):
- context_key = "selectedattributes_visible_in_storefront_by_page"
+class AssignedAttributesVisibleInStorefrontPageIdLoader(DataLoader[int, list[dict]]):
+ context_key = "assignedattributes_visible_in_storefront_by_page"
def batch_load(self, page_ids):
return AttributeValuesVisibleInStorefrontByPageIdLoader(self.context).load_many(
@@ -342,8 +342,8 @@ class AttributeValuesVisibleInStorefrontByPageIdAndAttributeSlugLoader(
)
-class SelectedAttributeAllByPageIdAttributeSlugLoader(DataLoader[int, list[dict]]):
- context_key = "selectedattributes_all_by_page_and_attribute_slug"
+class AssignedAttributeAllByPageIdAttributeSlugLoader(DataLoader[int, list[dict]]):
+ context_key = "assignedattributes_all_by_page_and_attribute_slug"
def batch_load(self, page_ids):
return AttributeValuesAllByPageIdAndAttributeSlugLoader(self.context).load_many(
@@ -351,10 +351,10 @@ class SelectedAttributeAllByPageIdAttributeSlugLoader(DataLoader[int, list[dict]
)
-class SelectedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(
+class AssignedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(
DataLoader[int, list[dict]]
):
- context_key = "selectedattributes_visible_in_storefront_by_page_and_attribute_slug"
+ context_key = "assignedattributes_visible_in_storefront_by_page_and_attribute_slug"
def batch_load(self, page_ids):
return AttributeValuesVisibleInStorefrontByPageIdAndAttributeSlugLoader(
diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.py
index 3572150f1e..c09dbae650 100644
--- a/saleor/graphql/page/tests/mutations/test_page_create.py
+++ b/saleor/graphql/page/tests/mutations/test_page_create.py
@@ -17,46 +17,126 @@ from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
CREATE_PAGE_MUTATION = """
- mutation CreatePage(
- $input: PageCreateInput!
- ) {
- pageCreate(input: $input) {
- page {
- id
- title
- content
- slug
- isPublished
- publishedAt
- pageType {
- id
- }
- attributes {
- attribute {
- slug
- }
- values {
- slug
- name
- reference
- date
- dateTime
- plainText
- file {
- url
- contentType
- }
- }
- }
- }
- errors {
- field
- code
- message
- attributes
- }
+mutation CreatePage($input: PageCreateInput!) {
+ pageCreate(input: $input) {
+ page {
+ id
+ title
+ content
+ slug
+ isPublished
+ publishedAt
+ pageType {
+ id
+ }
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedNumericAttribute {
+ value
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
+ slug
+ }
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ }
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ slug
+ name
+ reference
+ date
+ dateTime
+ plainText
+ file {
+ url
+ contentType
+ }
}
+ }
}
+ errors {
+ field
+ code
+ message
+ attributes
+ }
+ }
+}
"""
@@ -75,9 +155,9 @@ def test_page_create_mutation(
# Default attributes defined in page_type fixture
tag_attr = page_type.page_attributes.get(name="tag")
- tag_value_slug = tag_attr.values.first().slug
+
tag_attr_id = graphene.Node.to_global_id("Attribute", tag_attr.id)
- tag_value_name = tag_attr.values.first().name
+ tag_value = tag_attr.values.first()
# Add second attribute
size_attr = page_type.page_attributes.get(name="Page size")
@@ -96,7 +176,7 @@ def test_page_create_mutation(
"slug": page_slug,
"pageType": page_type_id,
"attributes": [
- {"id": tag_attr_id, "values": [tag_value_name]},
+ {"id": tag_attr_id, "values": [tag_value.name]},
{"id": size_attr_id, "values": [non_existent_attr_value]},
{
"id": to_global_id_or_none(numeric_attribute),
@@ -129,7 +209,26 @@ def test_page_create_mutation(
data["page"]["attributes"][1]["values"][0]["slug"],
)
assert slugify(non_existent_attr_value) in values
- assert tag_value_slug in values
+ assert tag_value.slug in values
+
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_size_assigned_attribute = {
+ "attribute": {"slug": size_attr.slug},
+ "choice": {
+ "name": non_existent_attr_value,
+ "slug": slugify(non_existent_attr_value),
+ },
+ }
+ expected_tag_assigned_attribute = {
+ "attribute": {"slug": tag_attr.slug},
+ "choice": {
+ "name": tag_value.name,
+ "slug": tag_value.slug,
+ },
+ }
+ assert expected_size_assigned_attribute in assigned_attributes
+ assert expected_tag_assigned_attribute in assigned_attributes
+
assert numeric_attribute.values.filter(
name=numeric_name, numeric=numeric_value
).exists()
@@ -150,8 +249,7 @@ def test_page_create_mutation_with_published_at_date(
# Default attributes defined in page_type fixture
tag_attr = page_type.page_attributes.get(name="tag")
- tag_value_slug = tag_attr.values.first().slug
- tag_value_name = tag_attr.values.first().name
+ tag_value = tag_attr.values.first()
tag_attr_id = graphene.Node.to_global_id("Attribute", tag_attr.id)
# Add second attribute
@@ -169,7 +267,7 @@ def test_page_create_mutation_with_published_at_date(
"slug": page_slug,
"pageType": page_type_id,
"attributes": [
- {"id": tag_attr_id, "values": [tag_value_name]},
+ {"id": tag_attr_id, "values": [tag_value.name]},
{"id": size_attr_id, "values": [non_existent_attr_value]},
],
}
@@ -192,7 +290,25 @@ def test_page_create_mutation_with_published_at_date(
data["page"]["attributes"][1]["values"][0]["slug"],
)
assert slugify(non_existent_attr_value) in values
- assert tag_value_slug in values
+ assert tag_value.slug in values
+
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_size_assigned_attribute = {
+ "attribute": {"slug": size_attr.slug},
+ "choice": {
+ "name": non_existent_attr_value,
+ "slug": slugify(non_existent_attr_value),
+ },
+ }
+ expected_tag_assigned_attribute = {
+ "attribute": {"slug": tag_attr.slug},
+ "choice": {
+ "name": tag_value.name,
+ "slug": tag_value.slug,
+ },
+ }
+ assert expected_size_assigned_attribute in assigned_attributes
+ assert expected_tag_assigned_attribute in assigned_attributes
@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@@ -455,6 +571,16 @@ def test_create_page_with_file_attribute(
}
assert data["page"]["attributes"][0] == expected_attr_data
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_file_attribute.refresh_from_db()
assert page_file_attribute.values.count() == values_count + 1
@@ -537,6 +663,16 @@ def test_create_page_with_file_attribute_new_attribute_value(
}
assert data["page"]["attributes"][0] == expected_attr_data
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": new_value_content_type,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_file_attribute.refresh_from_db()
assert page_file_attribute.values.count() == values_count + 1
@@ -588,6 +724,13 @@ def test_create_page_with_file_attribute_not_required_no_file_url_given(
assert len(data["page"]["attributes"]) == 1
assert len(data["page"]["attributes"][0]["values"]) == 0
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_file_attribute.slug},
+ "file": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_page_with_file_attribute_required_no_file_url_given(
staff_api_client, permission_manage_pages, page_type, page_file_attribute
@@ -707,6 +850,13 @@ def test_create_page_with_page_reference_attribute(
}
assert data["page"]["attributes"][0] == expected_attr_data
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_page_reference_attribute.refresh_from_db()
assert page_type_page_reference_attribute.values.count() == values_count + 1
@@ -767,9 +917,15 @@ def test_create_page_with_date_attribute(
}
],
}
-
assert expected_attributes_data in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_attribute.slug},
+ "date": str(date_value),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_create_page_with_date_time_attribute(
@@ -830,6 +986,13 @@ def test_create_page_with_date_time_attribute(
assert expected_attributes_data in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_time_attribute.slug},
+ "datetime": date_time_value.isoformat(),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_page_with_plain_text_attribute(
staff_api_client,
@@ -887,9 +1050,15 @@ def test_create_page_with_plain_text_attribute(
}
],
}
-
assert expected_attributes_data in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute_page_type.slug},
+ "plain_text": text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_page_with_page_reference_attribute_not_required_no_references_given(
staff_api_client,
@@ -907,7 +1076,7 @@ def test_create_page_with_page_reference_attribute_not_required_no_references_gi
)
page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
- file_attribute_id = graphene.Node.to_global_id(
+ reference_attribute_id = graphene.Node.to_global_id(
"Attribute", page_type_page_reference_attribute.pk
)
page_type.page_attributes.add(page_type_page_reference_attribute)
@@ -923,7 +1092,7 @@ def test_create_page_with_page_reference_attribute_not_required_no_references_gi
"isPublished": page_is_published,
"slug": page_slug,
"pageType": page_type_id,
- "attributes": [{"id": file_attribute_id, "file": ""}],
+ "attributes": [{"id": reference_attribute_id}],
}
}
@@ -943,6 +1112,13 @@ def test_create_page_with_page_reference_attribute_not_required_no_references_gi
assert len(data["page"]["attributes"]) == 1
assert len(data["page"]["attributes"][0]["values"]) == 0
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_page_reference_attribute.slug},
+ "pages": [],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_page_with_page_reference_attribute_required_no_references_given(
staff_api_client,
@@ -960,7 +1136,7 @@ def test_create_page_with_page_reference_attribute_required_no_references_given(
)
page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
- file_attribute_id = graphene.Node.to_global_id(
+ reference_attribute_id = graphene.Node.to_global_id(
"Attribute", page_type_page_reference_attribute.pk
)
page_type.page_attributes.add(page_type_page_reference_attribute)
@@ -976,7 +1152,11 @@ def test_create_page_with_page_reference_attribute_required_no_references_given(
"isPublished": page_is_published,
"slug": page_slug,
"pageType": page_type_id,
- "attributes": [{"id": file_attribute_id, "file": ""}],
+ "attributes": [
+ {
+ "id": reference_attribute_id,
+ }
+ ],
}
}
@@ -992,7 +1172,7 @@ def test_create_page_with_page_reference_attribute_required_no_references_given(
assert len(errors) == 1
assert errors[0]["code"] == PageErrorCode.REQUIRED.name
assert errors[0]["field"] == "attributes"
- assert errors[0]["attributes"] == [file_attribute_id]
+ assert errors[0]["attributes"] == [reference_attribute_id]
def test_create_page_with_product_reference_attribute(
@@ -1067,6 +1247,13 @@ def test_create_page_with_product_reference_attribute(
}
assert data["page"]["attributes"][0] == expected_attr_data
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_product_reference_attribute.refresh_from_db()
assert page_type_product_reference_attribute.values.count() == values_count + 1
@@ -1087,7 +1274,7 @@ def test_create_page_with_product_reference_attribute_not_required_no_references
)
page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
- file_attribute_id = graphene.Node.to_global_id(
+ reference_attribute_id = graphene.Node.to_global_id(
"Attribute", page_type_product_reference_attribute.pk
)
page_type.page_attributes.add(page_type_product_reference_attribute)
@@ -1103,7 +1290,7 @@ def test_create_page_with_product_reference_attribute_not_required_no_references
"isPublished": page_is_published,
"slug": page_slug,
"pageType": page_type_id,
- "attributes": [{"id": file_attribute_id, "file": ""}],
+ "attributes": [{"id": reference_attribute_id}],
}
}
@@ -1123,6 +1310,13 @@ def test_create_page_with_product_reference_attribute_not_required_no_references
assert len(data["page"]["attributes"]) == 1
assert len(data["page"]["attributes"][0]["values"]) == 0
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_product_reference_attribute.slug},
+ "products": [],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_page_with_product_reference_attribute_required_no_references_given(
staff_api_client,
@@ -1247,6 +1441,13 @@ def test_create_page_with_variant_reference_attribute(
}
assert data["page"]["attributes"][0] == expected_attr_data
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_variant_reference_attribute.refresh_from_db()
assert page_type_variant_reference_attribute.values.count() == values_count + 1
@@ -1322,6 +1523,13 @@ def test_create_page_with_category_reference_attribute(
}
assert data["page"]["attributes"][0] == expected_attr_data
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_category_reference_attribute.slug},
+ "categories": [{"slug": category.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_category_reference_attribute.refresh_from_db()
assert page_type_category_reference_attribute.values.count() == values_count + 1
@@ -1396,6 +1604,12 @@ def test_create_page_with_collection_reference_attribute(
],
}
assert data["page"]["attributes"][0] == expected_attr_data
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_collection_reference_attribute.slug},
+ "collections": [{"slug": collection.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
page_type_collection_reference_attribute.refresh_from_db()
assert page_type_collection_reference_attribute.values.count() == values_count + 1
@@ -1513,6 +1727,34 @@ def test_create_page_with_single_reference_attributes(
for attr_data in attributes_data:
assert attr_data in expected_attributes_data
+ assigned_attributes = data["page"]["assignedAttributes"]
+
+ expected_assigned_page_attribute = {
+ "attribute": {"slug": page_type_page_single_reference_attribute.slug},
+ "page": {"slug": page.slug},
+ }
+ expected_assigned_product_attribute = {
+ "attribute": {"slug": page_type_product_single_reference_attribute.slug},
+ "product": {"slug": product.slug},
+ }
+ expected_assigned_variant_attribute = {
+ "attribute": {"slug": page_type_variant_single_reference_attribute.slug},
+ "variant": {"sku": product_variant_list[0].sku},
+ }
+ expected_assigned_category_attribute = {
+ "attribute": {"slug": page_type_category_single_reference_attribute.slug},
+ "category": {"slug": categories[0].slug},
+ }
+ expected_assigned_collection_attribute = {
+ "attribute": {"slug": page_type_collection_single_reference_attribute.slug},
+ "collection": {"slug": collection.slug},
+ }
+ assert expected_assigned_page_attribute in assigned_attributes
+ assert expected_assigned_product_attribute in assigned_attributes
+ assert expected_assigned_variant_attribute in assigned_attributes
+ assert expected_assigned_category_attribute in assigned_attributes
+ assert expected_assigned_collection_attribute in assigned_attributes
+
@freeze_time("2020-03-18 12:00:00")
def test_page_create_mutation_with_numeric_attribue(
@@ -1567,6 +1809,13 @@ def test_page_create_mutation_with_numeric_attribue(
)
assert attribute["values"][0]["name"] == numeric_name
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": numeric_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert numeric_attribute.values.filter(
name=numeric_name, numeric=numeric_value
).exists()
diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.py
index 2a781340a2..560398c7aa 100644
--- a/saleor/graphql/page/tests/mutations/test_page_update.py
+++ b/saleor/graphql/page/tests/mutations/test_page_update.py
@@ -26,41 +26,119 @@ from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
UPDATE_PAGE_MUTATION = """
- mutation updatePage(
- $id: ID!, $input: PageInput!
- ) {
- pageUpdate(
- id: $id, input: $input
- ) {
- page {
- id
- title
- slug
- isPublished
- publishedAt
- attributes {
- attribute {
- slug
- }
- values {
- slug
- name
- reference
- file {
- url
- contentType
- }
- plainText
- }
- }
- }
- errors {
- field
- code
- message
- }
+mutation updatePage($id: ID!, $input: PageInput!) {
+ pageUpdate(id: $id, input: $input) {
+ page {
+ id
+ title
+ slug
+ isPublished
+ publishedAt
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedNumericAttribute {
+ value
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
+ slug
+ }
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
}
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ }
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ slug
+ name
+ reference
+ file {
+ url
+ contentType
+ }
+ plainText
+ }
+ }
}
+ errors {
+ field
+ code
+ message
+ }
+ }
+}
"""
@@ -101,23 +179,24 @@ def test_update_page(staff_api_client, permission_manage_pages, page):
assert data["page"]["title"] == page_title
assert data["page"]["slug"] == new_slug
- expected_attributes = []
- for attr in page_type.page_attributes.all():
- if attr.slug != tag_attr.slug:
- values = [
+ size_attr, tag_attr = page_type.page_attributes.all()
+ size_attr_value = get_page_attribute_values(page, size_attr).get()
+ expected_attributes = [
+ {
+ "attribute": {"slug": size_attr.slug},
+ "values": [
{
- "slug": slug,
+ "slug": size_attr_value.slug,
"file": None,
- "name": name,
+ "name": size_attr_value.name,
"reference": None,
"plainText": None,
}
- for slug, name in get_page_attribute_values(page, attr).values_list(
- "slug", "name"
- )
- ]
- else:
- values = [
+ ],
+ },
+ {
+ "attribute": {"slug": tag_attr.slug},
+ "values": [
{
"slug": slugify(new_value),
"file": None,
@@ -125,18 +204,33 @@ def test_update_page(staff_api_client, permission_manage_pages, page):
"plainText": None,
"reference": None,
}
- ]
- attr_data = {
- "attribute": {"slug": attr.slug},
- "values": values,
- }
- expected_attributes.append(attr_data)
+ ],
+ },
+ ]
attributes = data["page"]["attributes"]
assert len(attributes) == len(expected_attributes)
for attr_data in attributes:
assert attr_data in expected_attributes
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_size_assigned_attribute = {
+ "attribute": {"slug": size_attr.slug},
+ "choice": {
+ "name": size_attr_value.name,
+ "slug": size_attr_value.slug,
+ },
+ }
+ expected_tag_assigned_attribute = {
+ "attribute": {"slug": tag_attr.slug},
+ "choice": {
+ "name": new_value,
+ "slug": slugify(new_value),
+ },
+ }
+ assert expected_size_assigned_attribute in assigned_attributes
+ assert expected_tag_assigned_attribute in assigned_attributes
+
@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
@@ -229,31 +323,47 @@ def test_update_page_only_title(staff_api_client, permission_manage_pages, page)
assert data["page"]["title"] == page_title
assert data["page"]["slug"] == new_slug
- expected_attributes = []
- for attr in page_type.page_attributes.all():
- values = [
- {
- "slug": slug,
- "file": None,
- "name": name,
- "reference": None,
- "plainText": None,
- }
- for slug, name in get_page_attribute_values(page, attr).values_list(
- "slug", "name"
- )
- ]
- attr_data = {
- "attribute": {"slug": attr.slug},
- "values": values,
- }
- expected_attributes.append(attr_data)
+ size_attr, tag_attr = page_type.page_attributes.all()
+ size_attr_value = get_page_attribute_values(page, size_attr).get()
+ expected_attributes = [
+ {
+ "attribute": {"slug": size_attr.slug},
+ "values": [
+ {
+ "slug": size_attr_value.slug,
+ "file": None,
+ "name": size_attr_value.name,
+ "reference": None,
+ "plainText": None,
+ }
+ ],
+ },
+ {
+ "attribute": {"slug": tag_attr.slug},
+ "values": [],
+ },
+ ]
attributes = data["page"]["attributes"]
assert len(attributes) == len(expected_attributes)
for attr_data in attributes:
assert attr_data in expected_attributes
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_size_assigned_attribute = {
+ "attribute": {"slug": size_attr.slug},
+ "choice": {
+ "name": size_attr_value.name,
+ "slug": size_attr_value.slug,
+ },
+ }
+ expected_tag_assigned_attribute = {
+ "attribute": {"slug": tag_attr.slug},
+ "choice": None,
+ }
+ assert expected_size_assigned_attribute in assigned_attributes
+ assert expected_tag_assigned_attribute in assigned_attributes
+
def test_update_page_with_file_attribute_value(
staff_api_client, permission_manage_pages, page, page_file_attribute
@@ -304,6 +414,16 @@ def test_update_page_with_file_attribute_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_update_page_with_file_attribute_new_value_is_not_created(
staff_api_client, permission_manage_pages, page, page_file_attribute
@@ -357,6 +477,16 @@ def test_update_page_with_file_attribute_new_value_is_not_created(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": existing_value.content_type,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_update_page_clear_file_attribute_values(
staff_api_client, permission_manage_pages, page, page_file_attribute
@@ -403,6 +533,13 @@ def test_update_page_clear_file_attribute_values(
if attr["attribute"]["slug"] == attribute.slug
][0]
assert not attr_data["values"]
+
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_file_attribute.slug},
+ "file": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
assert not get_page_attribute_values(page, page_file_attribute).exists()
@@ -458,6 +595,13 @@ def test_update_page_with_page_reference_attribute_new_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_page_reference_attribute.slug},
+ "pages": [{"slug": ref_page.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_page_reference_attribute.refresh_from_db()
assert page_type_page_reference_attribute.values.count() == values_count + 1
@@ -524,6 +668,13 @@ def test_update_page_with_page_reference_attribute_existing_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_page_reference_attribute.slug},
+ "pages": [{"slug": ref_page.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_page_reference_attribute.refresh_from_db()
assert page_type_page_reference_attribute.values.count() == values_count
@@ -579,6 +730,13 @@ def test_update_page_with_plain_text_attribute_new_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute_page_type.slug},
+ "plain_text": text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
plain_text_attribute_page_type.refresh_from_db()
assert plain_text_attribute_page_type.values.count() == values_count + 1
@@ -638,6 +796,13 @@ def test_update_page_with_plain_text_attribute_existing_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute_page_type.slug},
+ "plain_text": text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
plain_text_attribute_page_type.refresh_from_db()
assert plain_text_attribute_page_type.values.count() == values_count
@@ -741,6 +906,13 @@ def test_update_page_with_product_reference_attribute_new_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_product_reference_attribute.refresh_from_db()
assert page_type_product_reference_attribute.values.count() == values_count + 1
@@ -807,6 +979,13 @@ def test_update_page_with_product_reference_attribute_existing_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_product_reference_attribute.refresh_from_db()
assert page_type_product_reference_attribute.values.count() == values_count
@@ -862,6 +1041,13 @@ def test_update_page_with_variant_reference_attribute_new_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_variant_reference_attribute.refresh_from_db()
assert page_type_variant_reference_attribute.values.count() == values_count + 1
@@ -928,6 +1114,13 @@ def test_update_page_with_variant_reference_attribute_existing_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_variant_reference_attribute.refresh_from_db()
assert page_type_variant_reference_attribute.values.count() == values_count
@@ -981,6 +1174,13 @@ def test_update_page_with_category_reference_attribute_new_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_category_reference_attribute.slug},
+ "categories": [{"slug": category.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_category_reference_attribute.refresh_from_db()
assert page_type_category_reference_attribute.values.count() == values_count + 1
@@ -1034,6 +1234,13 @@ def test_update_page_with_collection_reference_attribute_new_value(
}
assert updated_attribute in data["page"]["attributes"]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": page_type_collection_reference_attribute.slug},
+ "collections": [{"slug": collection.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
page_type_collection_reference_attribute.refresh_from_db()
assert page_type_collection_reference_attribute.values.count() == values_count + 1
@@ -1158,6 +1365,41 @@ UPDATE_PAGE_ATTRIBUTES_MUTATION = """
id
title
slug
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ }
attributes {
attribute {
slug
@@ -1240,7 +1482,15 @@ def test_update_page_change_attribute_values_ordering(
get_page_attribute_values(page, attribute).values_list("id", flat=True)
) == [attr_value_3.pk, attr_value_2.pk, attr_value_1.pk]
- new_ref_order = [product_list[1], product_list[0], product_list[2]]
+ expected_first_product = product_list[1]
+ expected_second_product = product_list[0]
+ expected_third_product = product_list[2]
+
+ new_ref_order = [
+ expected_first_product,
+ expected_second_product,
+ expected_third_product,
+ ]
variables = {
"id": page_id,
"input": {
@@ -1278,6 +1528,14 @@ def test_update_page_change_attribute_values_ordering(
for val in [attr_value_2, attr_value_1, attr_value_3]
]
+ assigned_attributes = data["page"]["assignedAttributes"]
+ assert len(assigned_attributes) == 1
+ assigned_values = assigned_attributes[0]["products"]
+ assert len(assigned_values) == 3
+ assert assigned_values[0]["slug"] == expected_first_product.slug
+ assert assigned_values[1]["slug"] == expected_second_product.slug
+ assert assigned_values[2]["slug"] == expected_third_product.slug
+
assert list(
get_page_attribute_values(page, attribute).values_list("id", flat=True)
) == [attr_value_2.pk, attr_value_1.pk, attr_value_3.pk]
@@ -1417,6 +1675,34 @@ def test_update_page_with_single_reference_attributes(
for attr_data in attributes_data:
assert attr_data in expected_attributes_data
+ assigned_attributes = data["page"]["assignedAttributes"]
+
+ expected_assigned_page_attribute = {
+ "attribute": {"slug": page_type_page_single_reference_attribute.slug},
+ "page": {"slug": page_ref.slug},
+ }
+ expected_assigned_product_attribute = {
+ "attribute": {"slug": page_type_product_single_reference_attribute.slug},
+ "product": {"slug": product.slug},
+ }
+ expected_assigned_variant_attribute = {
+ "attribute": {"slug": page_type_variant_single_reference_attribute.slug},
+ "variant": {"sku": product_variant_list[0].sku},
+ }
+ expected_assigned_category_attribute = {
+ "attribute": {"slug": page_type_category_single_reference_attribute.slug},
+ "category": {"slug": categories[0].slug},
+ }
+ expected_assigned_collection_attribute = {
+ "attribute": {"slug": page_type_collection_single_reference_attribute.slug},
+ "collection": {"slug": collection.slug},
+ }
+ assert expected_assigned_page_attribute in assigned_attributes
+ assert expected_assigned_product_attribute in assigned_attributes
+ assert expected_assigned_variant_attribute in assigned_attributes
+ assert expected_assigned_category_attribute in assigned_attributes
+ assert expected_assigned_collection_attribute in assigned_attributes
+
def test_update_page_with_numeric_attribute(
staff_api_client, permission_manage_pages, page, numeric_attribute
@@ -1460,6 +1746,13 @@ def test_update_page_with_numeric_attribute(
assert attributes[0]["values"][0]["slug"] == f"{page.pk}_{numeric_attribute.pk}"
assert attributes[0]["values"][0]["name"] == numeric_name
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": numeric_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert numeric_attribute.values.filter(
name=numeric_name,
numeric=numeric_value,
diff --git a/saleor/graphql/page/tests/queries/test_page.py b/saleor/graphql/page/tests/queries/test_page.py
index 5a56cf7ee8..b19b1c676d 100644
--- a/saleor/graphql/page/tests/queries/test_page.py
+++ b/saleor/graphql/page/tests/queries/test_page.py
@@ -24,6 +24,22 @@ PAGE_QUERY = """
}
content
contentJson
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ }
attributes {
attribute {
id
@@ -83,12 +99,25 @@ def test_query_published_page(user_api_client, page):
else []
)
expected_attributes.append(
- {"attribute": {"id": attr_id, "slug": attr.slug}, "values": values}
+ {
+ "attribute": {"id": attr_id, "slug": attr.slug},
+ "values": values,
+ }
)
for attr_data in page_data["attributes"]:
assert attr_data in expected_attributes
+ assigned_attributes = page_data["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": page_attr.slug},
+ "choice": {
+ "name": page_attr_value.name,
+ "slug": page_attr_value.slug,
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
# query by slug
variables = {"slug": page.slug}
response = user_api_client.post_graphql(PAGE_QUERY, variables)
@@ -288,18 +317,24 @@ def test_get_page_with_sorted_attribute_values(
attribute=page_type_product_reference_attribute,
name=product_list[0].name,
slug=f"{page.pk}_{product_list[0].pk}",
+ reference_product=product_list[0],
)
attr_value_2 = AttributeValue.objects.create(
attribute=page_type_product_reference_attribute,
name=product_list[1].name,
slug=f"{page.pk}_{product_list[1].pk}",
+ reference_product=product_list[1],
)
attr_value_3 = AttributeValue.objects.create(
attribute=page_type_product_reference_attribute,
name=product_list[2].name,
slug=f"{page.pk}_{product_list[2].pk}",
+ reference_product=product_list[2],
)
+ expected_first_product = product_list[1]
+ expected_second_product = product_list[0]
+ expected_third_product = product_list[2]
attr_values = [attr_value_2, attr_value_1, attr_value_3]
associate_attribute_values_to_instance(
page, {page_type_product_reference_attribute.pk: attr_values}
@@ -322,6 +357,14 @@ def test_get_page_with_sorted_attribute_values(
graphene.Node.to_global_id("AttributeValue", val.pk) for val in attr_values
]
+ assigned_attributes = data["assignedAttributes"]
+ assert len(assigned_attributes) == 1
+ assigned_values = assigned_attributes[0]["products"]
+ assert len(assigned_values) == 3
+ assert assigned_values[0]["slug"] == expected_first_product.slug
+ assert assigned_values[1]["slug"] == expected_second_product.slug
+ assert assigned_values[2]["slug"] == expected_third_product.slug
+
def test_page_attributes_not_visible_in_storefront_for_customer_is_not_returned(
user_api_client, page
@@ -346,16 +389,17 @@ def test_page_attributes_not_visible_in_storefront_for_customer_is_not_returned(
# 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 == {}
+ assert len(content["data"]["page"]["assignedAttributes"]) == visible_attrs_count
+ not_visible_attr_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+ not_visible_attr_slug = attribute.slug
+ assert not_visible_attr_id not in [
+ attr_data["attribute"]["id"]
+ for attr_data in content["data"]["page"]["attributes"]
+ ]
+ assert not_visible_attr_slug not in [
+ attr_data["attribute"]["slug"]
+ for attr_data in content["data"]["page"]["assignedAttributes"]
+ ]
def test_page_attributes_visible_in_storefront_for_customer_is_returned(
@@ -377,21 +421,17 @@ def test_page_attributes_visible_in_storefront_for_customer_is_returned(
# 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,
- }
- }
+
+ visible_attr_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+ visible_attr_slug = attribute.slug
+ assert visible_attr_id in [
+ attr_data["attribute"]["id"]
+ for attr_data in content["data"]["page"]["attributes"]
+ ]
+ assert visible_attr_slug in [
+ attr_data["attribute"]["slug"]
+ for attr_data in content["data"]["page"]["assignedAttributes"]
+ ]
@pytest.mark.parametrize("visible_in_storefront", [False, True])
@@ -418,21 +458,17 @@ def test_page_attributes_visible_in_storefront_for_staff_is_always_returned(
# 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,
- }
- }
+
+ visible_attr_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+ visible_attr_slug = attribute.slug
+ assert visible_attr_id in [
+ attr_data["attribute"]["id"]
+ for attr_data in content["data"]["page"]["attributes"]
+ ]
+ assert visible_attr_slug in [
+ attr_data["attribute"]["slug"]
+ for attr_data in content["data"]["page"]["assignedAttributes"]
+ ]
def test_page_query_by_translated_slug(user_api_client, page, page_translation_fr):
@@ -460,6 +496,38 @@ def test_page_query_by_translated_slug(user_api_client, page, page_translation_f
QUERY_PAGE_WITH_ATTRIBUTE = """
query Page($id: ID!, $slug: String!) {
page(id: $id) {
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ }
+ assignedAttribute(slug: $slug) {
+ attribute {
+ slug
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ }
attribute(slug: $slug) {
attribute {
id
@@ -495,9 +563,13 @@ def test_page_attribute_field_filtering(staff_api_client, page):
# then
expected_slug = slug
content = get_graphql_content(response)
- queried_slug = content["data"]["page"]["attribute"]["attribute"]["slug"]
+ page_data = content["data"]["page"]
+ queried_slug = page_data["attribute"]["attribute"]["slug"]
assert queried_slug == expected_slug
+ assigned_queried_slug = page_data["assignedAttribute"]["attribute"]["slug"]
+ assert assigned_queried_slug == expected_slug
+
def test_page_attribute_field_filtering_not_found(staff_api_client, page):
# given
@@ -517,6 +589,7 @@ def test_page_attribute_field_filtering_not_found(staff_api_client, page):
# then
content = get_graphql_content(response)
assert content["data"]["page"]["attribute"] is None
+ assert content["data"]["page"]["assignedAttribute"] is None
def test_page_attribute_not_visible_in_storefront_for_customer_is_not_returned(
@@ -544,13 +617,18 @@ def test_page_attribute_not_visible_in_storefront_for_customer_is_not_returned(
content = get_graphql_content(response)
assert content["data"]["page"]["attribute"] is None
assert len(content["data"]["page"]["attributes"]) == visible_attrs_count
- attr_data = {
- "attribute": {
- "id": graphene.Node.to_global_id("Attribute", attribute.pk),
- "slug": attribute.slug,
- }
- }
- assert attr_data not in content["data"]["page"]["attributes"]
+ assert len(content["data"]["page"]["assignedAttributes"]) == visible_attrs_count
+
+ not_visible_attr_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+ not_visible_attr_slug = attribute.slug
+ assert not_visible_attr_id not in [
+ attr_data["attribute"]["id"]
+ for attr_data in content["data"]["page"]["attributes"]
+ ]
+ assert not_visible_attr_slug not in [
+ attr_data["attribute"]["slug"]
+ for attr_data in content["data"]["page"]["assignedAttributes"]
+ ]
def test_page_attribute_visible_in_storefront_for_customer_is_returned(
@@ -573,7 +651,10 @@ def test_page_attribute_visible_in_storefront_for_customer_is_returned(
# then
content = get_graphql_content(response)
- assert content["data"]["page"]["attribute"]["attribute"]["slug"] == attribute.slug
+ page_data = content["data"]["page"]
+
+ assert page_data["attribute"]["attribute"]["slug"] == attribute.slug
+ assert page_data["assignedAttribute"]["attribute"]["slug"] == attribute.slug
@pytest.mark.parametrize("visible_in_storefront", [False, True])
@@ -601,7 +682,10 @@ def test_page_attribute_visible_in_storefront_for_staff_is_always_returned(
# then
content = get_graphql_content(response)
- assert content["data"]["page"]["attribute"]["attribute"]["slug"] == attribute.slug
+ page_data = content["data"]["page"]
+
+ assert page_data["attribute"]["attribute"]["slug"] == attribute.slug
+ assert page_data["assignedAttribute"]["attribute"]["slug"] == attribute.slug
def test_page_channel_not_found(staff_api_client, page, permission_manage_pages):
@@ -626,3 +710,50 @@ def test_page_channel_not_found(staff_api_client, page, permission_manage_pages)
# then
content = get_graphql_content(response)
assert content["data"]["page"] is None
+
+
+def test_applies_limit_on_page_assigned_attributes(
+ page, channel_USD, user_api_client, size_page_attribute, tag_page_attribute
+):
+ # given
+ query = """
+ query Page($id: ID!, $channel: String) {
+ page(id: $id, channel: $channel) {
+ assignedAttributes(limit:1) {
+ attribute {
+ slug
+ }
+ }
+ }
+ }
+ """
+
+ associate_attribute_values_to_instance(
+ page,
+ {
+ size_page_attribute.pk: [size_page_attribute.values.first()],
+ tag_page_attribute.pk: [tag_page_attribute.values.first()],
+ },
+ )
+
+ assert page.attributevalues.count() == 2
+ first_attribute = page.attributevalues.first().value.attribute
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+ variables = {
+ "id": page_id,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ expected_limit = 1
+ assert len(content["data"]["page"]["assignedAttributes"]) == expected_limit
+ assert (
+ content["data"]["page"]["assignedAttributes"][0]["attribute"]["slug"]
+ == first_attribute.slug
+ )
diff --git a/saleor/graphql/page/tests/queries/test_pages.py b/saleor/graphql/page/tests/queries/test_pages.py
index 85531bdee6..21c83d72b9 100644
--- a/saleor/graphql/page/tests/queries/test_pages.py
+++ b/saleor/graphql/page/tests/queries/test_pages.py
@@ -250,31 +250,156 @@ def test_query_pages_with_sort(
PAGES_QUERY = """
- query {
- pages(first: 10) {
- edges {
- node {
- id
- title
- slug
- pageType {
- id
- }
- content
- contentJson
- attributes {
- attribute {
- slug
- }
- values {
- id
- slug
- }
- }
- }
+{
+ pages(first: 10) {
+ edges {
+ node {
+ id
+ title
+ slug
+ pageType {
+ id
+ }
+ content
+ contentJson
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ id
+ slug
+ }
+ }
+ assignedAttributes(limit:5) {
+ attr: attribute {
+ slug
+ }
+ ... on AssignedNumericAttribute {
+ attribute {
+ id
+ }
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ text_translation: translation(languageCode: FR)
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ plain_translation: translation(languageCode: FR)
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant_ref: value {
+ __typename
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ __typename
+ pages: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ __typename
+ producs: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ __typename
+ variants: value {
+ __typename
+ sku
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ __typename
+ categories: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ __typename
+ collections: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleChoiceAttribute {
+ __typename
+ choice: value {
+ name
+ slug
+ translation(languageCode: FR)
+ }
+ }
+ ... on AssignedMultiChoiceAttribute {
+ __typename
+ choices: value {
+ name
+ slug
+ translation(languageCode: FR)
+ }
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
+ }
}
+ }
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
}
+ }
}
+ }
+}
"""
diff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.py
index 5f5c46c60e..5fb4dce804 100644
--- a/saleor/graphql/page/types.py
+++ b/saleor/graphql/page/types.py
@@ -1,3 +1,5 @@
+from typing import cast
+
import graphene
from ...attribute import models as attribute_models
@@ -9,22 +11,24 @@ from ..attribute.filters import (
filter_attribute_search,
)
from ..attribute.types import Attribute, AttributeCountableConnection, SelectedAttribute
+from ..attribute.utils.shared import AssignedAttributeData
from ..core import ResolveInfo
from ..core.connection import (
CountableConnection,
create_connection_slice,
filter_connection_queryset,
)
+from ..core.const import DEFAULT_NESTED_LIST_LIMIT
from ..core.context import (
ChannelContext,
ChannelQsContext,
get_database_connection_name,
)
-from ..core.descriptions import DEPRECATED_IN_3X_INPUT, RICH_CONTENT
+from ..core.descriptions import ADDED_IN_322, DEPRECATED_IN_3X_INPUT, RICH_CONTENT
from ..core.doc_category import DOC_CATEGORY_PAGES
from ..core.federation import federated_entity, resolve_federation_references
from ..core.fields import FilterConnectionField, JSONString, PermissionsField
-from ..core.scalars import Date, DateTime
+from ..core.scalars import Date, DateTime, PositiveInt
from ..core.types import ModelObjectType, NonNullList
from ..core.types.context import ChannelContextType
from ..meta.types import ObjectWithMetadata
@@ -32,14 +36,14 @@ from ..translations.fields import TranslationField
from ..translations.types import PageTranslation
from ..utils import get_user_or_app_from_context
from .dataloaders import (
+ AssignedAttributeAllByPageIdAttributeSlugLoader,
+ AssignedAttributesAllByPageIdLoader,
+ AssignedAttributesVisibleInStorefrontPageIdLoader,
+ AssignedAttributeVisibleInStorefrontPageIdAttributeSlugLoader,
PageAttributesAllByPageTypeIdLoader,
PageAttributesVisibleInStorefrontByPageTypeIdLoader,
PagesByPageTypeIdLoader,
PageTypeByIdLoader,
- SelectedAttributeAllByPageIdAttributeSlugLoader,
- SelectedAttributesAllByPageIdLoader,
- SelectedAttributesVisibleInStorefrontPageIdLoader,
- SelectedAttributeVisibleInStorefrontPageIdAttributeSlugLoader,
)
@@ -185,11 +189,35 @@ class Page(ChannelContextType[models.Page]):
required=True,
),
description="Get a single attribute attached to page by attribute slug.",
+ deprecation_reason="Use `assignedAttribute` field instead.",
+ )
+ assigned_attribute = graphene.Field(
+ "saleor.graphql.attribute.types.AssignedAttribute",
+ slug=graphene.Argument(
+ graphene.String,
+ description="Slug of the attribute",
+ required=True,
+ ),
+ description="Get a single attribute attached to page by attribute slug."
+ + ADDED_IN_322,
+ )
+ assigned_attributes = NonNullList(
+ "saleor.graphql.attribute.types.AssignedAttribute",
+ required=True,
+ description="List of attributes assigned to this page." + ADDED_IN_322,
+ limit=PositiveInt(
+ description=(
+ "Maximum number of attributes to return. "
+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}."
+ ),
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
)
attributes = NonNullList(
SelectedAttribute,
required=True,
description="List of attributes assigned to this page.",
+ deprecation_reason="Use `assignedAttributes` field instead.",
)
class Meta:
@@ -218,25 +246,57 @@ class Page(ChannelContextType[models.Page]):
content = root.node.content
return content if content is not None else {}
- @staticmethod
- def resolve_attributes(root: ChannelContext[models.Page], info: ResolveInfo):
+ @classmethod
+ def resolve_assigned_attributes(
+ cls,
+ root: ChannelContext[models.Page],
+ info: ResolveInfo,
+ limit: int = DEFAULT_NESTED_LIST_LIMIT,
+ ):
+ return cls._resolve_assigned_attributes(root, info, limit)
+
+ @classmethod
+ def resolve_assigned_attribute(
+ cls, root: ChannelContext[models.Page], info: ResolveInfo, slug: str
+ ):
+ return cls._resolve_assigned_attribute(root, info, slug)
+
+ @classmethod
+ def resolve_attributes(cls, root: ChannelContext[models.Page], info: ResolveInfo):
+ return cls._resolve_assigned_attributes(root, info)
+
+ @classmethod
+ def _resolve_assigned_attributes(
+ cls,
+ root: ChannelContext[models.Page],
+ info: ResolveInfo,
+ limit: int | None = None,
+ ):
page = root.node
def wrap_with_channel_context(
attributes: list[dict[str, list]] | None,
- ) -> list[SelectedAttribute] | None:
+ ) -> list[AssignedAttributeData] | None:
if attributes is None:
return None
- return [
- SelectedAttribute(
- attribute=ChannelContext(attribute["attribute"], root.channel_slug),
- values=[
- ChannelContext(value, root.channel_slug)
- for value in attribute["values"]
- ],
+ response: list[AssignedAttributeData] = []
+ for attribute_data in attributes:
+ attribute = cast(
+ attribute_models.Attribute, attribute_data["attribute"]
+ )
+ values = cast(
+ list[attribute_models.AttributeValue], attribute_data["values"]
)
- for attribute in attributes
- ]
+ response.append(
+ AssignedAttributeData(
+ attribute=ChannelContext(attribute, root.channel_slug),
+ values=[
+ ChannelContext(value, root.channel_slug) for value in values
+ ],
+ )
+ )
+ response = response[:limit] if limit is not None else response
+ return response
requestor = get_user_or_app_from_context(info.context)
if (
@@ -245,35 +305,41 @@ class Page(ChannelContextType[models.Page]):
and requestor.has_perm(PagePermissions.MANAGE_PAGES)
):
return (
- SelectedAttributesAllByPageIdLoader(info.context)
+ AssignedAttributesAllByPageIdLoader(info.context)
.load(page.id)
.then(wrap_with_channel_context)
)
return (
- SelectedAttributesVisibleInStorefrontPageIdLoader(info.context)
+ AssignedAttributesVisibleInStorefrontPageIdLoader(info.context)
.load(page.id)
.then(wrap_with_channel_context)
)
- @staticmethod
+ @classmethod
def resolve_attribute(
- root: ChannelContext[models.Page], info: ResolveInfo, slug: str
+ cls, root: ChannelContext[models.Page], info: ResolveInfo, slug: str
+ ):
+ return cls._resolve_assigned_attribute(root, info, slug)
+
+ @classmethod
+ def _resolve_assigned_attribute(
+ cls, root: ChannelContext[models.Page], info: ResolveInfo, slug: str
):
page = root.node
def wrap_with_channel_context(
attribute_data: dict[str, dict | list[dict]] | None,
- ) -> SelectedAttribute | None:
+ ) -> AssignedAttributeData | None:
if attribute_data is None:
return None
- return SelectedAttribute(
- attribute=ChannelContext(
- attribute_data["attribute"], root.channel_slug
- ),
- values=[
- ChannelContext(value, root.channel_slug)
- for value in attribute_data["values"]
- ],
+ attribute = cast(attribute_models.Attribute, attribute_data["attribute"])
+ values = cast(
+ list[attribute_models.AttributeValue], attribute_data["values"]
+ )
+
+ return AssignedAttributeData(
+ attribute=ChannelContext(attribute, root.channel_slug),
+ values=[ChannelContext(value, root.channel_slug) for value in values],
)
requestor = get_user_or_app_from_context(info.context)
@@ -283,12 +349,12 @@ class Page(ChannelContextType[models.Page]):
and requestor.has_perm(PagePermissions.MANAGE_PAGES)
):
return (
- SelectedAttributeAllByPageIdAttributeSlugLoader(info.context)
+ AssignedAttributeAllByPageIdAttributeSlugLoader(info.context)
.load((page.id, slug))
.then(wrap_with_channel_context)
)
return (
- SelectedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(info.context)
+ AssignedAttributeVisibleInStorefrontPageIdAttributeSlugLoader(info.context)
.load((page.id, slug))
.then(wrap_with_channel_context)
)
diff --git a/saleor/graphql/product/dataloaders/__init__.py b/saleor/graphql/product/dataloaders/__init__.py
index 7a51246495..e7a949bb6d 100644
--- a/saleor/graphql/product/dataloaders/__init__.py
+++ b/saleor/graphql/product/dataloaders/__init__.py
@@ -1,9 +1,9 @@
from .attributes import (
+ AssignedAttributesAllByProductIdLoader,
+ AssignedAttributesByProductVariantIdLoader,
+ AssignedAttributesVisibleInStorefrontByProductIdLoader,
ProductAttributesAllByProductTypeIdLoader,
ProductAttributesVisibleInStorefrontByProductTypeIdLoader,
- SelectedAttributesAllByProductIdLoader,
- SelectedAttributesByProductVariantIdLoader,
- SelectedAttributesVisibleInStorefrontByProductIdLoader,
VariantAttributesAllByProductTypeIdLoader,
VariantAttributesVisibleInStorefrontByProductTypeIdLoader,
)
@@ -71,9 +71,9 @@ __all__ = [
"ProductVariantsByProductIdLoader",
"ProductMediaByIdLoader",
"MediaByProductVariantIdLoader",
- "SelectedAttributesAllByProductIdLoader",
- "SelectedAttributesByProductVariantIdLoader",
- "SelectedAttributesVisibleInStorefrontByProductIdLoader",
+ "AssignedAttributesAllByProductIdLoader",
+ "AssignedAttributesByProductVariantIdLoader",
+ "AssignedAttributesVisibleInStorefrontByProductIdLoader",
"ThumbnailByCategoryIdSizeAndFormatLoader",
"ThumbnailByCollectionIdSizeAndFormatLoader",
"ThumbnailByProductMediaIdSizeAndFormatLoader",
diff --git a/saleor/graphql/product/dataloaders/attributes.py b/saleor/graphql/product/dataloaders/attributes.py
index 0443fc37cf..632d81d782 100644
--- a/saleor/graphql/product/dataloaders/attributes.py
+++ b/saleor/graphql/product/dataloaders/attributes.py
@@ -262,15 +262,15 @@ class AttributeValuesVisibleInStorefrontByProductIdLoader(
return ProductAttributesVisibleInStorefrontByProductTypeIdLoader(self.context)
-class SelectedAttributesAllByProductIdLoader(DataLoader):
- context_key = "selectedattributes_all_by_product"
+class AssignedAttributesAllByProductIdLoader(DataLoader):
+ context_key = "assignedAttributes_all_by_product"
def batch_load(self, product_ids):
return AttributeValuesAllByProductIdLoader(self.context).load_many(product_ids)
-class SelectedAttributesVisibleInStorefrontByProductIdLoader(DataLoader):
- context_key = "selectedattributes_visible_in_storefront_by_product"
+class AssignedAttributesVisibleInStorefrontByProductIdLoader(DataLoader):
+ context_key = "assignedattributes_visible_in_storefront_by_product"
def batch_load(self, product_ids):
return AttributeValuesVisibleInStorefrontByProductIdLoader(
@@ -278,8 +278,8 @@ class SelectedAttributesVisibleInStorefrontByProductIdLoader(DataLoader):
).load_many(product_ids)
-class SelectedAttributesByProductVariantIdLoader(DataLoader):
- context_key = "selectedattributes_by_productvariant"
+class AssignedAttributesByProductVariantIdLoader(DataLoader):
+ context_key = "assignedattributes_by_productvariant"
def batch_load(self, keys):
def with_variants_and_assigned_attributed(results):
diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
index 4f55a9dcce..f817620c19 100644
--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
@@ -22,64 +22,163 @@ from ....tests.utils import (
)
PRODUCT_BULK_CREATE_MUTATION = """
- mutation ProductBulkCreate(
- $products: [ProductBulkCreateInput!]!
- $errorPolicy: ErrorPolicyEnum
- ) {
- productBulkCreate(products: $products, errorPolicy: $errorPolicy) {
- results {
- errors {
- path
- code
- message
- warehouses
- channels
- }
- product{
- id
- name
- slug
- media{
- url
- alt
- type
- oembedData
- }
- category{
- name
- }
- collections{
- id
- }
- description
- attributes{
- attribute{
- slug
- }
- values{
- value
- }
- }
- channelListings{
- id
- channel{
- name
- }
- }
- variants{
- name
- stocks{
- warehouse{
- slug
- }
- quantity
- }
- }
- }
+mutation ProductBulkCreate($products: [ProductBulkCreateInput!]!, $errorPolicy: ErrorPolicyEnum) {
+ productBulkCreate(products: $products, errorPolicy: $errorPolicy) {
+ results {
+ errors {
+ path
+ code
+ message
+ warehouses
+ channels
+ }
+ product {
+ id
+ name
+ slug
+ media {
+ url
+ alt
+ type
+ oembedData
+ }
+ category {
+ name
+ }
+ collections {
+ id
+ }
+ description
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ value
+ }
+ }
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedNumericAttribute {
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
}
- count
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiChoiceAttribute {
+ multi: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
+ }
+ }
+ }
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
+ }
+ channelListings {
+ id
+ channel {
+ name
+ }
}
+ variants {
+ name
+ stocks {
+ warehouse {
+ slug
+ }
+ quantity
+ }
+ }
+ }
}
+ count
+ }
+}
"""
@@ -790,6 +889,16 @@ def test_product_bulk_create_with_attributes(
== color_attr.slug
)
+ first_p_assigned_attributes = data["results"][0]["product"]["assignedAttributes"]
+ assert len(first_p_assigned_attributes) == 2
+ assert first_p_assigned_attributes[0]["choice"]["name"] == color_value_name
+ assert first_p_assigned_attributes[1]["choice"]["name"] == non_existent_attr_value
+
+ second_p_assigned_attributes = data["results"][1]["product"]["assignedAttributes"]
+ assert len(second_p_assigned_attributes) == 2
+ assert second_p_assigned_attributes[0]["choice"]["name"] == color_value_name
+ assert second_p_assigned_attributes[1]["choice"]["name"] == non_existent_attr_value
+
for product in products:
product_attributes = get_product_attributes(product)
assert len(product_attributes) == 2
@@ -874,6 +983,16 @@ def test_product_bulk_create_with_single_reference_attributes(
== attribute.slug
)
+ first_p_assigned_attributes = data["results"][0]["product"]["assignedAttributes"]
+ second_p_assigned_attributes = data["results"][1]["product"]["assignedAttributes"]
+
+ expected_assigned_page_attribute = {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "page": {"slug": page.slug},
+ }
+ assert expected_assigned_page_attribute in first_p_assigned_attributes
+ assert expected_assigned_page_attribute in second_p_assigned_attributes
+
def test_product_bulk_create_with_attributes_using_external_refs(
staff_api_client,
@@ -897,7 +1016,8 @@ def test_product_bulk_create_with_attributes_using_external_refs(
# Default attribute defined in product_type fixture
color_attr = product_type.product_attributes.get(name="Color")
- color_value_external_reference = color_attr.values.first().external_reference
+ color_value = color_attr.values.first()
+ color_value_external_reference = color_value.external_reference
# Add second attribute
product_type.product_attributes.add(size_attribute)
@@ -942,6 +1062,11 @@ def test_product_bulk_create_with_attributes_using_external_refs(
== color_attr.slug
)
+ first_p_assigned_attributes = data["results"][0]["product"]["assignedAttributes"]
+ assert len(first_p_assigned_attributes) == 2
+ assert first_p_assigned_attributes[0]["choice"]["name"] == color_value.name
+ assert first_p_assigned_attributes[1]["choice"]["name"] == non_existent_attr_value
+
for product in products:
attributes = get_product_attributes(product)
first_attribute_assignment = attributes[0]
@@ -1016,6 +1141,11 @@ def test_product_bulk_create_with_attributes_and_create_new_value_with_external_
data["results"][0]["product"]["attributes"][0]["attribute"]["slug"]
== color_attr.slug
)
+
+ first_p_assigned_attributes = data["results"][0]["product"]["assignedAttributes"]
+ assert len(first_p_assigned_attributes) == 1
+ assert first_p_assigned_attributes[0]["choice"]["name"] == new_value
+
assert color_attr.values.count() == color_attr_values_count + 1
attributes = get_product_attributes(product)
first_attribute_assignment = attributes[0]
diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.py
index 65d054d938..e2fbf78cb6 100644
--- a/saleor/graphql/product/tests/mutations/test_product_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_create.py
@@ -21,68 +21,167 @@ from .....product.models import Product
from .....tests.utils import dummy_editorjs
CREATE_PRODUCT_MUTATION = """
- mutation createProduct(
- $input: ProductCreateInput!
- ) {
- productCreate(
- input: $input) {
- product {
- id
- category {
- name
- }
- description
- chargeTaxes
- taxClass {
- id
- }
- taxType {
- taxCode
- description
- }
- name
- slug
- rating
- productType {
- name
- }
- metadata {
- key
- value
- }
- privateMetadata {
- key
- value
- }
- attributes {
- attribute {
- slug
- }
- values {
- slug
- name
- reference
- richText
- plainText
- boolean
- dateTime
- date
- file {
- url
- contentType
- }
- }
- }
- externalReference
- }
- errors {
- field
- code
- message
- attributes
- }
- }
- }
+mutation createProduct($input: ProductCreateInput!) {
+ productCreate(input: $input) {
+ product {
+ id
+ category {
+ name
+ }
+ description
+ chargeTaxes
+ taxClass {
+ id
+ }
+ taxType {
+ taxCode
+ description
+ }
+ name
+ slug
+ rating
+ productType {
+ name
+ }
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedNumericAttribute {
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
+ }
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiChoiceAttribute {
+ multi: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
+ }
+ }
+ }
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
+ }
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ slug
+ name
+ reference
+ richText
+ plainText
+ boolean
+ dateTime
+ date
+ file {
+ url
+ contentType
+ }
+ }
+ }
+ externalReference
+ }
+ errors {
+ field
+ code
+ message
+ attributes
+ }
+ }
+}
"""
@@ -171,6 +270,7 @@ def test_create_product(
assert data["product"]["category"]["name"] == category.name
assert data["product"]["taxClass"]["id"] == tax_class_id
assert data["product"]["externalReference"] == external_reference
+
values = (
data["product"]["attributes"][0]["values"][0]["slug"],
data["product"]["attributes"][1]["values"][0]["slug"],
@@ -178,6 +278,11 @@ def test_create_product(
assert slugify(non_existent_attr_value) in values
assert color_value_slug in values
+ assigned_attributes = data["product"]["assignedAttributes"]
+ assert len(assigned_attributes) == 2
+ assert assigned_attributes[0]["choice"]["name"] == color_value_name
+ assert assigned_attributes[1]["choice"]["name"] == non_existent_attr_value
+
product = Product.objects.first()
assert product.search_index_dirty is True
assert product.metadata == {metadata_key: metadata_value}
@@ -334,6 +439,7 @@ def test_create_product_with_using_attribute_external_ref(
product_name = "test name"
product_slug = "product-test-slug"
+ expected_attr_value_name = "newColor"
# test creating root product
variables = {
"input": {
@@ -344,7 +450,7 @@ def test_create_product_with_using_attribute_external_ref(
"attributes": [
{
"externalReference": color_attribute.external_reference,
- "dropdown": {"value": "newColor"},
+ "dropdown": {"value": expected_attr_value_name},
}
],
}
@@ -367,8 +473,8 @@ def test_create_product_with_using_attribute_external_ref(
"attribute": {"slug": "color"},
"values": [
{
- "slug": "newcolor",
- "name": "newColor",
+ "slug": expected_attr_value_name.lower(),
+ "name": expected_attr_value_name,
"reference": None,
"richText": None,
"plainText": None,
@@ -384,6 +490,16 @@ def test_create_product_with_using_attribute_external_ref(
for attr_data in data["product"]["attributes"]:
assert attr_data in expected_attributes_data
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": color_attribute.slug},
+ "choice": {
+ "name": expected_attr_value_name,
+ "slug": expected_attr_value_name.lower(),
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
def test_create_product_with_using_attribute_id_and_external_ref(
staff_api_client,
@@ -495,6 +611,16 @@ def test_create_product_with_using_attribute_and_value_external_ref(
for attr_data in data["product"]["attributes"]:
assert attr_data in expected_attributes_data
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": color_attribute.slug},
+ "choice": {
+ "name": attr_value.name,
+ "slug": attr_value.slug,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_rich_text_attribute(
staff_api_client,
@@ -572,6 +698,13 @@ def test_create_product_with_rich_text_attribute(
for attr_data in data["product"]["attributes"]:
assert attr_data in expected_attributes_data
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": rich_text_attribute.slug},
+ "text": rich_text_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_no_value_for_rich_text_attribute(
staff_api_client,
@@ -611,6 +744,14 @@ def test_create_product_no_value_for_rich_text_attribute(
assert data["errors"] == []
assert data["product"]["name"] == product_name
assert data["product"]["productType"]["name"] == product_type.name
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": rich_text_attribute.slug},
+ "text": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
expected_attributes_data = {
"attribute": {"slug": rich_text_attribute.slug},
"values": [],
@@ -692,6 +833,13 @@ def test_create_product_with_plain_text_attribute(
},
]
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute.slug},
+ "plain_text": text_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
for attr_data in data["product"]["attributes"]:
assert attr_data in expected_attributes_data
@@ -738,6 +886,14 @@ def test_create_product_no_value_for_plain_text_attribute(
assert data["errors"] == []
assert data["product"]["name"] == product_name
assert data["product"]["productType"]["name"] == product_type.name
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute.slug},
+ "plain_text": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
expected_attributes_data = {
"attribute": {"slug": plain_text_attribute.slug},
"values": [],
@@ -808,6 +964,13 @@ def test_create_product_with_date_time_attribute(
assert expected_attributes_data in data["product"]["attributes"]
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_time_attribute.slug},
+ "datetime": str(value.isoformat()),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_create_product_with_date_attribute(
@@ -870,6 +1033,13 @@ def test_create_product_with_date_attribute(
assert expected_attributes_data in data["product"]["attributes"]
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_attribute.slug},
+ "date": str(value),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_no_value_for_date_attribute(
staff_api_client,
@@ -913,6 +1083,13 @@ def test_create_product_no_value_for_date_attribute(
}
assert expected_attributes_data in data["product"]["attributes"]
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_attribute.slug},
+ "date": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_boolean_attribute(
staff_api_client,
@@ -973,6 +1150,13 @@ def test_create_product_with_boolean_attribute(
}
assert expected_attributes_data in data["product"]["attributes"]
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": boolean_attribute.slug},
+ "bool": False,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_no_value_for_boolean_attribute(
staff_api_client,
@@ -1016,6 +1200,13 @@ def test_create_product_no_value_for_boolean_attribute(
}
assert expected_attributes_data in data["product"]["attributes"]
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": boolean_attribute.slug},
+ "bool": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
@pytest.mark.parametrize("input_slug", ["", None])
def test_create_product_no_slug_in_input(
@@ -1467,6 +1658,7 @@ def test_create_product_with_file_attribute(
query = CREATE_PRODUCT_MUTATION
product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
category_id = graphene.Node.to_global_id("Category", category.pk)
product_name = "test name"
product_slug = "product-test-slug"
@@ -1530,6 +1722,16 @@ def test_create_product_with_file_attribute(
file_attribute.refresh_from_db()
assert file_attribute.values.count() == values_count + 1
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_page_reference_attribute(
staff_api_client,
@@ -1603,6 +1805,13 @@ def test_create_product_with_page_reference_attribute(
product_type_page_reference_attribute.refresh_from_db()
assert product_type_page_reference_attribute.values.count() == values_count + 1
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_product_reference_attribute(
staff_api_client,
@@ -1676,6 +1885,13 @@ def test_create_product_with_product_reference_attribute(
product_type_product_reference_attribute.refresh_from_db()
assert product_type_product_reference_attribute.values.count() == values_count + 1
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_variant_reference_attribute(
staff_api_client,
@@ -1753,6 +1969,13 @@ def test_create_product_with_variant_reference_attribute(
product_type_variant_reference_attribute.refresh_from_db()
assert product_type_variant_reference_attribute.values.count() == values_count + 1
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_category_reference_attribute(
staff_api_client,
@@ -1827,6 +2050,13 @@ def test_create_product_with_category_reference_attribute(
product_type_category_reference_attribute.refresh_from_db()
assert product_type_category_reference_attribute.values.count() == values_count + 1
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_category_reference_attribute.slug},
+ "categories": [{"slug": category.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_collection_reference_attribute(
staff_api_client,
@@ -1904,6 +2134,13 @@ def test_create_product_with_collection_reference_attribute(
product_type_collection_reference_attribute.values.count() == values_count + 1
)
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_collection_reference_attribute.slug},
+ "collections": [{"slug": collection.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_single_reference_attributes(
staff_api_client,
@@ -2017,6 +2254,34 @@ def test_create_product_with_single_reference_attributes(
for attr_data in data["product"]["attributes"]:
assert attr_data in expected_attributes_data
+ assigned_attributes = data["product"]["assignedAttributes"]
+
+ expected_assigned_page_attribute = {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "page": {"slug": page.slug},
+ }
+ expected_assigned_product_attribute = {
+ "attribute": {"slug": product_type_product_single_reference_attribute.slug},
+ "product": {"slug": product.slug},
+ }
+ expected_assigned_variant_attribute = {
+ "attribute": {"slug": product_type_variant_single_reference_attribute.slug},
+ "variant": {"sku": product_variant_list[0].sku},
+ }
+ expected_assigned_category_attribute = {
+ "attribute": {"slug": product_type_category_single_reference_attribute.slug},
+ "category": {"slug": categories[0].slug},
+ }
+ expected_assigned_collection_attribute = {
+ "attribute": {"slug": product_type_collection_single_reference_attribute.slug},
+ "collection": {"slug": collection.slug},
+ }
+ assert expected_assigned_page_attribute in assigned_attributes
+ assert expected_assigned_product_attribute in assigned_attributes
+ assert expected_assigned_variant_attribute in assigned_attributes
+ assert expected_assigned_category_attribute in assigned_attributes
+ assert expected_assigned_collection_attribute in assigned_attributes
+
def test_create_product_with_product_reference_attribute_values_saved_in_order(
staff_api_client,
@@ -2083,6 +2348,12 @@ def test_create_product_with_product_reference_attribute_values_saved_in_order(
}
for product, reference in zip(reference_instances, reference_ids, strict=False)
]
+ expected_assigned_attribute = [
+ {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug} for product in reference_instances],
+ }
+ ]
assert len(data["product"]["attributes"]) == 1
attribute_data = data["product"]["attributes"][0]
@@ -2096,6 +2367,13 @@ def test_create_product_with_product_reference_attribute_values_saved_in_order(
product_type_product_reference_attribute.refresh_from_db()
assert product_type_product_reference_attribute.values.count() == values_count + 3
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug} for product in reference_instances],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_page_reference_attribute_and_invalid_product_one(
staff_api_client,
@@ -2221,6 +2499,21 @@ def test_create_product_with_file_attribute_new_attribute_value(
file_attribute.refresh_from_db()
assert file_attribute.values.count() == values_count + 1
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": color_attribute.slug},
+ "choice": None,
+ }
+ expected_assigned_file_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": None,
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+ assert expected_assigned_file_attribute in assigned_attributes
+
def test_create_product_with_file_attribute_not_required_no_file_url_given(
staff_api_client,
@@ -2275,6 +2568,18 @@ def test_create_product_with_file_attribute_not_required_no_file_url_given(
file_attribute.refresh_from_db()
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": color_attribute.slug},
+ "choice": None,
+ }
+ expected_assigned_file_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": None,
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+ assert expected_assigned_file_attribute in assigned_attributes
+
def test_create_product_with_file_attribute_required_no_file_url_given(
staff_api_client,
@@ -2468,11 +2773,13 @@ def test_create_product_no_values_given(
assert data["product"]["category"]["name"] == category.name
assert len(data["product"]["attributes"]) == 1
assert data["product"]["attributes"][0]["values"] == []
+ assert len(data["product"]["assignedAttributes"]) == 1
+ assert data["product"]["assignedAttributes"][0]["choice"] is None
@pytest.mark.parametrize(
("value", "expected_name", "expected_slug"),
- [(20.1, "20.1", "20_1"), (20, "20", "20"), ("1", "1", "1")],
+ [(20.1, "20.1", "20_1"), (20, "20", "20"), (1, "1", "1")],
)
def test_create_product_with_numeric_attribute_new_attribute_value(
value,
@@ -2530,6 +2837,13 @@ def test_create_product_with_numeric_attribute_new_attribute_value(
assert values[0]["name"] == expected_name
assert values[0]["slug"] == f"{product_pk}_{numeric_attribute.id}"
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
numeric_attribute.refresh_from_db()
assert numeric_attribute.values.filter(name=expected_name, numeric=value).exists()
@@ -2589,6 +2903,13 @@ def test_create_product_with_numeric_attribute_existing_value(
numeric_attribute.refresh_from_db()
assert numeric_attribute.values.count() == values_count + 1
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": existing_value.numeric,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_swatch_attribute_new_attribute_value(
staff_api_client,
@@ -2644,6 +2965,18 @@ def test_create_product_with_swatch_attribute_new_attribute_value(
swatch_attribute.refresh_from_db()
assert swatch_attribute.values.count() == values_count + 1
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": swatch_attribute.slug},
+ "swatch": {
+ "name": new_value,
+ "slug": slugify(new_value),
+ "hexColor": None,
+ "file": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_swatch_attribute_new_value_using_values_field(
staff_api_client,
@@ -2701,6 +3034,18 @@ def test_create_product_with_swatch_attribute_new_value_using_values_field(
swatch_attribute.refresh_from_db()
assert swatch_attribute.values.count() == values_count + 1
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": swatch_attribute.slug},
+ "swatch": {
+ "name": new_value,
+ "slug": slugify(new_value),
+ "hexColor": None,
+ "file": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_swatch_attribute_existing_value(
staff_api_client,
@@ -2757,6 +3102,18 @@ def test_create_product_with_swatch_attribute_existing_value(
swatch_attribute.refresh_from_db()
assert swatch_attribute.values.count() == values_count
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": swatch_attribute.slug},
+ "swatch": {
+ "name": existing_value.name,
+ "slug": existing_value.slug,
+ "hexColor": existing_value.value,
+ "file": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_swatch_attribute_existing_value_using_values_field(
staff_api_client,
@@ -2812,6 +3169,18 @@ def test_create_product_with_swatch_attribute_existing_value_using_values_field(
swatch_attribute.refresh_from_db()
assert swatch_attribute.values.count() == values_count
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": swatch_attribute.slug},
+ "swatch": {
+ "name": existing_value.name,
+ "slug": existing_value.slug,
+ "hexColor": existing_value.value,
+ "file": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_create_product_with_numeric_attribute_not_numeric_value_given(
staff_api_client,
diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.py
index 0e1274f544..60e13da333 100644
--- a/saleor/graphql/product/tests/mutations/test_product_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_update.py
@@ -29,73 +29,175 @@ from .....product.models import Product
from ....attribute.utils.type_handlers import AttributeInputErrors
MUTATION_UPDATE_PRODUCT = """
- mutation updateProduct($productId: ID!, $input: ProductInput!) {
- productUpdate(id: $productId, input: $input) {
- product {
- category {
- name
- }
- collections {
- name
- }
- rating
- description
- chargeTaxes
- variants {
- name
- }
- productVariants(first: 10) {
- edges {
- node {
- id
- name
- }
- }
- }
- taxType {
- taxCode
- description
- }
- name
- slug
- productType {
- name
- }
- metadata {
- key
- value
- }
- privateMetadata {
- key
- value
- }
- attributes {
- attribute {
- id
- name
- }
- values {
- id
- name
- slug
- boolean
- reference
- plainText
- file {
- url
- contentType
- }
- }
- }
- externalReference
- }
- errors {
- message
- field
- code
- }
+mutation updateProduct($productId: ID!, $input: ProductInput!) {
+ productUpdate(id: $productId, input: $input) {
+ product {
+ category {
+ name
+ }
+ collections {
+ name
+ }
+ rating
+ description
+ chargeTaxes
+ variants {
+ name
+ }
+ productVariants(first: 10) {
+ edges {
+ node {
+ id
+ name
+ }
+ }
+ }
+ taxType {
+ taxCode
+ description
+ }
+ name
+ slug
+ productType {
+ name
+ }
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedNumericAttribute {
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
+ }
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiChoiceAttribute {
+ multi: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
}
+ }
}
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
+ }
+ attributes {
+ attribute {
+ id
+ name
+ }
+ values {
+ id
+ name
+ slug
+ boolean
+ reference
+ plainText
+ file {
+ url
+ contentType
+ }
+ }
+ }
+ externalReference
+ }
+ errors {
+ message
+ field
+ code
+ }
+ }
+}
"""
@@ -195,6 +297,10 @@ def test_update_product(
assert attributes[0]["values"][0]["name"] == "Rainbow"
assert attributes[0]["values"][0]["slug"] == "rainbow"
+ assigned_attributes = data["product"]["assignedAttributes"]
+ assert len(assigned_attributes) == 1
+ assert assigned_attributes[0]["choice"]["name"] == attr_value
+
updated_webhook_mock.assert_called_once_with(product)
created_webhook_mock.assert_not_called()
@@ -489,6 +595,13 @@ def test_update_product_with_boolean_attribute_value(
}
assert expected_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": boolean_attribute.slug},
+ "bool": new_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
@@ -549,6 +662,16 @@ def test_update_product_with_file_attribute_value(
}
assert expected_file_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
@@ -615,6 +738,16 @@ def test_update_product_with_file_attribute_value_new_value_is_not_created(
}
assert expected_file_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": existing_value.content_type,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
file_attribute.refresh_from_db()
assert file_attribute.values.count() == values_count
@@ -674,6 +807,14 @@ def test_update_product_with_numeric_attribute_value(
],
}
assert expected_att_data in attributes
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": numeric_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert numeric_attribute.values.filter(
name=new_value,
numeric=numeric_value,
@@ -743,6 +884,13 @@ def test_update_product_with_numeric_attribute_value_new_value_is_not_created(
}
assert expected_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": numeric_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert AttributeValue.objects.count() == value_count
value.refresh_from_db()
assert value.name == new_value
@@ -766,6 +914,8 @@ def test_update_product_clear_attribute_values(
attribute.value_required = False
attribute.save(update_fields=["value_required"])
+ assert attribute.input_type == AttributeInputType.DROPDOWN
+
attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
variables = {
@@ -787,6 +937,14 @@ def test_update_product_clear_attribute_values(
assert len(attributes) == 1
assert not attributes[0]["values"]
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "choice": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert not get_product_attribute_values(product, attribute).exists()
updated_webhook_mock.assert_called_once_with(product)
@@ -835,6 +993,14 @@ def test_update_product_clean_boolean_attribute_value(
"values": [],
}
assert expected_att_data in attributes
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": boolean_attribute.slug},
+ "bool": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert get_product_attribute_values(product, product_attr).count() == 0
@@ -880,7 +1046,16 @@ def test_update_product_clean_file_attribute_value(
"attribute": {"id": attribute_id, "name": file_attribute.name},
"values": [],
}
+ file_attribute.refresh_from_db()
assert expected_att_data in attributes
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert get_product_attribute_values(product, file_attribute).count() == 0
@@ -901,6 +1076,8 @@ def test_update_product_none_as_attribute_values(
attribute.value_required = False
attribute.save(update_fields=["value_required"])
+ assert attribute.input_type == AttributeInputType.DROPDOWN
+
attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
variables = {
@@ -922,6 +1099,14 @@ def test_update_product_none_as_attribute_values(
assert len(attributes) == 1
assert not attributes[0]["values"]
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "choice": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert not get_product_attribute_values(product, attribute).exists()
updated_webhook_mock.assert_called_once_with(product)
@@ -979,6 +1164,13 @@ def test_update_product_with_plain_text_attribute_value(
}
assert expected_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute.slug},
+ "plain_text": text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
@@ -1037,6 +1229,13 @@ def test_update_product_with_plain_text_attribute_value_required(
}
assert expected_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute.slug},
+ "plain_text": text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
@@ -1168,6 +1367,13 @@ def test_update_product_with_page_reference_attribute_value(
}
assert expected_file_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
product_type_page_reference_attribute.refresh_from_db()
@@ -1272,6 +1478,34 @@ def test_update_product_with_single_reference_attribute_value(
for attr_data in expected_attributes_data:
assert attr_data in attributes_data
+ assigned_attributes = data["product"]["assignedAttributes"]
+
+ expected_assigned_page_attribute = {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "page": {"slug": page.slug},
+ }
+ expected_assigned_product_attribute = {
+ "attribute": {"slug": product_type_product_single_reference_attribute.slug},
+ "product": {"slug": product.slug},
+ }
+ expected_assigned_variant_attribute = {
+ "attribute": {"slug": product_type_variant_single_reference_attribute.slug},
+ "variant": {"sku": product_variant_list[0].sku},
+ }
+ expected_assigned_category_attribute = {
+ "attribute": {"slug": product_type_category_single_reference_attribute.slug},
+ "category": {"slug": categories[0].slug},
+ }
+ expected_assigned_collection_attribute = {
+ "attribute": {"slug": product_type_collection_single_reference_attribute.slug},
+ "collection": {"slug": collection.slug},
+ }
+ assert expected_assigned_page_attribute in assigned_attributes
+ assert expected_assigned_product_attribute in assigned_attributes
+ assert expected_assigned_variant_attribute in assigned_attributes
+ assert expected_assigned_category_attribute in assigned_attributes
+ assert expected_assigned_collection_attribute in assigned_attributes
+
def test_update_product_without_supplying_required_product_attribute(
staff_api_client, product, permission_manage_products, color_attribute
@@ -1282,10 +1516,16 @@ def test_update_product_without_supplying_required_product_attribute(
product_type = product.product_type
color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)
+ assert color_attribute.input_type == AttributeInputType.DROPDOWN
+
# Create and assign a new attribute requiring a value to be always supplied
required_attribute = Attribute.objects.create(
- name="Required One", slug="required-one", value_required=True
+ name="Required One",
+ slug="required-one",
+ value_required=True,
+ input_type=AttributeInputType.DROPDOWN,
)
+
product_type.product_attributes.add(required_attribute)
required_attribute_id = graphene.Node.to_global_id(
"Attribute", required_attribute.id
@@ -1325,6 +1565,18 @@ def test_update_product_without_supplying_required_product_attribute(
],
} in attributes_data
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_color_assigned_attribute = {
+ "attribute": {"slug": color_attribute.slug},
+ "choice": {"name": value, "slug": value.lower()},
+ }
+ assert expected_color_assigned_attribute in assigned_attributes
+ expected_required_assigned_attribute = {
+ "attribute": {"slug": required_attribute.slug},
+ "choice": None,
+ }
+ assert expected_required_assigned_attribute in assigned_attributes
+
def test_update_product_with_empty_input_collections(
product, permission_manage_products, staff_api_client
@@ -1429,6 +1681,13 @@ def test_update_product_with_page_reference_attribute_existing_value(
}
assert expected_file_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
product_type_page_reference_attribute.refresh_from_db()
@@ -1537,6 +1796,13 @@ def test_update_product_with_product_reference_attribute_value(
}
assert expected_file_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product_ref.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
product_type_product_reference_attribute.refresh_from_db()
@@ -1601,6 +1867,14 @@ def test_update_product_with_variant_reference_attribute_value(
],
}
assert expected_file_att_data in attributes
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant_ref.sku}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
product_type_variant_reference_attribute.refresh_from_db()
assert product_type_variant_reference_attribute.values.count() == values_count + 1
@@ -1664,6 +1938,14 @@ def test_update_product_with_category_reference_attribute_value(
],
}
assert expected_file_att_data in attributes
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_category_reference_attribute.slug},
+ "categories": [{"slug": category.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
product_type_category_reference_attribute.refresh_from_db()
assert product_type_category_reference_attribute.values.count() == values_count + 1
@@ -1731,6 +2013,13 @@ def test_update_product_with_collection_reference_attribute_value(
product_type_collection_reference_attribute.values.count() == values_count + 1
)
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_collection_reference_attribute.slug},
+ "collections": [{"slug": collection.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
@@ -1834,6 +2123,13 @@ def test_update_product_with_product_reference_attribute_existing_value(
}
assert expected_file_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product_ref.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
product_type_product_reference_attribute.refresh_from_db()
@@ -1930,6 +2226,8 @@ def test_update_product_change_values_ordering(
).values_list("value_id", flat=True)
) == [attr_value_2.pk, attr_value_1.pk]
+ expected_first_page = page_list[0]
+ expected_second_page = page_list[1]
variables = {
"productId": product_id,
"input": {
@@ -1937,8 +2235,8 @@ def test_update_product_change_values_ordering(
{
"id": attribute_id,
"references": [
- graphene.Node.to_global_id("Page", page_list[0].pk),
- graphene.Node.to_global_id("Page", page_list[1].pk),
+ graphene.Node.to_global_id("Page", expected_first_page.pk),
+ graphene.Node.to_global_id("Page", expected_second_page.pk),
],
}
]
@@ -1964,6 +2262,14 @@ def test_update_product_change_values_ordering(
graphene.Node.to_global_id("AttributeValue", val.pk)
for val in [attr_value_1, attr_value_2]
]
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ assert len(assigned_attributes) == 1
+ assigned_values = assigned_attributes[0]["pages"]
+ assert len(assigned_values) == 2
+ assert assigned_values[0]["slug"] == expected_first_page.slug
+ assert assigned_values[1]["slug"] == expected_second_page.slug
+
product.refresh_from_db()
attribute = get_product_attributes(product).first()
@@ -2397,6 +2703,14 @@ def test_update_product_with_numeric_attribute_value_by_numeric_field(
],
}
assert expected_att_data in attributes
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": numeric_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert numeric_attribute.values.filter(
name=new_value, numeric=numeric_value
).first()
@@ -2440,6 +2754,13 @@ def test_update_product_with_numeric_attribute_by_numeric_field_null_value(
assert data["errors"] == []
assert not data["product"]["attributes"][1]["values"]
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_update_product_with_numeric_attribute_by_numeric_field_new_value_not_created(
staff_api_client,
@@ -2499,6 +2820,12 @@ def test_update_product_with_numeric_attribute_by_numeric_field_new_value_not_cr
],
}
assert expected_att_data in attributes
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": numeric_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
assert AttributeValue.objects.count() == value_count
value.refresh_from_db()
@@ -2523,6 +2850,9 @@ def test_update_product_with_dropdown_attribute_non_existing_value(
attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)
product_type.product_attributes.add(color_attribute)
+ assert color_attribute.input_type == AttributeInputType.DROPDOWN
+
+ new_color_name = "new-color"
variables = {
"productId": product_id,
"input": {
@@ -2530,7 +2860,7 @@ def test_update_product_with_dropdown_attribute_non_existing_value(
{
"id": attribute_id,
"dropdown": {
- "value": "new color",
+ "value": new_color_name,
},
}
]
@@ -2548,7 +2878,18 @@ def test_update_product_with_dropdown_attribute_non_existing_value(
errors = data["errors"]
assert not errors
- assert data["product"]["attributes"][0]["values"][0]["name"] == "new color"
+ assert data["product"]["attributes"][0]["values"][0]["name"] == new_color_name
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": color_attribute.slug},
+ "choice": {
+ "name": new_color_name,
+ "slug": new_color_name.lower(),
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
@@ -2566,12 +2907,13 @@ def test_update_product_with_dropdown_attribute_existing_value(
product_id = graphene.Node.to_global_id("Product", product.pk)
attribute = product_type.product_attributes.first()
+ assert attribute.input_type == AttributeInputType.DROPDOWN
+
attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
attribute_value = attribute.values.model.objects.first()
attribute_value_id = graphene.Node.to_global_id(
"AttributeValue", attribute_value.pk
)
- attribute_value_name = attribute.values.model.objects.first().name
product_type.product_attributes.add(attribute)
variables = {
@@ -2599,7 +2941,18 @@ def test_update_product_with_dropdown_attribute_existing_value(
errors = data["errors"]
assert not errors
- assert data["product"]["attributes"][0]["values"][0]["name"] == attribute_value_name
+ assert data["product"]["attributes"][0]["values"][0]["name"] == attribute_value.name
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "choice": {
+ "name": attribute_value.name,
+ "slug": attribute_value.slug,
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
@@ -2616,12 +2969,14 @@ def test_update_product_with_dropdown_attribute_existing_value_passed_as_new_val
product_id = graphene.Node.to_global_id("Product", product.pk)
attribute = product_type.product_attributes.first()
+
+ assert attribute.input_type == AttributeInputType.DROPDOWN
+
attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
attribute_value = attribute.values.model.objects.first()
attribute_value_id = graphene.Node.to_global_id(
"AttributeValue", attribute_value.pk
)
- attribute_value_name = attribute.values.model.objects.first().name
product_type.product_attributes.add(attribute)
value_count = AttributeValue.objects.count()
@@ -2633,7 +2988,7 @@ def test_update_product_with_dropdown_attribute_existing_value_passed_as_new_val
{
"id": attribute_id,
"dropdown": {
- "value": attribute_value_name,
+ "value": attribute_value.name,
},
}
]
@@ -2652,6 +3007,17 @@ def test_update_product_with_dropdown_attribute_existing_value_passed_as_new_val
assert not errors
assert data["product"]["attributes"][0]["values"][0]["id"] == attribute_value_id
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "choice": {
+ "name": attribute_value.name,
+ "slug": attribute_value.slug,
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
assert AttributeValue.objects.count() == value_count
updated_webhook_mock.assert_called_once_with(product)
@@ -2698,6 +3064,13 @@ def test_update_product_with_dropdown_attribute_null_value(
assert not errors
assert not data["product"]["attributes"][0]["values"]
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": color_attribute.slug},
+ "choice": None,
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
updated_webhook_mock.assert_called_once_with(product)
@@ -2718,13 +3091,18 @@ def test_update_product_with_multiselect_attribute_non_existing_values(
value_count = AttributeValue.objects.count()
+ first_value_name = "new-mode-1"
+ second_value_name = "new-mode-2"
variables = {
"productId": product_id,
"input": {
"attributes": [
{
"id": attribute_id,
- "multiselect": [{"value": "new mode 1"}, {"value": "new mode 2"}],
+ "multiselect": [
+ {"value": first_value_name},
+ {"value": second_value_name},
+ ],
}
]
},
@@ -2743,8 +3121,22 @@ def test_update_product_with_multiselect_attribute_non_existing_values(
assert not errors
values = data["product"]["attributes"][0]["values"]
assert len(values) == 2
- assert values[0]["name"] == "new mode 1"
- assert values[1]["name"] == "new mode 2"
+ assert values[0]["name"] == first_value_name
+ assert values[1]["name"] == second_value_name
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "multi": [
+ {"name": first_value_name, "slug": first_value_name.lower()},
+ {
+ "name": second_value_name,
+ "slug": second_value_name.lower(),
+ },
+ ],
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
updated_webhook_mock.assert_called_once_with(product)
assert AttributeValue.objects.count() == value_count + 2
@@ -2768,10 +3160,8 @@ def test_update_product_with_multiselect_attribute_existing_values(
attribute_values = get_product_attribute_values(product, attribute)
attr_value_1 = attribute_values[0]
attr_value_id_1 = graphene.Node.to_global_id("AttributeValue", attr_value_1.pk)
- attr_value_name_1 = attr_value_1.name
attr_value_2 = attribute_values[1]
attr_value_id_2 = graphene.Node.to_global_id("AttributeValue", attr_value_2.pk)
- attr_value_name_2 = attr_value_2.name
associate_attribute_values_to_instance(product, {attribute.pk: [attr_value_1]})
@@ -2803,8 +3193,18 @@ def test_update_product_with_multiselect_attribute_existing_values(
assert not errors
values = data["product"]["attributes"][0]["values"]
assert len(values) == 2
- assert values[0]["name"] == attr_value_name_1
- assert values[1]["name"] == attr_value_name_2
+ assert values[0]["name"] == attr_value_1.name
+ assert values[1]["name"] == attr_value_2.name
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "multi": [
+ {"name": attr_value_1.name, "slug": attr_value_1.slug},
+ {"name": attr_value_2.name, "slug": attr_value_2.slug},
+ ],
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
updated_webhook_mock.assert_called_once_with(product)
@@ -2827,11 +3227,9 @@ def test_update_product_with_multiselect_attribute_new_values_not_created(
attr_value_1 = attr_values[0]
attr_value_id_1 = graphene.Node.to_global_id("AttributeValue", attr_value_1.pk)
- attr_value_name_1 = attr_value_1.name
attr_value_2 = attr_values[1]
attr_value_id_2 = graphene.Node.to_global_id("AttributeValue", attr_value_2.pk)
- attr_value_name_2 = attr_value_2.name
value_count = AttributeValue.objects.count()
@@ -2844,8 +3242,8 @@ def test_update_product_with_multiselect_attribute_new_values_not_created(
{
"id": attribute_id,
"multiselect": [
- {"value": attr_value_name_1},
- {"value": attr_value_name_2},
+ {"value": attr_value_1.name},
+ {"value": attr_value_2.name},
],
}
]
@@ -2867,6 +3265,17 @@ def test_update_product_with_multiselect_attribute_new_values_not_created(
assert len(values) == 2
assert values[0]["id"] == attr_value_id_1
assert values[1]["id"] == attr_value_id_2
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "multi": [
+ {"name": attr_value_1.name, "slug": attr_value_1.slug},
+ {"name": attr_value_2.name, "slug": attr_value_2.slug},
+ ],
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
assert AttributeValue.objects.count() == value_count
updated_webhook_mock.assert_called_once_with(product)
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
index c96a7087ea..6df2b6c768 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
@@ -20,82 +20,182 @@ from ....core.enums import ErrorPolicyEnum
from ....tests.utils import get_graphql_content
PRODUCT_VARIANT_BULK_CREATE_MUTATION = """
- mutation ProductVariantBulkCreate(
- $variants: [ProductVariantBulkCreateInput!]!,
- $productId: ID!,
- $errorPolicy: ErrorPolicyEnum
- ) {
- productVariantBulkCreate(
- variants: $variants, product: $productId, errorPolicy: $errorPolicy
- ) {
- results{
- productVariant{
- metadata {
- key
- value
- }
- id
- name
- sku
- trackInventory
- attributes{
- attribute {
- slug
- }
- values {
- name
- slug
- reference
- richText
- plainText
- boolean
- date
- dateTime
- file {
- url
- contentType
- }
- }
- }
- stocks {
- warehouse {
- slug
- }
- quantity
- }
- channelListings {
- channel {
- slug
- }
- price {
- currency
- amount
- }
- costPrice {
- currency
- amount
- }
- preorderThreshold {
- quantity
- }
- }
- preorder {
- globalThreshold
- endDate
- }
- }
- errors {
- field
- path
- message
- code
- warehouses
- channels
- }
- }
- count
+mutation ProductVariantBulkCreate($variants: [ProductVariantBulkCreateInput!]!, $productId: ID!, $errorPolicy: ErrorPolicyEnum) {
+ productVariantBulkCreate(
+ variants: $variants
+ product: $productId
+ errorPolicy: $errorPolicy
+ ) {
+ results {
+ productVariant {
+ metadata {
+ key
+ value
+ }
+ id
+ name
+ sku
+ trackInventory
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedNumericAttribute {
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
+ }
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiChoiceAttribute {
+ multi: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
+ }
+ }
+ }
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
+ }
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ name
+ slug
+ reference
+ richText
+ plainText
+ boolean
+ date
+ dateTime
+ file {
+ url
+ contentType
+ }
+ }
+ }
+ stocks {
+ warehouse {
+ slug
+ }
+ quantity
+ }
+ channelListings {
+ channel {
+ slug
+ }
+ price {
+ currency
+ amount
+ }
+ costPrice {
+ currency
+ amount
+ }
+ preorderThreshold {
+ quantity
+ }
+ }
+ preorder {
+ globalThreshold
+ endDate
}
+ }
+ errors {
+ field
+ path
+ message
+ code
+ warehouses
+ channels
+ }
}
+ count
+ }
+}
"""
@@ -284,6 +384,15 @@ def test_product_variant_bulk_create_by_attribute_external_ref(
data["results"][0]["productVariant"]["attributes"][1]["values"][0]["slug"]
== attribute_value.slug
)
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": color_attribute.slug},
+ "choice": {
+ "name": attribute_value.name,
+ "slug": attribute_value.slug,
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
def test_product_variant_bulk_create_return_error_when_attribute_external_ref_and_id(
@@ -389,6 +498,15 @@ def test_product_variant_bulk_create_will_create_new_attr_value_and_external_ref
data["results"][0]["productVariant"]["attributes"][1]["values"][0]["name"]
== new_value
)
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": color_attribute.slug},
+ "choice": {
+ "name": new_value,
+ "slug": new_value.lower(),
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
def test_product_variant_bulk_create_with_swatch_attribute(
@@ -480,6 +598,14 @@ def test_product_variant_bulk_create_with_plain_text_attribute(
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
assert attributes[-1]["values"][0]["plainText"] == plain_text
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute.slug},
+ "plain_text": plain_text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
@@ -521,6 +647,14 @@ def test_product_variant_bulk_create_with_date_attribute(
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
assert attributes[-1]["values"][0]["date"] == str(date_value)
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_attribute.slug},
+ "date": str(date_value),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
@@ -561,6 +695,17 @@ def test_product_variant_bulk_create_with_file_attribute(
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
assert attributes[-1]["values"][0]["file"]["url"] == file_url
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
@@ -604,6 +749,14 @@ def test_product_variant_bulk_create_with_datetime_attribute(
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
assert attributes[-1]["values"][0]["dateTime"] == date_time_value.isoformat()
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_time_attribute.slug},
+ "datetime": date_time_value.isoformat(),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
@@ -619,7 +772,7 @@ def test_product_variant_bulk_create_with_rich_text_attribute(
product_id = graphene.Node.to_global_id("Product", product.pk)
attribute_id = graphene.Node.to_global_id("Attribute", rich_text_attribute.pk)
- rich_text = json.dumps(dummy_editorjs("Sample text"))
+ rich_text = dummy_editorjs("Sample text")
sku = str(uuid4())[:12]
variants = [
@@ -627,7 +780,7 @@ def test_product_variant_bulk_create_with_rich_text_attribute(
"sku": sku,
"weight": 2.5,
"trackInventory": True,
- "attributes": [{"id": attribute_id, "richText": rich_text}],
+ "attributes": [{"id": attribute_id, "richText": json.dumps(rich_text)}],
}
]
@@ -645,7 +798,15 @@ def test_product_variant_bulk_create_with_rich_text_attribute(
assert not data["results"][0]["errors"]
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
- assert attributes[-1]["values"][0]["richText"] == rich_text
+ assert attributes[-1]["values"][0]["richText"] == json.dumps(rich_text)
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": rich_text_attribute.slug},
+ "text": rich_text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
@@ -688,6 +849,14 @@ def test_product_variant_bulk_create_with_numeric_attribute(
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
assert attributes[-1]["values"][0]["name"] == existing_value.name
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": existing_value.numeric,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
@@ -733,6 +902,14 @@ def test_product_variant_bulk_create_with_page_reference_attribute(
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
assert attributes[-1]["values"][0]["reference"] == reference
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
@@ -776,6 +953,14 @@ def test_product_variant_bulk_create_with_single_reference_attribute(
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
assert attributes[-1]["values"][0]["reference"] == reference
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_category_single_reference_attribute.slug},
+ "category": {"slug": category.slug},
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
@@ -827,6 +1012,14 @@ def test_product_variant_bulk_create_with_dropdown_attribute(
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
assert attributes[-1]["values"][0]["name"] == attribute_value.name
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": size_attribute.slug},
+ "choice": {"slug": attribute_value.slug, "name": attribute_value.name},
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
@@ -874,6 +1067,14 @@ def test_product_variant_bulk_create_with_multiselect_attribute(
assert data["count"] == 1
attributes = data["results"][0]["productVariant"]["attributes"]
assert attributes[-1]["values"][0]["name"] == attribute_value.name
+
+ assigned_attributes = data["results"][0]["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": size_attribute.slug},
+ "multi": [{"slug": attribute_value.slug, "name": attribute_value.name}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert product_variant_count + 1 == ProductVariant.objects.count()
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
index 6ae99bb9e3..3f186c816d 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
@@ -15,64 +15,165 @@ from ....core.enums import WeightUnitsEnum
from ....tests.utils import get_graphql_content
CREATE_VARIANT_MUTATION = """
- mutation createVariant ($input: ProductVariantCreateInput!) {
- productVariantCreate(input: $input) {
- errors {
- field
- message
- attributes
- code
- }
- productVariant {
- id
- name
- sku
- attributes {
- attribute {
- slug
- }
- values {
- name
- slug
- reference
- richText
- plainText
- boolean
- date
- dateTime
- file {
- url
- contentType
- }
- }
- }
- weight {
- value
- unit
- }
- stocks {
- quantity
- warehouse {
- slug
- }
- }
- preorder {
- globalThreshold
- endDate
- }
- metadata {
- key
- value
- }
- privateMetadata {
- key
- value
- }
- externalReference
- }
- }
+mutation createVariant($input: ProductVariantCreateInput!) {
+ productVariantCreate(input: $input) {
+ errors {
+ field
+ message
+ attributes
+ code
+ }
+ productVariant {
+ id
+ name
+ sku
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedNumericAttribute {
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
+ }
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiChoiceAttribute {
+ multi: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
}
-
+ }
+ }
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
+ }
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ name
+ slug
+ reference
+ richText
+ plainText
+ boolean
+ date
+ dateTime
+ file {
+ url
+ contentType
+ }
+ }
+ }
+ weight {
+ value
+ unit
+ }
+ stocks {
+ quantity
+ warehouse {
+ slug
+ }
+ }
+ preorder {
+ globalThreshold
+ endDate
+ }
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
+ externalReference
+ }
+ }
+}
"""
@@ -94,11 +195,9 @@ def test_create_variant_with_name(
weight = 10.22
metadata_key = "md key"
metadata_value = "md value"
- variant_slug = product_type.variant_attributes.first().slug
- attribute_id = graphene.Node.to_global_id(
- "Attribute", product_type.variant_attributes.first().pk
- )
- variant_value = "test-value"
+ attribute = product_type.variant_attributes.first()
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+ attr_value = "test-value"
stocks = [
{
"warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
@@ -114,7 +213,7 @@ def test_create_variant_with_name(
"stocks": stocks,
"name": name,
"weight": weight,
- "attributes": [{"id": attribute_id, "values": [variant_value]}],
+ "attributes": [{"id": attribute_id, "values": [attr_value]}],
"trackInventory": True,
"metadata": [{"key": metadata_key, "value": metadata_value}],
"privateMetadata": [{"key": metadata_key, "value": metadata_value}],
@@ -133,8 +232,8 @@ def test_create_variant_with_name(
data = content["productVariant"]
assert data["name"] == name
assert data["sku"] == sku
- assert data["attributes"][0]["attribute"]["slug"] == variant_slug
- assert data["attributes"][0]["values"][0]["slug"] == variant_value
+ assert data["attributes"][0]["attribute"]["slug"] == attribute.slug
+ assert data["attributes"][0]["values"][0]["slug"] == attr_value
assert data["weight"]["unit"] == WeightUnitsEnum.KG.name
assert data["weight"]["value"] == weight
assert len(data["stocks"]) == 1
@@ -146,6 +245,16 @@ def test_create_variant_with_name(
assert data["privateMetadata"][0]["value"] == metadata_value
assert data["externalReference"] == external_reference
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "choice": {
+ "name": attr_value,
+ "slug": attr_value.lower(),
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
created_webhook_mock.assert_called_once_with(product.variants.last())
updated_webhook_mock.assert_not_called()
for rule in get_active_catalogue_promotion_rules():
@@ -168,11 +277,11 @@ def test_create_variant_without_name(
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = "1"
weight = 10.22
- variant_slug = product_type.variant_attributes.first().slug
- attribute_id = graphene.Node.to_global_id(
- "Attribute", product_type.variant_attributes.first().pk
- )
- variant_value = "test-value"
+
+ attribute = product_type.variant_attributes.first()
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+ attr_value = "test-value"
+
stocks = [
{
"warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
@@ -186,7 +295,7 @@ def test_create_variant_without_name(
"sku": sku,
"stocks": stocks,
"weight": weight,
- "attributes": [{"id": attribute_id, "values": [variant_value]}],
+ "attributes": [{"id": attribute_id, "values": [attr_value]}],
"trackInventory": True,
}
}
@@ -200,15 +309,26 @@ def test_create_variant_without_name(
# then
assert not content["errors"]
data = content["productVariant"]
- assert data["name"] == variant_value
+ assert data["name"] == attr_value
assert data["sku"] == sku
- assert data["attributes"][0]["attribute"]["slug"] == variant_slug
- assert data["attributes"][0]["values"][0]["slug"] == variant_value
+ assert data["attributes"][0]["attribute"]["slug"] == attribute.slug
+ assert data["attributes"][0]["values"][0]["slug"] == attr_value.lower()
assert data["weight"]["unit"] == WeightUnitsEnum.KG.name
assert data["weight"]["value"] == weight
assert len(data["stocks"]) == 1
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "choice": {
+ "name": attr_value,
+ "slug": attr_value.lower(),
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
created_webhook_mock.assert_called_once_with(product.variants.last())
updated_webhook_mock.assert_not_called()
@@ -425,6 +545,16 @@ def test_create_variant_with_file_attribute(
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
file_attribute.refresh_from_db()
assert file_attribute.values.count() == values_count + 1
@@ -495,6 +625,13 @@ def test_create_variant_with_boolean_attribute(
}
assert expected_attribute_data in data["attributes"]
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": boolean_attribute.slug},
+ "bool": True,
+ }
+ assert expected_assigned_attribute in assigned_attributes
created_webhook_mock.assert_called_once_with(product.variants.last())
@@ -555,6 +692,16 @@ def test_create_variant_with_file_attribute_new_value(
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
file_attribute.refresh_from_db()
assert file_attribute.values.count() == values_count + 1
@@ -617,6 +764,13 @@ def test_create_variant_with_file_attribute_no_file_url_given(
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
file_attribute.refresh_from_db()
assert file_attribute.values.count() == values_count
@@ -705,6 +859,14 @@ def test_create_variant_with_page_reference_attribute(
]
for value in expected_values:
assert value in data["attributes"][0]["values"]
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [{"slug": page_list[0].slug}, {"slug": page_list[1].slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert len(data["stocks"]) == 1
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
@@ -867,6 +1029,14 @@ def test_create_variant_with_product_reference_attribute(
]
for value in expected_values:
assert value in data["attributes"][0]["values"]
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product_list[0].slug}, {"slug": product_list[1].slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert len(data["stocks"]) == 1
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
@@ -1036,6 +1206,14 @@ def test_create_variant_with_variant_reference_attribute(
]
for value in expected_values:
assert value in data["attributes"][0]["values"]
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant_1.sku}, {"sku": variant_2.sku}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert len(data["stocks"]) == 1
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
@@ -1207,6 +1385,17 @@ def test_create_variant_with_category_reference_attribute(
]
for value in expected_values:
assert value in data["attributes"][0]["values"]
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_category_reference_attribute.slug},
+ "categories": [
+ {"slug": category_list[0].slug},
+ {"slug": category_list[1].slug},
+ ],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert len(data["stocks"]) == 1
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
@@ -1308,6 +1497,17 @@ def test_create_variant_with_collection_reference_attribute(
]
for value in expected_values:
assert value in data["attributes"][0]["values"]
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_collection_reference_attribute.slug},
+ "collections": [
+ {"slug": collection_list[0].slug},
+ {"slug": collection_list[1].slug},
+ ],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert len(data["stocks"]) == 1
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
@@ -1431,6 +1631,34 @@ def test_create_variant_with_single_reference_attributes(
for attr_data in data["attributes"]:
assert attr_data in expected_attributes_data
+ assigned_attributes = data["assignedAttributes"]
+
+ expected_assigned_page_attribute = {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "page": {"slug": page.slug},
+ }
+ expected_assigned_product_attribute = {
+ "attribute": {"slug": product_type_product_single_reference_attribute.slug},
+ "product": {"slug": product.slug},
+ }
+ expected_assigned_variant_attribute = {
+ "attribute": {"slug": product_type_variant_single_reference_attribute.slug},
+ "variant": {"sku": product_variant_list[0].sku},
+ }
+ expected_assigned_category_attribute = {
+ "attribute": {"slug": product_type_category_single_reference_attribute.slug},
+ "category": {"slug": categories[0].slug},
+ }
+ expected_assigned_collection_attribute = {
+ "attribute": {"slug": product_type_collection_single_reference_attribute.slug},
+ "collection": {"slug": collection.slug},
+ }
+ assert expected_assigned_page_attribute in assigned_attributes
+ assert expected_assigned_product_attribute in assigned_attributes
+ assert expected_assigned_variant_attribute in assigned_attributes
+ assert expected_assigned_category_attribute in assigned_attributes
+ assert expected_assigned_collection_attribute in assigned_attributes
+
created_webhook_mock.assert_called_once_with(product.variants.get(pk=variant_pk))
@@ -1489,6 +1717,14 @@ def test_create_variant_with_numeric_attribute(
data["attributes"][0]["values"][0]["slug"]
== f"{variant_pk}_{numeric_attribute.pk}"
)
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": numeric_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert data["weight"]["unit"] == WeightUnitsEnum.KG.name
assert data["weight"]["value"] == weight
assert len(data["stocks"]) == 1
@@ -1797,7 +2033,7 @@ def test_create_variant_with_rich_text_attribute(
sku = "1"
weight = 10.22
attr_id = graphene.Node.to_global_id("Attribute", rich_text_attribute.id)
- rich_text = json.dumps(dummy_editorjs("Sample text"))
+ rich_text = dummy_editorjs("Sample text")
stocks = [
{
"warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
@@ -1811,7 +2047,7 @@ def test_create_variant_with_rich_text_attribute(
"stocks": stocks,
"weight": weight,
"attributes": [
- {"id": attr_id, "richText": rich_text},
+ {"id": attr_id, "richText": json.dumps(rich_text)},
],
"trackInventory": True,
}
@@ -1826,7 +2062,15 @@ def test_create_variant_with_rich_text_attribute(
assert not content["errors"]
assert data["name"] == sku
assert data["sku"] == sku
- assert data["attributes"][-1]["values"][0]["richText"] == rich_text
+ assert data["attributes"][-1]["values"][0]["richText"] == json.dumps(rich_text)
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": rich_text_attribute.slug},
+ "text": rich_text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
created_webhook_mock.assert_called_once_with(product.variants.last())
@@ -1880,6 +2124,14 @@ def test_create_variant_with_plain_text_attribute(
assert data["name"] == sku
assert data["sku"] == sku
assert data["attributes"][-1]["values"][0]["plainText"] == text
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute.slug},
+ "plain_text": text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
created_webhook_mock.assert_called_once_with(product.variants.last())
@@ -1942,6 +2194,13 @@ def test_create_variant_with_date_attribute(
assert data["sku"] == sku
assert expected_attributes_data in data["attributes"]
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_attribute.slug},
+ "date": str(date_value),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
created_webhook_mock.assert_called_once_with(variant)
@@ -2005,6 +2264,13 @@ def test_create_variant_with_date_time_attribute(
assert data["sku"] == sku
assert expected_attributes_data in data["attributes"]
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_time_attribute.slug},
+ "datetime": date_time_value.isoformat(),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
created_webhook_mock.assert_called_once_with(variant)
@@ -2023,11 +2289,11 @@ def test_create_variant_with_empty_string_for_sku(
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = ""
weight = 10.22
- variant_slug = product_type.variant_attributes.first().slug
- attribute_id = graphene.Node.to_global_id(
- "Attribute", product_type.variant_attributes.first().pk
- )
- variant_value = "test-value"
+
+ attribute = product_type.variant_attributes.first()
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+ attr_value = "test-value"
+
stocks = [
{
"warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
@@ -2041,7 +2307,7 @@ def test_create_variant_with_empty_string_for_sku(
"sku": sku,
"stocks": stocks,
"weight": weight,
- "attributes": [{"id": attribute_id, "values": [variant_value]}],
+ "attributes": [{"id": attribute_id, "values": [attr_value]}],
"trackInventory": True,
}
}
@@ -2052,15 +2318,26 @@ def test_create_variant_with_empty_string_for_sku(
assert not content["errors"]
data = content["productVariant"]
- assert data["name"] == variant_value
+ assert data["name"] == attr_value
assert data["sku"] is None
- assert data["attributes"][0]["attribute"]["slug"] == variant_slug
- assert data["attributes"][0]["values"][0]["slug"] == variant_value
+ assert data["attributes"][0]["attribute"]["slug"] == attribute.slug
+ assert data["attributes"][0]["values"][0]["slug"] == attr_value
assert data["weight"]["unit"] == WeightUnitsEnum.KG.name
assert data["weight"]["value"] == weight
assert len(data["stocks"]) == 1
assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "choice": {
+ "name": attr_value,
+ "slug": attr_value.lower(),
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
created_webhook_mock.assert_called_once_with(product.variants.last())
updated_webhook_mock.assert_not_called()
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
index e15622ae03..497cb43597 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
@@ -42,6 +42,17 @@ def test_product_variant_update_with_new_attributes(
}
productVariant {
id
+ assignedAttributes(limit:10) {
+ ... on AssignedSingleChoiceAttribute {
+ attribute {
+ slug
+ }
+ choice: value {
+ name
+ slug
+ }
+ }
+ }
attributes {
attribute {
id
@@ -91,6 +102,16 @@ def test_product_variant_update_with_new_attributes(
assert len(attributes) == 1
assert attributes[0]["attribute"]["id"] == size_attribute_id
+ assigned_attributes = data["productVariant"]["assignedAttributes"]
+ expected_assigned_choice_attribute = {
+ "attribute": {"slug": size_attribute.slug},
+ "choice": {
+ "name": attr_value,
+ "slug": attr_value.lower(),
+ },
+ }
+ assert expected_assigned_choice_attribute in assigned_attributes
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
@@ -640,46 +661,140 @@ def test_update_product_variant_change_sku_to_empty_string(
QUERY_UPDATE_VARIANT_ATTRIBUTES = """
- mutation updateVariant (
- $id: ID!,
- $sku: String,
- $attributes: [AttributeValueInput!]) {
- productVariantUpdate(
- id: $id,
- input: {
- sku: $sku,
- attributes: $attributes
- }) {
- productVariant {
- sku
- attributes {
- attribute {
- slug
- }
- values {
- id
- slug
- name
- file {
- url
- contentType
- }
- reference
- richText
- plainText
- boolean
- date
- dateTime
- }
- }
- }
- errors {
- field
- code
- message
- }
+mutation updateVariant($id: ID!, $sku: String, $attributes: [AttributeValueInput!]) {
+ productVariantUpdate(id: $id, input: {sku: $sku, attributes: $attributes}) {
+ productVariant {
+ sku
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ ... on AssignedNumericAttribute {
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
+ }
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiChoiceAttribute {
+ multi: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
}
+ }
+ }
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
+ }
+ attributes {
+ attribute {
+ slug
}
+ values {
+ id
+ slug
+ name
+ file {
+ url
+ contentType
+ }
+ reference
+ richText
+ plainText
+ boolean
+ date
+ dateTime
+ }
+ }
+ }
+ errors {
+ field
+ code
+ message
+ }
+ }
+}
"""
@@ -711,6 +826,7 @@ def test_update_product_variant_do_not_require_required_attributes(
assert data["productVariant"]["sku"] == sku
assert len(data["productVariant"]["attributes"]) == 1
assert data["productVariant"]["attributes"][0]["values"]
+ assert len(data["productVariant"]["assignedAttributes"]) == 1
def test_update_product_variant_with_current_attribute(
@@ -808,6 +924,8 @@ def test_update_product_variant_with_value_that_matching_existing_slug(
assert not variant.sku == sku
attribute_1, attribute_2 = product.product_type.variant_attributes.all()
+ assert attribute_1.input_type == AttributeInputType.DROPDOWN
+ assert attribute_2.input_type == AttributeInputType.DROPDOWN
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
attribute_1_id = graphene.Node.to_global_id("Attribute", attribute_1.pk)
@@ -816,12 +934,14 @@ def test_update_product_variant_with_value_that_matching_existing_slug(
attr_1_values_count = attribute_1.values.count()
attr_2_values_count = attribute_2.values.count()
+ value_for_attr_1 = attribute_1.values.first()
+ value_for_attr_2 = attribute_2.values.first()
variables = {
"id": variant_id,
"sku": sku,
"attributes": [
- {"id": attribute_1_id, "values": [attribute_1.values.first().slug]},
- {"id": attribute_2_id, "values": [attribute_2.values.first().slug]},
+ {"id": attribute_1_id, "values": [value_for_attr_1.slug]},
+ {"id": attribute_2_id, "values": [value_for_attr_2.slug]},
],
}
@@ -841,6 +961,24 @@ def test_update_product_variant_with_value_that_matching_existing_slug(
for attr_data in data["productVariant"]["attributes"]:
assert len(attr_data["values"]) == 1
+ assigned_attributes = data["productVariant"]["assignedAttributes"]
+ expected_first_assigned_choice_attribute = {
+ "attribute": {"slug": attribute_1.slug},
+ "choice": {
+ "name": value_for_attr_1.name,
+ "slug": value_for_attr_1.slug,
+ },
+ }
+ expected_second_assigned_choice_attribute = {
+ "attribute": {"slug": attribute_2.slug},
+ "choice": {
+ "name": value_for_attr_2.name,
+ "slug": value_for_attr_2.slug,
+ },
+ }
+ assert expected_first_assigned_choice_attribute in assigned_attributes
+ assert expected_second_assigned_choice_attribute in assigned_attributes
+
def test_update_product_variant_with_value_that_matching_existing_name(
staff_api_client,
@@ -853,6 +991,8 @@ def test_update_product_variant_with_value_that_matching_existing_name(
assert not variant.sku == sku
attribute_1, attribute_2 = product.product_type.variant_attributes.all()
+ assert attribute_1.input_type == AttributeInputType.DROPDOWN
+ assert attribute_2.input_type == AttributeInputType.DROPDOWN
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
attribute_1_id = graphene.Node.to_global_id("Attribute", attribute_1.pk)
@@ -861,12 +1001,15 @@ def test_update_product_variant_with_value_that_matching_existing_name(
attr_1_values_count = attribute_1.values.count()
attr_2_values_count = attribute_2.values.count()
+ value_for_attr_1 = attribute_1.values.first()
+ value_for_attr_2 = attribute_2.values.first()
+
variables = {
"id": variant_id,
"sku": sku,
"attributes": [
- {"id": attribute_1_id, "values": [attribute_1.values.first().name]},
- {"id": attribute_2_id, "values": [attribute_2.values.first().name]},
+ {"id": attribute_1_id, "values": [value_for_attr_1.name]},
+ {"id": attribute_2_id, "values": [value_for_attr_2.name]},
],
}
@@ -888,6 +1031,24 @@ def test_update_product_variant_with_value_that_matching_existing_name(
for attr_data in data["productVariant"]["attributes"]:
assert len(attr_data["values"]) == 1
+ assigned_attributes = data["productVariant"]["assignedAttributes"]
+ expected_first_assigned_choice_attribute = {
+ "attribute": {"slug": attribute_1.slug},
+ "choice": {
+ "name": value_for_attr_1.name,
+ "slug": value_for_attr_1.slug,
+ },
+ }
+ expected_second_assigned_choice_attribute = {
+ "attribute": {"slug": attribute_2.slug},
+ "choice": {
+ "name": value_for_attr_2.name,
+ "slug": value_for_attr_2.slug,
+ },
+ }
+ assert expected_first_assigned_choice_attribute in assigned_attributes
+ assert expected_second_assigned_choice_attribute in assigned_attributes
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
def test_update_variant_with_boolean_attribute(
@@ -908,13 +1069,14 @@ def test_update_variant_with_boolean_attribute(
attr_id = graphene.Node.to_global_id("Attribute", boolean_attribute.id)
size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ size_value_name = "XXXL"
new_value = False
values_count = boolean_attribute.values.count()
variables = {
"id": variant_id,
"sku": sku,
"attributes": [
- {"id": size_attr_id, "values": ["XXXL"]},
+ {"id": size_attr_id, "values": [size_value_name]},
{"id": attr_id, "boolean": new_value},
],
}
@@ -936,6 +1098,22 @@ def test_update_variant_with_boolean_attribute(
assert data["attributes"][-1]["attribute"]["slug"] == boolean_attribute.slug
assert data["attributes"][-1]["values"][0]["name"] == "Boolean: No"
assert data["attributes"][-1]["values"][0]["boolean"] is new_value
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_boolean_assigned_choice_attribute = {
+ "attribute": {"slug": boolean_attribute.slug},
+ "bool": new_value,
+ }
+ expected_size_assigned_choice_attribute = {
+ "attribute": {"slug": size_attribute.slug},
+ "choice": {
+ "name": size_value_name,
+ "slug": size_value_name.lower(),
+ },
+ }
+ assert expected_boolean_assigned_choice_attribute in assigned_attributes
+ assert expected_size_assigned_choice_attribute in assigned_attributes
+
assert boolean_attribute.values.count() == values_count
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -985,6 +1163,19 @@ def test_update_variant_with_swatch_attribute_new_value_created(
assert data["sku"] == sku
assert data["attributes"][-1]["attribute"]["slug"] == swatch_attribute.slug
assert data["attributes"][-1]["values"][0]["name"] == value
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": swatch_attribute.slug},
+ "swatch": {
+ "name": value,
+ "slug": slugify(value),
+ "hexColor": None,
+ "file": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert swatch_attribute.values.count() == values_count + 1
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -1035,6 +1226,19 @@ def test_update_variant_with_swatch_attribute_existing_value(
assert data["sku"] == sku
assert data["attributes"][-1]["attribute"]["slug"] == swatch_attribute.slug
assert data["attributes"][-1]["values"][0]["name"] == value.name
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": swatch_attribute.slug},
+ "swatch": {
+ "name": value.name,
+ "slug": value.slug,
+ "hexColor": value.value,
+ "file": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert swatch_attribute.values.count() == values_count
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -1081,6 +1285,19 @@ def test_update_variant_with_swatch_attribute_use_values(
assert data["sku"] == sku
assert data["attributes"][-1]["attribute"]["slug"] == swatch_attribute.slug
assert data["attributes"][-1]["values"][0]["name"] == value
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": swatch_attribute.slug},
+ "swatch": {
+ "name": value,
+ "slug": slugify(value),
+ "hexColor": None,
+ "file": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert swatch_attribute.values.count() == values_count + 1
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -1126,6 +1343,13 @@ def test_update_variant_with_swatch_attribute_no_values_given(
assert data["attributes"][-1]["attribute"]["slug"] == swatch_attribute.slug
assert not data["attributes"][-1]["values"]
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": swatch_attribute.slug},
+ "swatch": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
def test_update_variant_with_rich_text_attribute(
@@ -1144,12 +1368,12 @@ def test_update_variant_with_rich_text_attribute(
sku = "123"
attr_id = graphene.Node.to_global_id("Attribute", rich_text_attribute.id)
rich_text_attribute_value = rich_text_attribute.values.first()
- rich_text = json.dumps(rich_text_attribute_value.rich_text)
+ rich_text = rich_text_attribute_value.rich_text
variables = {
"id": variant_id,
"sku": sku,
"attributes": [
- {"id": attr_id, "richText": rich_text},
+ {"id": attr_id, "richText": json.dumps(rich_text)},
],
}
rich_text_attribute_value.slug = f"{variant.id}_{rich_text_attribute.id}"
@@ -1169,7 +1393,15 @@ def test_update_variant_with_rich_text_attribute(
assert not content["errors"]
assert data["sku"] == sku
assert data["attributes"][-1]["attribute"]["slug"] == rich_text_attribute.slug
- assert data["attributes"][-1]["values"][0]["richText"] == rich_text
+ assert data["attributes"][-1]["values"][0]["richText"] == json.dumps(rich_text)
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": rich_text_attribute.slug},
+ "text": rich_text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert rich_text_attribute.values.count() == values_count
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -1221,6 +1453,14 @@ def test_update_variant_with_plain_text_attribute(
assert data["sku"] == sku
assert data["attributes"][-1]["attribute"]["slug"] == plain_text_attribute.slug
assert data["attributes"][-1]["values"][0]["plainText"] == text
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute.slug},
+ "plain_text": text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert plain_text_attribute.values.count() == values_count
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -1276,6 +1516,14 @@ def test_update_variant_with_plain_text_attribute_value_required(
assert data["sku"] == sku
assert data["attributes"][-1]["attribute"]["slug"] == plain_text_attribute.slug
assert data["attributes"][-1]["values"][0]["plainText"] == text
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": plain_text_attribute.slug},
+ "plain_text": text,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert plain_text_attribute.values.count() == values_count
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -1390,6 +1638,14 @@ def test_update_variant_with_date_attribute(
assert data["sku"] == sku
assert date_values_count + 1 == date_attribute.values.count()
assert expected_attributes_data in data["attributes"]
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_attribute.slug},
+ "date": str(date_value),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -1452,6 +1708,14 @@ def test_update_variant_with_date_time_attribute(
assert data["sku"] == sku
assert date_time_values_count + 1 == date_time_attribute.values.count()
assert expected_attributes_data in data["attributes"]
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": date_time_attribute.slug},
+ "datetime": date_time_value.isoformat(),
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -1497,6 +1761,14 @@ def test_update_variant_removes_numeric_attribute_value(
assert data["sku"] == sku
assert data["attributes"][-1]["attribute"]["slug"] == numeric_attribute.slug
assert not data["attributes"][-1]["values"]
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": None,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert numeric_attribute.values.count() == values_count
product_variant_updated.assert_called_once_with(product.variants.last())
@@ -1548,6 +1820,13 @@ def test_update_variant_adds_numeric_attribute(
assert attribute_data["attribute"]["slug"] == numeric_attribute.slug
assert attribute_data["values"][0]["name"] == numeric_name
+ assigned_attributes = data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": numeric_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
assert numeric_attribute.values.filter(
name=numeric_name, numeric=numeric_value
).first()
@@ -1636,6 +1915,13 @@ def test_update_product_variant_clear_attributes(
assert not data["errors"]
variant.refresh_from_db()
assert not data["productVariant"]["attributes"][0]["values"]
+ assigned_attributes = data["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": attribute.slug},
+ "multi": [],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
with pytest.raises(variant_attr._meta.model.DoesNotExist):
variant_attr.refresh_from_db()
@@ -1740,6 +2026,16 @@ def test_update_product_variant_with_current_file_attribute(
== f"{slugify(second_value)}-2"
)
+ assigned_attributes = variant_data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": None,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_update_product_variant_with_duplicated_file_attribute(
staff_api_client,
@@ -1843,6 +2139,16 @@ def test_update_product_variant_with_file_attribute_new_value_is_not_created(
assert value_data["file"]["url"] == file_url
assert value_data["file"]["contentType"] == existing_value.content_type
+ assigned_attributes = variant_data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": file_attribute.slug},
+ "file": {
+ "url": file_url,
+ "contentType": existing_value.content_type,
+ },
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_update_product_variant_with_page_reference_attribute(
staff_api_client,
@@ -1894,6 +2200,15 @@ def test_update_product_variant_with_page_reference_attribute(
)
assert variant_data["attributes"][0]["values"][0]["reference"] == reference
+ assigned_attributes = variant_data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [
+ {"slug": page.slug},
+ ],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_update_product_variant_with_product_reference_attribute(
staff_api_client,
@@ -1948,6 +2263,13 @@ def test_update_product_variant_with_product_reference_attribute(
)
assert variant_data["attributes"][0]["values"][0]["reference"] == reference
+ assigned_attributes = variant_data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product_ref.slug}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_update_product_variant_with_variant_reference_attribute(
staff_api_client,
@@ -2006,6 +2328,13 @@ def test_update_product_variant_with_variant_reference_attribute(
)
assert variant_data["attributes"][0]["values"][0]["reference"] == reference
+ assigned_attributes = variant_data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant_ref.sku}],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_update_product_variant_with_category_reference_attribute(
staff_api_client,
@@ -2061,6 +2390,15 @@ def test_update_product_variant_with_category_reference_attribute(
)
assert variant_data["attributes"][0]["values"][0]["reference"] == reference
+ assigned_attributes = variant_data["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": product_type_category_reference_attribute.slug},
+ "categories": [
+ {"slug": category.slug},
+ ],
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
def test_update_product_variant_with_single_reference_attributes(
staff_api_client,
@@ -2164,6 +2502,34 @@ def test_update_product_variant_with_single_reference_attributes(
for attr_data in attributes_data:
assert attr_data in expected_attributes_data
+ assigned_attributes = variant_data["assignedAttributes"]
+
+ expected_assigned_page_attribute = {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "page": {"slug": page.slug},
+ }
+ expected_assigned_product_attribute = {
+ "attribute": {"slug": product_type_product_single_reference_attribute.slug},
+ "product": {"slug": product.slug},
+ }
+ expected_assigned_variant_attribute = {
+ "attribute": {"slug": product_type_variant_single_reference_attribute.slug},
+ "variant": {"sku": product_variant_list[0].sku},
+ }
+ expected_assigned_category_attribute = {
+ "attribute": {"slug": product_type_category_single_reference_attribute.slug},
+ "category": {"slug": categories[0].slug},
+ }
+ expected_assigned_collection_attribute = {
+ "attribute": {"slug": product_type_collection_single_reference_attribute.slug},
+ "collection": {"slug": collection.slug},
+ }
+ assert expected_assigned_page_attribute in assigned_attributes
+ assert expected_assigned_product_attribute in assigned_attributes
+ assert expected_assigned_variant_attribute in assigned_attributes
+ assert expected_assigned_category_attribute in assigned_attributes
+ assert expected_assigned_collection_attribute in assigned_attributes
+
def test_update_product_variant_change_attribute_values_ordering(
staff_api_client,
@@ -2219,7 +2585,16 @@ def test_update_product_variant_change_attribute_values_ordering(
)
) == [attr_value_3.pk, attr_value_2.pk, attr_value_1.pk]
- new_ref_order = [product_list[1], product_list[0], product_list[2]]
+ expected_first_product = product_list[1]
+ expected_second_product = product_list[0]
+ expected_third_product = product_list[2]
+
+ new_ref_order = [
+ expected_first_product,
+ expected_second_product,
+ expected_third_product,
+ ]
+
variables = {
"id": variant_id,
"sku": sku,
@@ -2255,6 +2630,14 @@ def test_update_product_variant_change_attribute_values_ordering(
graphene.Node.to_global_id("AttributeValue", val.pk)
for val in [attr_value_2, attr_value_1, attr_value_3]
]
+ assigned_attributes = data["productVariant"]["assignedAttributes"]
+ assert len(assigned_attributes) == 1
+ assigned_values = assigned_attributes[0]["products"]
+ assert len(assigned_values) == 3
+ assert assigned_values[0]["slug"] == expected_first_product.slug
+ assert assigned_values[1]["slug"] == expected_second_product.slug
+ assert assigned_values[2]["slug"] == expected_third_product.slug
+
variant.refresh_from_db()
assert list(
variant.attributes.first().variantvalueassignment.values_list(
diff --git a/saleor/graphql/product/tests/queries/test_categories_query_with_filter.py b/saleor/graphql/product/tests/queries/test_categories_query_with_filter.py
index 9628f2b5bb..fcbb9de20b 100644
--- a/saleor/graphql/product/tests/queries/test_categories_query_with_filter.py
+++ b/saleor/graphql/product/tests/queries/test_categories_query_with_filter.py
@@ -169,13 +169,28 @@ query (
id
name
products(
- first: 5, channel: $channel, filter: $filters, where: $where, search: $search
+ first: 5
+ channel: $channel
+ filter: $filters
+ where: $where
+ search: $search
) {
edges {
node {
id
name
channel
+ assignedAttributes(limit:10) {
+ attribute {
+ choices(first: 10) {
+ edges {
+ node {
+ slug
+ }
+ }
+ }
+ }
+ }
attributes {
attribute {
choices(first: 10) {
@@ -340,6 +355,18 @@ def test_category_filter_products_by_multiple_attributes(
}
}
]
+ assert products[0]["node"]["assignedAttributes"] == [
+ {
+ "attribute": {
+ "choices": {
+ "edges": [
+ {"node": {"slug": "eco"}},
+ {"node": {"slug": "power"}},
+ ]
+ }
+ }
+ }
+ ]
@pytest.mark.parametrize(
diff --git a/saleor/graphql/product/tests/queries/test_collection_query.py b/saleor/graphql/product/tests/queries/test_collection_query.py
index c361a1ebc6..e14ec235a0 100644
--- a/saleor/graphql/product/tests/queries/test_collection_query.py
+++ b/saleor/graphql/product/tests/queries/test_collection_query.py
@@ -7,10 +7,7 @@ from django.core.files import File
from .....product.tests.utils import create_image
from .....thumbnail.models import Thumbnail
from ....core.enums import LanguageCodeEnum, ThumbnailFormatEnum
-from ....tests.utils import (
- get_graphql_content,
- get_graphql_content_from_response,
-)
+from ....tests.utils import get_graphql_content, get_graphql_content_from_response
QUERY_COLLECTION = """
query ($id: ID, $slug: String, $channel: String, $slugLanguageCode: LanguageCodeEnum){
@@ -183,6 +180,17 @@ query CollectionProducts(
edges {
node {
id
+ assignedAttributes(limit:10) {
+ attribute {
+ choices(first: 10) {
+ edges {
+ node {
+ slug
+ }
+ }
+ }
+ }
+ }
attributes {
attribute {
choices(first: 10) {
@@ -312,6 +320,18 @@ def test_filter_collection_products_by_multiple_attributes(
}
}
]
+ assert product["assignedAttributes"] == [
+ {
+ "attribute": {
+ "choices": {
+ "edges": [
+ {"node": {"slug": "eco"}},
+ {"node": {"slug": "power"}},
+ ]
+ }
+ }
+ }
+ ]
def test_filter_where_collection_products(
diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.py
index 5c33bb7929..2d65b7c70a 100644
--- a/saleor/graphql/product/tests/queries/test_product_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_query.py
@@ -1672,7 +1672,7 @@ def test_product_variant_without_price_as_staff_with_permission(
assert variants_data[1]["node"]["pricing"] is None
-def test_get_product_with_sorted_attribute_values(
+def test_get_product_with_sorted_attribute_values_for_attributes_field(
staff_api_client,
product,
permission_manage_products,
@@ -1734,6 +1734,71 @@ def test_get_product_with_sorted_attribute_values(
]
+def test_get_product_with_sorted_attribute_values_for_assigned_attributes_field(
+ staff_api_client,
+ product,
+ permission_manage_products,
+ product_type_page_reference_attribute,
+ page_list,
+):
+ # given
+ query = """
+ query getProduct($productID: ID!) {
+ product(id: $productID) {
+ assignedAttributes(limit:10) {
+ ... on AssignedMultiPageReferenceAttribute {
+ value {
+ id
+ }
+ }
+ }
+ }
+ }
+ """
+ product_type = product.product_type
+ product_type.product_attributes.set([product_type_page_reference_attribute])
+
+ attr_value_1 = AttributeValue.objects.create(
+ attribute=product_type_page_reference_attribute,
+ name=page_list[0].title,
+ slug=f"{product.pk}_{page_list[0].pk}",
+ reference_page=page_list[0],
+ )
+ attr_value_2 = AttributeValue.objects.create(
+ attribute=product_type_page_reference_attribute,
+ name=page_list[1].title,
+ slug=f"{product.pk}_{page_list[1].pk}",
+ reference_page=page_list[1],
+ )
+
+ associate_attribute_values_to_instance(
+ product,
+ {product_type_page_reference_attribute.pk: [attr_value_2, attr_value_1]},
+ )
+
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ variables = {"productID": product_id}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["product"]
+
+ assigned_attributes = data["assignedAttributes"]
+ assert len(assigned_attributes) == 1
+ assigned_values = assigned_attributes[0]["value"]
+ assert len(assigned_values) == 2
+ assert assigned_values[0]["id"] == graphene.Node.to_global_id(
+ "Page", page_list[1].pk
+ )
+ assert assigned_values[1]["id"] == graphene.Node.to_global_id(
+ "Page", page_list[0].pk
+ )
+
+
QUERY_PRODUCT_IMAGE_BY_ID = """
query productImageById($imageId: ID!, $productId: ID!, $channel: String) {
product(id: $productId, channel: $channel) {
@@ -2651,12 +2716,24 @@ query Product($id: ID!, $channel: String, $slug: String!) {
slug
}
}
+ assignedAttribute(slug: $slug) {
+ attribute {
+ id
+ slug
+ }
+ }
attributes {
attribute {
id
slug
}
}
+ assignedAttributes(limit:10) {
+ attribute {
+ id
+ slug
+ }
+ }
}
}
"""
@@ -2681,8 +2758,11 @@ def test_product_attribute_field_filtering(staff_api_client, product, channel_US
# then
expected_slug = "color"
content = get_graphql_content(response)
- queried_slug = content["data"]["product"]["attribute"]["attribute"]["slug"]
- assert queried_slug == expected_slug
+ product_data = content["data"]["product"]
+ attribute_queried_slug = product_data["attribute"]["attribute"]["slug"]
+ assigned_queried_slug = product_data["assignedAttribute"]["attribute"]["slug"]
+ assert assigned_queried_slug == expected_slug
+ assert attribute_queried_slug == expected_slug
def test_product_attribute_field_filtering_not_found(
@@ -2706,6 +2786,7 @@ def test_product_attribute_field_filtering_not_found(
# then
content = get_graphql_content(response)
assert content["data"]["product"]["attribute"] is None
+ assert content["data"]["product"]["assignedAttribute"] is None
def test_product_attribute_not_visible_in_storefront_for_customer_is_not_returned(
@@ -2741,6 +2822,7 @@ def test_product_attribute_not_visible_in_storefront_for_customer_is_not_returne
}
}
assert attr_data not in content["data"]["product"]["attributes"]
+ assert attr_data not in content["data"]["product"]["assignedAttributes"]
def test_product_attribute_visible_in_storefront_for_customer_is_returned(
@@ -2764,9 +2846,9 @@ def test_product_attribute_visible_in_storefront_for_customer_is_returned(
# then
content = get_graphql_content(response)
- assert (
- content["data"]["product"]["attribute"]["attribute"]["slug"] == attribute.slug
- )
+ product_data = content["data"]["product"]
+ assert product_data["attribute"]["attribute"]["slug"] == attribute.slug
+ assert product_data["assignedAttribute"]["attribute"]["slug"] == attribute.slug
@pytest.mark.parametrize("visible_in_storefront", [False, True])
@@ -3034,3 +3116,49 @@ def test_query_product_variants_with_where(
assert len(variants) == 1
assert variants[0]["node"]["sku"] == sku_value
+
+
+def test_applies_limit_on_product_assigned_attributes(
+ product, channel_USD, user_api_client, size_attribute
+):
+ # given
+ query = """
+ query Product($id: ID!, $channel: String) {
+ product(id: $id, channel: $channel) {
+ assignedAttributes(limit:1) {
+ attribute {
+ slug
+ }
+ }
+ }
+ }
+ """
+
+ associate_attribute_values_to_instance(
+ product,
+ {
+ size_attribute.pk: [size_attribute.values.first()],
+ },
+ )
+
+ assert product.attributevalues.count() == 2
+ first_attribute = product.attributevalues.first().value.attribute
+
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ variables = {
+ "id": product_id,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ expected_limit = 1
+ assert len(content["data"]["product"]["assignedAttributes"]) == expected_limit
+ assert (
+ content["data"]["product"]["assignedAttributes"][0]["attribute"]["slug"]
+ == first_attribute.slug
+ )
diff --git a/saleor/graphql/product/tests/queries/test_product_variant_query.py b/saleor/graphql/product/tests/queries/test_product_variant_query.py
index 055d4bce66..bf8a4ae043 100644
--- a/saleor/graphql/product/tests/queries/test_product_variant_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_variant_query.py
@@ -1,11 +1,14 @@
import graphene
+import pytest
from django.contrib.sites.models import Site
from measurement.measures import Weight
+from .....attribute.utils import associate_attribute_values_to_instance
from .....core.units import WeightUnits
from .....warehouse import WarehouseClickAndCollectOption
from ....core.enums import WeightUnitsEnum
from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import VariantAttributeScope
QUERY_VARIANT = """query ProductVariantDetails(
$id: ID!, $address: AddressInput, $countryCode: CountryCode, $channel: String
@@ -858,3 +861,181 @@ def test_query_product_variant_for_federation_as_staff_user_without_chanel(
"name": variant.name,
}
]
+
+
+ "variant_selection",
+ [
+ VariantAttributeScope.ALL.name,
+ VariantAttributeScope.VARIANT_SELECTION.name,
+ ],
+)
+def test_applies_limit_on_product_assigned_attributes(
+ variant,
+ channel_USD,
+ user_api_client,
+ size_attribute,
+ weight_attribute,
+ variant_selection,
+):
+ # given
+ query = """
+ query productVariant($id: ID!, $channel: String, $variantSelection: VariantAttributeScope) {
+ productVariant(id: $id, channel: $channel) {
+ assignedAttributes(limit: 1, variantSelection: $variantSelection) {
+ attribute {
+ slug
+ }
+ }
+ }
+ }
+ """
+
+ product_type = variant.product.product_type
+ product_type.variant_attributes.set([size_attribute, weight_attribute])
+
+ weight_attribute.storefront_search_position = (
+ size_attribute.storefront_search_position + 1
+ )
+ weight_attribute.save(update_fields=["storefront_search_position"])
+
+ associate_attribute_values_to_instance(
+ variant,
+ {
+ size_attribute.pk: [size_attribute.values.first()],
+ weight_attribute.pk: [weight_attribute.values.first()],
+ },
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {
+ "id": variant_id,
+ "channel": channel_USD.slug,
+ "variantSelection": variant_selection,
+ }
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ expected_limit = 1
+ assert (
+ len(content["data"]["productVariant"]["assignedAttributes"]) == expected_limit
+ )
+ assert (
+ content["data"]["productVariant"]["assignedAttributes"][0]["attribute"]["slug"]
+ == size_attribute.slug
+ )
+
+
+QUERY_PRODUCT_VARIANT_WITH_ASSIGNED_ATTRIBUTE = """
+query productVariant($id: ID!, $channel: String, $attrSlug: String!) {
+ productVariant(id: $id, channel: $channel) {
+ assignedAttribute(slug:$attrSlug){
+ attribute{
+ slug
+ }
+ ...on AssignedSingleChoiceAttribute{
+ value{
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_product_variant_with_assigned_attribute(
+ variant, channel_USD, user_api_client, size_attribute, weight_attribute
+):
+ # given
+ product_type = variant.product.product_type
+ product_type.variant_attributes.set([size_attribute, weight_attribute])
+
+ expected_attribute_value = size_attribute.values.first()
+ associate_attribute_values_to_instance(
+ variant,
+ {
+ size_attribute.pk: [expected_attribute_value],
+ weight_attribute.pk: [weight_attribute.values.first()],
+ },
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {
+ "id": variant_id,
+ "channel": channel_USD.slug,
+ "attrSlug": size_attribute.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_WITH_ASSIGNED_ATTRIBUTE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assigned_attribute_data = content["data"]["productVariant"]["assignedAttribute"]
+ assert assigned_attribute_data["attribute"]["slug"] == size_attribute.slug
+ assert assigned_attribute_data["value"]["slug"] == expected_attribute_value.slug
+
+
+def test_product_variant_with_assigned_attribute_without_value(
+ variant, channel_USD, user_api_client, size_attribute, weight_attribute
+):
+ # given
+ product_type = variant.product.product_type
+ product_type.variant_attributes.set([size_attribute, weight_attribute])
+
+ associate_attribute_values_to_instance(
+ variant,
+ {
+ size_attribute.pk: [],
+ weight_attribute.pk: [weight_attribute.values.first()],
+ },
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {
+ "id": variant_id,
+ "channel": channel_USD.slug,
+ "attrSlug": size_attribute.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_WITH_ASSIGNED_ATTRIBUTE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assigned_attribute_data = content["data"]["productVariant"]["assignedAttribute"]
+ assert assigned_attribute_data["attribute"]["slug"] == size_attribute.slug
+ assert assigned_attribute_data["value"] is None
+
+
+def test_product_variant_when_assigned_attribute_is_none(
+ variant, channel_USD, user_api_client, size_attribute, weight_attribute
+):
+ # given
+ product_type = variant.product.product_type
+ product_type.variant_attributes.set([size_attribute, weight_attribute])
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {
+ "id": variant_id,
+ "channel": channel_USD.slug,
+ "attrSlug": "non-existing-slug",
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_WITH_ASSIGNED_ATTRIBUTE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["productVariant"]["assignedAttribute"] is None
diff --git a/saleor/graphql/product/tests/queries/test_products_query.py b/saleor/graphql/product/tests/queries/test_products_query.py
index 23ac33d8e0..86f6f0c09e 100644
--- a/saleor/graphql/product/tests/queries/test_products_query.py
+++ b/saleor/graphql/product/tests/queries/test_products_query.py
@@ -1181,6 +1181,11 @@ def test_products_with_variants_query_as_app(
node{
id
name
+ assignedAttributes(limit:10) {
+ attribute {
+ slug
+ }
+ }
attributes {
attribute {
id
@@ -1211,6 +1216,9 @@ def test_products_with_variants_query_as_app(
attrs = response_product["node"]["attributes"]
assert len(attrs) == 1
assert attrs[0]["attribute"]["id"] == attribute_id
+ assigned_attribtues = response_product["node"]["assignedAttributes"]
+ assert len(assigned_attribtues) == 1
+ assert assigned_attribtues[0]["attribute"]["slug"] == attribute.slug
PRODUCT_SEARCH_QUERY = """
diff --git a/saleor/graphql/product/tests/queries/test_variant_query.py b/saleor/graphql/product/tests/queries/test_variant_query.py
index c590a05775..5c9afcfa03 100644
--- a/saleor/graphql/product/tests/queries/test_variant_query.py
+++ b/saleor/graphql/product/tests/queries/test_variant_query.py
@@ -28,6 +28,28 @@ query variant(
id
sku
externalReference
+ assignedAttributes(variantSelection: $variantSelection) {
+ attribute {
+ slug
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ }
attributes(variantSelection: $variantSelection) {
attribute {
slug
@@ -559,11 +581,20 @@ def test_get_variant_by_id_with_variant_selection_filter(
data["attributes"][0]["attribute"]["slug"]
== file_attribute_with_file_input_type_without_values.slug
)
+ assert len(data["assignedAttributes"]) == 1
+ assert (
+ data["assignedAttributes"][0]["attribute"]["slug"]
+ == file_attribute_with_file_input_type_without_values.slug
+ )
elif variant_selection == VariantAttributeScope.VARIANT_SELECTION.name:
assert len(data["attributes"]) == 1
assert data["attributes"][0]["attribute"]["slug"] == size_attribute.slug
+
+ assert len(data["assignedAttributes"]) == 1
+ assert data["assignedAttributes"][0]["attribute"]["slug"] == size_attribute.slug
else:
assert len(data["attributes"]) == 2
+ assert len(data["assignedAttributes"]) == 2
def test_get_variant_with_sorted_attribute_values(
@@ -581,18 +612,25 @@ def test_get_variant_with_sorted_attribute_values(
attribute=product_type_product_reference_attribute,
name=product_list[0].name,
slug=f"{variant.pk}_{product_list[0].pk}",
+ reference_product=product_list[0],
)
attr_value_2 = AttributeValue.objects.create(
attribute=product_type_product_reference_attribute,
name=product_list[1].name,
slug=f"{variant.pk}_{product_list[1].pk}",
+ reference_product=product_list[1],
)
attr_value_3 = AttributeValue.objects.create(
attribute=product_type_product_reference_attribute,
name=product_list[2].name,
slug=f"{variant.pk}_{product_list[2].pk}",
+ reference_product=product_list[2],
)
+ expected_first_product = product_list[1]
+ expected_second_product = product_list[0]
+ expected_third_product = product_list[2]
+
attr_values = [attr_value_2, attr_value_1, attr_value_3]
associate_attribute_values_to_instance(
variant, {product_type_product_reference_attribute.pk: attr_values}
@@ -615,6 +653,14 @@ def test_get_variant_with_sorted_attribute_values(
graphene.Node.to_global_id("AttributeValue", val.pk) for val in attr_values
]
+ assigned_attributes = data["assignedAttributes"]
+ assert len(assigned_attributes) == 1
+ assigned_values = assigned_attributes[0]["products"]
+ assert len(assigned_values) == 3
+ assert assigned_values[0]["slug"] == expected_first_product.slug
+ assert assigned_values[1]["slug"] == expected_second_product.slug
+ assert assigned_values[2]["slug"] == expected_third_product.slug
+
@pytest.mark.parametrize(
("field", "is_nested"),
diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.py
index 9bd42be725..0f01db74a0 100644
--- a/saleor/graphql/product/tests/test_attributes.py
+++ b/saleor/graphql/product/tests/test_attributes.py
@@ -25,34 +25,282 @@ from ...tests.utils import get_graphql_content
from ..enums import ProductAttributeType
QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = """
- query ($channel: String){
- products(first: 1, channel: $channel) {
- edges {
- node {
- attributes {
+query ($channel: String) {
+ products(first: 1, channel: $channel) {
+ edges {
+ node {
+ attributes {
+ attribute {
+ slug
+ type
+ }
+ values {
+ slug
+ }
+ }
+ assignedAttributes(limit:10) {
+ attr: attribute {
+ slug
+ type
+ }
+ ... on AssignedNumericAttribute {
+ attribute {
+ id
+ }
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ text_translation: translation(languageCode: FR)
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ plain_translation: translation(languageCode: FR)
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant_ref: value {
+ __typename
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ __typename
+ pages: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ __typename
+ producs: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ __typename
+ variants: value {
+ __typename
+ sku
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ __typename
+ categories: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ __typename
+ collections: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleChoiceAttribute {
+ __typename
+ choice: value {
+ name
+ slug
+ translation(languageCode: FR)
+ }
+ }
+ ... on AssignedMultiChoiceAttribute {
+ __typename
+ multi: value {
+ name
+ slug
+ translation(languageCode: FR)
+ }
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
+ }
+ }
+ }
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
+ }
+ variants {
+ attributes {
+ attribute {
+ slug
+ type
+ }
+ values {
+ slug
+ }
+ }
+ assignedAttributes(limit:10) {
+ ... on AssignedNumericAttribute {
attribute {
+ id
+ }
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ text_translation: translation(languageCode: FR)
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ plain_translation: translation(languageCode: FR)
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page_ref: value {
+ __typename
slug
- type
}
- values {
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product_ref: value {
+ __typename
slug
}
}
- variants {
- attributes {
- attribute {
- slug
- type
- }
- values {
- slug
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant_ref: value {
+ __typename
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection_ref: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ __typename
+ pages: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiProductReferenceAttribute {
+ __typename
+ producs: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ __typename
+ variants: value {
+ __typename
+ sku
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ __typename
+ categories: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ __typename
+ collections: value {
+ __typename
+ slug
+ }
+ }
+ ... on AssignedSingleChoiceAttribute {
+ __typename
+ choice: value {
+ name
+ slug
+ translation(languageCode: FR)
+ }
+ }
+ ... on AssignedMultiChoiceAttribute {
+ __typename
+ multi: value {
+ name
+ slug
+ translation(languageCode: FR)
+ }
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
}
}
}
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
+ }
}
}
}
}
+ }
+}
"""
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 064be71307..2077137b40 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -45,11 +45,13 @@ from ...attribute.filters import (
)
from ...attribute.resolvers import resolve_attributes
from ...attribute.types import (
+ AssignedAttribute,
AssignedVariantAttribute,
Attribute,
AttributeCountableConnection,
SelectedAttribute,
)
+from ...attribute.utils.shared import AssignedAttributeData
from ...channel.dataloaders import ChannelBySlugLoader
from ...channel.utils import get_default_channel_slug_or_graphql_error
from ...core.connection import (
@@ -57,12 +59,18 @@ from ...core.connection import (
create_connection_slice,
filter_connection_queryset,
)
+from ...core.const import DEFAULT_NESTED_LIST_LIMIT
from ...core.context import (
ChannelContext,
ChannelQsContext,
get_database_connection_name,
)
-from ...core.descriptions import ADDED_IN_321, DEPRECATED_IN_3X_INPUT, RICH_CONTENT
+from ...core.descriptions import (
+ ADDED_IN_321,
+ ADDED_IN_322,
+ DEPRECATED_IN_3X_INPUT,
+ RICH_CONTENT,
+)
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.enums import ReportingPeriod
from ...core.federation import federated_entity, resolve_federation_references
@@ -72,7 +80,7 @@ from ...core.fields import (
JSONString,
PermissionsField,
)
-from ...core.scalars import Date, DateTime
+from ...core.scalars import Date, DateTime, PositiveInt
from ...core.tracing import traced_resolver
from ...core.types import (
BaseObjectType,
@@ -87,7 +95,9 @@ from ...core.types import (
)
from ...core.types.context import ChannelContextType
from ...core.utils import from_global_id_or_error
-from ...core.validators import validate_one_of_args_is_in_query
+from ...core.validators import (
+ validate_one_of_args_is_in_query,
+)
from ...meta.types import ObjectWithMetadata
from ...order.dataloaders import (
OrderByIdLoader,
@@ -121,6 +131,9 @@ from ...warehouse.dataloaders import (
)
from ...warehouse.types import Stock
from ..dataloaders import (
+ AssignedAttributesAllByProductIdLoader,
+ AssignedAttributesByProductVariantIdLoader,
+ AssignedAttributesVisibleInStorefrontByProductIdLoader,
CategoryByIdLoader,
CollectionChannelListingByCollectionIdAndChannelSlugLoader,
CollectionsByProductIdLoader,
@@ -136,9 +149,6 @@ from ..dataloaders import (
ProductTypeByIdLoader,
ProductVariantByIdLoader,
ProductVariantsByProductIdLoader,
- SelectedAttributesAllByProductIdLoader,
- SelectedAttributesByProductVariantIdLoader,
- SelectedAttributesVisibleInStorefrontByProductIdLoader,
ThumbnailByProductMediaIdSizeAndFormatLoader,
VariantAttributesAllByProductTypeIdLoader,
VariantAttributesVisibleInStorefrontByProductTypeIdLoader,
@@ -329,6 +339,33 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
"only meant for displaying."
),
)
+ assigned_attribute = graphene.Field(
+ AssignedAttribute,
+ slug=graphene.Argument(
+ graphene.String,
+ description="Slug of the attribute",
+ required=True,
+ ),
+ description="Get a single attribute attached to product by attribute slug."
+ + ADDED_IN_322,
+ )
+
+ assigned_attributes = NonNullList(
+ AssignedAttribute,
+ required=True,
+ description="List of attributes assigned to this variant." + ADDED_IN_322,
+ variant_selection=graphene.Argument(
+ VariantAttributeScope,
+ description="Define scope of returned attributes.",
+ ),
+ limit=PositiveInt(
+ description=(
+ "Maximum number of attributes to return. "
+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}."
+ ),
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
+ )
attributes = NonNullList(
SelectedAttribute,
required=True,
@@ -582,18 +619,81 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
def resolve_digital_content(root: ChannelContext[models.ProductVariant], _info):
return getattr(root.node, "digital_content", None)
- @staticmethod
+ @classmethod
+ def resolve_assigned_attribute(
+ cls, root: ChannelContext[models.ProductVariant], info, slug
+ ):
+ def get_selected_attribute_by_slug(
+ attributes: (
+ list[
+ dict[
+ str,
+ attribute_models.Attribute
+ | list[attribute_models.AttributeValue],
+ ]
+ ]
+ | None
+ ),
+ ) -> AssignedAttributeData | None:
+ if attributes is None:
+ return None
+
+ for atr in attributes:
+ attribute = atr["attribute"]
+ attribute = cast(attribute_models.Attribute, attribute)
+ if attribute.slug == slug:
+ values = atr["values"]
+ values = cast(list[attribute_models.AttributeValue], values)
+ return AssignedAttributeData(
+ attribute=ChannelContext(attribute, root.channel_slug),
+ values=[
+ ChannelContext(value, root.channel_slug) for value in values
+ ],
+ )
+ return None
+
+ return (
+ AssignedAttributesByProductVariantIdLoader(info.context)
+ .load(root.node.id)
+ .then(get_selected_attribute_by_slug)
+ )
+
+ @classmethod
def resolve_attributes(
+ cls,
+ root: ChannelContext[models.ProductVariant],
+ info,
+ variant_selection: VariantAttributeScope | None = None,
+ ):
+ return cls._resolve_attributes(root, info, variant_selection)
+
+ @classmethod
+ def resolve_assigned_attributes(
+ cls,
root: ChannelContext[models.ProductVariant],
info,
variant_selection: str | None = None,
+ limit: int = DEFAULT_NESTED_LIST_LIMIT,
+ ):
+ return cls._resolve_attributes(root, info, variant_selection, limit)
+
+ @classmethod
+ def _resolve_attributes(
+ cls,
+ root: ChannelContext[models.ProductVariant],
+ info,
+ variant_selection: str | None = None,
+ limit: int | None = None,
):
def apply_variant_selection_filter(
selected_attributes,
- ) -> list[SelectedAttribute]:
+ ) -> list[AssignedAttributeData]:
if not variant_selection or variant_selection == VariantAttributeScope.ALL:
+ selected_attributes = (
+ selected_attributes[:limit] if limit else selected_attributes
+ )
return [
- SelectedAttribute(
+ AssignedAttributeData(
attribute=ChannelContext(
selected_att["attribute"], root.channel_slug
),
@@ -625,9 +725,12 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
for selected_att in selected_attributes
if selected_att["attribute"] not in variant_selection_attrs
]
+ attributes_to_return = (
+ attributes_to_return[:limit] if limit else attributes_to_return
+ )
return [
- SelectedAttribute(
+ AssignedAttributeData(
attribute=ChannelContext(
selected_att["attribute"], root.channel_slug
),
@@ -640,7 +743,7 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
]
return (
- SelectedAttributesByProductVariantIdLoader(info.context)
+ AssignedAttributesByProductVariantIdLoader(info.context)
.load(root.node.id)
.then(apply_variant_selection_filter)
)
@@ -946,6 +1049,29 @@ class Product(ChannelContextType[models.Product]):
description="A type of tax. Assigned by enabled tax gateway",
deprecation_reason="Use `taxClass` field instead.",
)
+ assigned_attribute = graphene.Field(
+ AssignedAttribute,
+ slug=graphene.Argument(
+ graphene.String,
+ description="Slug of the attribute",
+ required=True,
+ ),
+ description="Get a single attribute attached to product by attribute slug."
+ + ADDED_IN_322,
+ )
+ assigned_attributes = NonNullList(
+ AssignedAttribute,
+ required=True,
+ description="List of attributes assigned to this product." + ADDED_IN_322,
+ limit=PositiveInt(
+ description=(
+ "Maximum number of attributes to return. "
+ f"Default is {DEFAULT_NESTED_LIST_LIMIT}."
+ ),
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
+ )
+
attribute = graphene.Field(
SelectedAttribute,
slug=graphene.Argument(
@@ -1332,8 +1458,18 @@ class Product(ChannelContextType[models.Product]):
.then(check_is_available_for_purchase)
)
- @staticmethod
- def resolve_attribute(root: ChannelContext[models.Product], info, slug):
+ @classmethod
+ def resolve_assigned_attribute(
+ cls, root: ChannelContext[models.Product], info, slug
+ ):
+ return cls._resolve_attribute(root, info, slug)
+
+ @classmethod
+ def resolve_attribute(cls, root: ChannelContext[models.Product], info, slug):
+ return cls._resolve_attribute(root, info, slug)
+
+ @classmethod
+ def _resolve_attribute(cls, root: ChannelContext[models.Product], info, slug):
def get_selected_attribute_by_slug(
attributes: (
list[
@@ -1345,7 +1481,7 @@ class Product(ChannelContextType[models.Product]):
]
| None
),
- ) -> SelectedAttribute | None:
+ ) -> AssignedAttributeData | None:
if attributes is None:
return None
@@ -1355,7 +1491,7 @@ class Product(ChannelContextType[models.Product]):
if attribute.slug == slug:
values = atr["values"]
values = cast(list[attribute_models.AttributeValue], values)
- return SelectedAttribute(
+ return AssignedAttributeData(
attribute=ChannelContext(attribute, root.channel_slug),
values=[
ChannelContext(value, root.channel_slug) for value in values
@@ -1370,18 +1506,33 @@ class Product(ChannelContextType[models.Product]):
and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)
):
return (
- SelectedAttributesAllByProductIdLoader(info.context)
+ AssignedAttributesAllByProductIdLoader(info.context)
.load(root.node.id)
.then(get_selected_attribute_by_slug)
)
return (
- SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)
+ AssignedAttributesVisibleInStorefrontByProductIdLoader(info.context)
.load(root.node.id)
.then(get_selected_attribute_by_slug)
)
- @staticmethod
- def resolve_attributes(root: ChannelContext[models.Product], info):
+ @classmethod
+ def resolve_assigned_attributes(
+ cls,
+ root: ChannelContext[models.Product],
+ info,
+ limit: int = DEFAULT_NESTED_LIST_LIMIT,
+ ):
+ return cls._resolve_attributes(root, info, limit)
+
+ @classmethod
+ def resolve_attributes(cls, root: ChannelContext[models.Product], info):
+ return cls._resolve_attributes(root, info)
+
+ @classmethod
+ def _resolve_attributes(
+ cls, root: ChannelContext[models.Product], info, limit: int | None = None
+ ):
def wrap_with_channel_context(
attributes: (
list[
@@ -1393,7 +1544,7 @@ class Product(ChannelContextType[models.Product]):
]
| None
),
- ) -> list[SelectedAttribute] | None:
+ ) -> list[AssignedAttributeData] | None:
if attributes is None:
return None
@@ -1404,13 +1555,14 @@ class Product(ChannelContextType[models.Product]):
values = attr_data["values"]
values = cast(list[attribute_models.AttributeValue], values)
response.append(
- SelectedAttribute(
+ AssignedAttributeData(
attribute=ChannelContext(attribute, root.channel_slug),
values=[
ChannelContext(value, root.channel_slug) for value in values
],
)
)
+ response = response[:limit] if limit else response
return response
requestor = get_user_or_app_from_context(info.context)
@@ -1420,12 +1572,12 @@ class Product(ChannelContextType[models.Product]):
and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)
):
return (
- SelectedAttributesAllByProductIdLoader(info.context)
+ AssignedAttributesAllByProductIdLoader(info.context)
.load(root.node.id)
.then(wrap_with_channel_context)
)
return (
- SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)
+ AssignedAttributesVisibleInStorefrontByProductIdLoader(info.context)
.load(root.node.id)
.then(wrap_with_channel_context)
)
diff --git a/saleor/graphql/query_cost_map.py b/saleor/graphql/query_cost_map.py
index c2d55e028a..47aed5f90a 100644
--- a/saleor/graphql/query_cost_map.py
+++ b/saleor/graphql/query_cost_map.py
@@ -141,6 +141,91 @@ COST_MAP = {
"tokens": {"complexity": 1},
"webhooks": {"complexity": 1},
},
+ "AssignedAttribute": {"attribute": {"complexity": 1}},
+ "AssignedNumericAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedTextAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ "translation": {"complexity": 1},
+ },
+ "AssignedPlainTextAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ "translation": {"complexity": 1},
+ },
+ "AssignedFileAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedChoiceAttributeValue": {
+ "translation": {"complexity": 1},
+ },
+ "AssignedSingleChoiceAttribute": {
+ "value": {"complexity": 1},
+ },
+ "AssignedMultiChoiceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1, "multipliers": ["limit"]},
+ },
+ "AssignedSwatchAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedBooleanAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedDateAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedDateTimeAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedMultiPageReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1, "multipliers": ["limit"]},
+ },
+ "AssignedMultiProductReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1, "multipliers": ["limit"]},
+ },
+ "AssignedMultiProductVariantReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1, "multipliers": ["limit"]},
+ },
+ "AssignedMultiCategoryReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1, "multipliers": ["limit"]},
+ },
+ "AssignedMultiCollectionReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1, "multipliers": ["limit"]},
+ },
+ "AssignedSinglePageReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedSingleProductReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedSingleProductVariantReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedSingleCategoryReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
+ "AssignedSingleCollectionReferenceAttribute": {
+ "attribute": {"complexity": 1},
+ "value": {"complexity": 1},
+ },
"Attribute": {
"choices": {"complexity": 1, "multipliers": ["first", "last"]},
"productTypes": {"complexity": 1, "multipliers": ["first", "last"]},
@@ -233,6 +318,7 @@ COST_MAP = {
"variant": {"complexity": 1},
},
"Page": {
+ "assignedAttributes": {"complexity": 1, "multipliers": ["limit"]},
"attributes": {"complexity": 1},
"pageType": {"complexity": 1},
},
@@ -245,6 +331,7 @@ COST_MAP = {
"transactions": {"complexity": 1},
},
"Product": {
+ "assignedAttributes": {"complexity": 1, "multipliers": ["limit"]},
"attributes": {"complexity": 1},
"category": {"complexity": 1},
"channelListings": {"complexity": 1},
@@ -277,6 +364,7 @@ COST_MAP = {
"products": {"complexity": 1, "multipliers": ["first", "last"]},
},
"ProductVariant": {
+ "assignedAttributes": {"complexity": 1, "multipliers": ["limit"]},
"attributes": {"complexity": 1},
"channelListings": {"complexity": 1},
"images": {"complexity": 1},
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 45879866e3..436fa47ca0 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -8,7 +8,7 @@ schema {
directive @doc(
"""Name of the grouping category"""
category: String!
-) on ENUM | FIELD | FIELD_DEFINITION | INPUT_OBJECT | OBJECT
+) on ENUM | FIELD | FIELD_DEFINITION | INPUT_OBJECT | OBJECT | INTERFACE
"""Webhook events triggered by a specific location."""
directive @webhookEventsInfo(
@@ -5699,6 +5699,26 @@ type Product implements Node & ObjectWithMetadata @doc(category: "Products") {
"""A type of tax. Assigned by enabled tax gateway"""
taxType: TaxType @deprecated(reason: "Use `taxClass` field instead.")
+ """
+ Get a single attribute attached to product by attribute slug.
+
+ Added in Saleor 3.22.
+ """
+ assignedAttribute(
+ """Slug of the attribute"""
+ slug: String!
+ ): AssignedAttribute
+
+ """
+ List of attributes assigned to this product.
+
+ Added in Saleor 3.22.
+ """
+ assignedAttributes(
+ """Maximum number of attributes to return. Default is 100."""
+ limit: PositiveInt = 100
+ ): [AssignedAttribute!]!
+
"""Get a single attribute attached to product by attribute slug."""
attribute(
"""Slug of the attribute"""
@@ -7385,6 +7405,29 @@ type ProductVariant implements Node & ObjectWithMetadata @doc(category: "Product
address: AddressInput
): VariantPricingInfo
+ """
+ Get a single attribute attached to product by attribute slug.
+
+ Added in Saleor 3.22.
+ """
+ assignedAttribute(
+ """Slug of the attribute"""
+ slug: String!
+ ): AssignedAttribute
+
+ """
+ List of attributes assigned to this variant.
+
+ Added in Saleor 3.22.
+ """
+ assignedAttributes(
+ """Define scope of returned attributes."""
+ variantSelection: VariantAttributeScope
+
+ """Maximum number of attributes to return. Default is 100."""
+ limit: PositiveInt = 100
+ ): [AssignedAttribute!]!
+
"""List of attributes assigned to this variant."""
attributes(
"""Define scope of returned attributes."""
@@ -7626,6 +7669,23 @@ input MetadataInput {
value: String!
}
+"""
+Represents an attribute assigned to an object.
+
+Added in Saleor 3.22.
+"""
+interface AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+}
+
+"""
+Positive Integer scalar implementation.
+
+Should be used in places where value must be positive (greater than 0).
+"""
+scalar PositiveInt
+
"""Represents an assigned attribute to an object."""
type SelectedAttribute @doc(category: "Attributes") {
"""Name of an attribute displayed in the interface."""
@@ -8694,10 +8754,30 @@ type Page implements Node & ObjectWithMetadata @doc(category: "Pages") {
attribute(
"""Slug of the attribute"""
slug: String!
- ): SelectedAttribute
+ ): SelectedAttribute @deprecated(reason: "Use `assignedAttribute` field instead.")
+
+ """
+ Get a single attribute attached to page by attribute slug.
+
+ Added in Saleor 3.22.
+ """
+ assignedAttribute(
+ """Slug of the attribute"""
+ slug: String!
+ ): AssignedAttribute
+
+ """
+ List of attributes assigned to this page.
+
+ Added in Saleor 3.22.
+ """
+ assignedAttributes(
+ """Maximum number of attributes to return. Default is 100."""
+ limit: PositiveInt = 100
+ ): [AssignedAttribute!]!
"""List of attributes assigned to this page."""
- attributes: [SelectedAttribute!]!
+ attributes: [SelectedAttribute!]! @deprecated(reason: "Use `assignedAttributes` field instead.")
}
"""
@@ -34466,6 +34546,327 @@ type OtherPaymentMethodDetails implements PaymentMethodDetails {
name: String!
}
+"""
+Represents a numeric value of an attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedNumericAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned numeric value."""
+ value: Float
+}
+
+"""
+Represents text attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedTextAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned rich text content."""
+ value: JSON
+
+ """Translation of the rich text content in the specified language."""
+ translation(languageCode: LanguageCodeEnum!): JSON
+}
+
+"""
+Represents plain text attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedPlainTextAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned plain text content."""
+ value: String
+
+ """Translation of the plain text content in the specified language."""
+ translation(languageCode: LanguageCodeEnum!): String
+}
+
+"""
+Represents file attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedFileAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned file."""
+ value: File
+}
+
+"""
+Represents a single choice attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedSingleChoiceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned choice value."""
+ value: AssignedChoiceAttributeValue
+}
+
+"""
+Represents a single choice value of the attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedChoiceAttributeValue @doc(category: "Attributes") {
+ """Name of a value displayed in the interface."""
+ name: String
+
+ """Internal representation of a value (unique per attribute)."""
+ slug: String
+
+ """Translation of the name."""
+ translation(languageCode: LanguageCodeEnum!): String
+}
+
+"""
+Represents a multi choice attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedMultiChoiceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """List of assigned choice values."""
+ value(
+ """Maximum number of choices to return. Default is 100."""
+ limit: PositiveInt = 100
+ ): [AssignedChoiceAttributeValue!]!
+}
+
+"""
+Represents a swatch attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedSwatchAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned swatch value."""
+ value: AssignedSwatchAttributeValue
+}
+
+"""
+Represents a single swatch value.
+
+Added in Saleor 3.22.
+"""
+type AssignedSwatchAttributeValue @doc(category: "Attributes") {
+ """Name of the selected swatch value."""
+ name: String
+
+ """Slug of the selected swatch value."""
+ slug: String
+
+ """Hex color code."""
+ hexColor: String
+
+ """File associated with the attribute."""
+ file: File
+}
+
+"""
+Represents a boolean attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedBooleanAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned boolean value."""
+ value: Boolean
+}
+
+"""
+Represents a date attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedDateAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned date value."""
+ value: Date
+}
+
+"""
+Represents a date time attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedDateTimeAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned date time value."""
+ value: DateTime
+}
+
+"""
+Represents single page reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedSinglePageReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned page reference."""
+ value: Page
+}
+
+"""
+Represents single product reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedSingleProductReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned product reference."""
+ value: Product
+}
+
+"""
+Represents single product variant reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedSingleProductVariantReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned product variant reference."""
+ value: ProductVariant
+}
+
+"""
+Represents single category reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedSingleCategoryReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned category reference."""
+ value: Category
+}
+
+"""
+Represents single collection reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedSingleCollectionReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """The assigned collection reference."""
+ value: Collection
+}
+
+"""
+Represents multi page reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedMultiPageReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """List of assigned page references."""
+ value(
+ """Maximum number of referenced pages to return. Default is 100."""
+ limit: PositiveInt = 100
+ ): [Page!]!
+}
+
+"""
+Represents multi product reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedMultiProductReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """List of assigned product references."""
+ value(
+ """Maximum number of referenced products to return. Default is 100."""
+ limit: PositiveInt = 100
+ ): [Product!]!
+}
+
+"""
+Represents multi product variant reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedMultiProductVariantReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """List of assigned product variant references."""
+ value(
+ """
+ Maximum number of referenced product variants to return. Default is 100.
+ """
+ limit: PositiveInt = 100
+ ): [ProductVariant!]!
+}
+
+"""
+Represents multi category reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedMultiCategoryReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """List of assigned category references."""
+ value(
+ """Maximum number of referenced categories to return. Default is 100."""
+ limit: PositiveInt = 100
+ ): [Category!]!
+}
+
+"""
+Represents multi collection reference attribute.
+
+Added in Saleor 3.22.
+"""
+type AssignedMultiCollectionReferenceAttribute implements AssignedAttribute @doc(category: "Attributes") {
+ """Attribute assigned to an object."""
+ attribute: Attribute!
+
+ """List of assigned collection references."""
+ value(
+ """Maximum number of referenced collections to return. Default is 100"""
+ limit: PositiveInt = 100
+ ): [Collection!]!
+}
+
"""_Any value scalar as defined by Federation spec."""
scalar _Any
diff --git a/saleor/graphql/schema_printer.py b/saleor/graphql/schema_printer.py
index 08b4ddc79e..8050d30f21 100644
--- a/saleor/graphql/schema_printer.py
+++ b/saleor/graphql/schema_printer.py
@@ -252,7 +252,12 @@ def print_object(type_: GrapheneObjectType) -> str:
def print_interface(type_: GraphQLInterfaceType) -> str:
- return print_description(type_) + f"interface {type_.name}" + print_fields(type_)
+ return (
+ print_description(type_)
+ + f"interface {type_.name}"
+ + print_object_directives(type_)
+ + print_fields(type_)
+ )
def print_union(type_: GraphQLUnionType) -> str:
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index 993a22ced4..8c01000491 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -34,18 +34,18 @@ from ..discount.dataloaders import (
)
from ..menu.dataloaders import MenuItemByIdLoader
from ..page.dataloaders import (
+ AssignedAttributesAllByPageIdLoader,
+ AssignedAttributesVisibleInStorefrontPageIdLoader,
PageByIdLoader,
- SelectedAttributesAllByPageIdLoader,
- SelectedAttributesVisibleInStorefrontPageIdLoader,
)
from ..product.dataloaders import (
+ AssignedAttributesAllByProductIdLoader,
+ AssignedAttributesByProductVariantIdLoader,
+ AssignedAttributesVisibleInStorefrontByProductIdLoader,
CategoryByIdLoader,
CollectionByIdLoader,
ProductByIdLoader,
ProductVariantByIdLoader,
- SelectedAttributesAllByProductIdLoader,
- SelectedAttributesByProductVariantIdLoader,
- SelectedAttributesVisibleInStorefrontByProductIdLoader,
)
from ..shipping.dataloaders import ShippingMethodByIdLoader
from ..utils import get_user_or_app_from_context
@@ -294,7 +294,7 @@ class ProductVariantTranslatableContent(ModelObjectType[product_models.ProductVa
@staticmethod
def resolve_attribute_values(root: product_models.ProductVariant, info):
return (
- SelectedAttributesByProductVariantIdLoader(info.context)
+ AssignedAttributesByProductVariantIdLoader(info.context)
.load(root.id)
.then(get_translatable_attribute_values)
)
@@ -396,12 +396,12 @@ class ProductTranslatableContent(ModelObjectType[product_models.Product]):
and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)
):
return (
- SelectedAttributesAllByProductIdLoader(info.context)
+ AssignedAttributesAllByProductIdLoader(info.context)
.load(root.id)
.then(get_translatable_attribute_values)
)
return (
- SelectedAttributesVisibleInStorefrontByProductIdLoader(info.context)
+ AssignedAttributesVisibleInStorefrontByProductIdLoader(info.context)
.load(root.id)
.then(get_translatable_attribute_values)
)
@@ -680,12 +680,12 @@ class PageTranslatableContent(ModelObjectType[page_models.Page]):
and requestor.has_perm(PagePermissions.MANAGE_PAGES)
):
return (
- SelectedAttributesAllByPageIdLoader(info.context)
+ AssignedAttributesAllByPageIdLoader(info.context)
.load(root.id)
.then(get_translatable_attribute_values)
)
return (
- SelectedAttributesVisibleInStorefrontPageIdLoader(info.context)
+ AssignedAttributesVisibleInStorefrontPageIdLoader(info.context)
.load(root.id)
.then(get_translatable_attribute_values)
)