Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add reference attribute input type (#6575)
Iga Karbowiakf0ceede4ee84
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.pyindex 2c98a3dc64..a1690307a8 100644--- a/saleor/attribute/__init__.py+++ b/saleor/attribute/__init__.py@@ -4,8 +4,14 @@ class AttributeInputType:DROPDOWN = "dropdown"MULTISELECT = "multiselect"FILE = "file"+ REFERENCE = "reference"- CHOICES = [(DROPDOWN, "Dropdown"), (MULTISELECT, "Multi Select"), (FILE, "File")]+ CHOICES = [+ (DROPDOWN, "Dropdown"),+ (MULTISELECT, "Multi Select"),+ (FILE, "File"),+ (REFERENCE, "Reference"),+ ]# list of the input types that can be used in variant selectionALLOWED_IN_VARIANT_SELECTION = [DROPDOWN]@@ -15,3 +21,9 @@ class AttributeType:PAGE_TYPE = "page-type"CHOICES = [(PRODUCT_TYPE, "Product type"), (PAGE_TYPE, "Page type")]+++class AttributeEntityType:+ PAGE = "page"++ CHOICES = [(PAGE, "Page")]diff --git a/saleor/attribute/migrations/0004_auto_20201203_1115.py b/saleor/attribute/migrations/0004_auto_20201203_1115.pynew file mode 100644index 0000000000..739c20b0b3--- /dev/null+++ b/saleor/attribute/migrations/0004_auto_20201203_1115.py@@ -0,0 +1,34 @@+# Generated by Django 3.1.3 on 2020-12-03 11:15++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("attribute", "0003_auto_20201113_1149"),+ ]++ operations = [+ migrations.AddField(+ model_name="attribute",+ name="entity_type",+ field=models.CharField(+ blank=True, choices=[("page", "Page")], max_length=50, null=True+ ),+ ),+ migrations.AlterField(+ model_name="attribute",+ name="input_type",+ field=models.CharField(+ choices=[+ ("dropdown", "Dropdown"),+ ("multiselect", "Multi Select"),+ ("file", "File"),+ ("reference", "Reference"),+ ],+ default="dropdown",+ max_length=50,+ ),+ ),+ ]diff --git a/saleor/attribute/models.py b/saleor/attribute/models.pyindex 170d7467f9..3db58606ca 100644--- a/saleor/attribute/models.py+++ b/saleor/attribute/models.py@@ -8,7 +8,7 @@ from ..core.permissions import ProductPermissionsfrom ..core.utils.translations import TranslationProxyfrom ..page.models import Page, PageTypefrom ..product.models import Product, ProductType, ProductVariant-from . import AttributeInputType, AttributeType+from . import AttributeEntityType, AttributeInputType, AttributeTypeif TYPE_CHECKING:from ..account.models import User@@ -226,6 +226,9 @@ class Attribute(ModelWithMetadata):choices=AttributeInputType.CHOICES,default=AttributeInputType.DROPDOWN,)+ entity_type = models.CharField(+ max_length=50, choices=AttributeEntityType.CHOICES, blank=True, null=True+ )product_types = models.ManyToManyField(ProductType,diff --git a/saleor/graphql/attribute/descriptions.py b/saleor/graphql/attribute/descriptions.pyindex 9c69b45400..027d929948 100644--- a/saleor/graphql/attribute/descriptions.py+++ b/saleor/graphql/attribute/descriptions.py@@ -1,5 +1,6 @@class AttributeDescriptions:INPUT_TYPE = "The input type to use for entering attribute values in the dashboard."+ ENTITY_TYPE = "The entity type which can be used as a reference."NAME = "Name of an attribute displayed in the interface."SLUG = "Internal representation of an attribute name."TYPE = "The attribute type."diff --git a/saleor/graphql/attribute/enums.py b/saleor/graphql/attribute/enums.pyindex ad109a9f9d..58b0a4244b 100644--- a/saleor/graphql/attribute/enums.py+++ b/saleor/graphql/attribute/enums.py@@ -1,10 +1,11 @@import graphene-from ...attribute import AttributeInputType, AttributeType+from ...attribute import AttributeEntityType, AttributeInputType, AttributeTypefrom ..core.enums import to_enumAttributeInputTypeEnum = to_enum(AttributeInputType)AttributeTypeEnum = to_enum(AttributeType)+AttributeEntityTypeEnum = to_enum(AttributeEntityType)class AttributeValueType(graphene.Enum):diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.pyindex b61f635a5d..59a1cff6b0 100644--- a/saleor/graphql/attribute/mutations.py+++ b/saleor/graphql/attribute/mutations.py@@ -24,7 +24,7 @@ from ..core.utils import (from ..core.utils.reordering import perform_reorderingfrom ..utils import resolve_global_ids_to_primary_keysfrom .descriptions import AttributeDescriptions, AttributeValueDescriptions-from .enums import AttributeInputTypeEnum, AttributeTypeEnum+from .enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnumif TYPE_CHECKING:from django.db.models import QuerySet@@ -86,6 +86,7 @@ class AttributeValueCreateInput(graphene.InputObjectType):class AttributeCreateInput(graphene.InputObjectType):input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)+ entity_type = AttributeEntityTypeEnum(description=AttributeDescriptions.ENTITY_TYPE)name = graphene.String(required=True, description=AttributeDescriptions.NAME)slug = graphene.String(required=False, description=AttributeDescriptions.SLUG)type = AttributeTypeEnum(description=AttributeDescriptions.TYPE, required=True)@@ -195,11 +196,16 @@ class AttributeMixin:if values_input is None:return- if attribute_input_type == AttributeInputType.FILE and values_input:+ if (+ attribute_input_type+ in [AttributeInputType.FILE, AttributeInputType.REFERENCE]+ and values_input+ ):raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: ValidationError(- "Values cannot be used with input type FILE.",+ "Values cannot be used with "+ f"input type {attribute_input_type}.",code=AttributeErrorCode.INVALID.value,)}@@ -237,7 +243,10 @@ class AttributeMixin:Ensure that any invalid operations will be not performed."""attribute_input_type = cleaned_input.get("input_type") or instance.input_type- if attribute_input_type != AttributeInputType.FILE:+ if attribute_input_type not in [+ AttributeInputType.FILE,+ AttributeInputType.REFERENCE,+ ]:returnerrors = {}for field in [@@ -248,7 +257,7 @@ class AttributeMixin:]:if cleaned_input.get(field):errors[field] = ValidationError(- "Cannot set on a file attribute.",+ f"Cannot set on a {attribute_input_type} attribute.",code=AttributeErrorCode.INVALID.value,)if errors:@@ -280,6 +289,22 @@ class AttributeCreate(AttributeMixin, ModelMutation):error_type_class = AttributeErrorerror_type_field = "attribute_errors"+ @classmethod+ def clean_input(cls, info, instance, data, input_cls=None):+ cleaned_input = super().clean_input(info, instance, data, input_cls)+ if cleaned_input.get(+ "input_type"+ ) == AttributeInputType.REFERENCE and not cleaned_input.get("entity_type"):+ raise ValidationError(+ {+ "entity_type": ValidationError(+ "Entity type is required when REFERENCE input type is used.",+ code=AttributeErrorCode.REQUIRED.value,+ )+ }+ )+ return cleaned_input+@classmethoddef perform_mutation(cls, _root, info, **data):input = data.get("input")diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.pyindex 0b760581b1..5603f74133 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py@@ -3,7 +3,7 @@ from django.utils.text import slugifyfrom .....attribute.error_codes import AttributeErrorCodefrom ....tests.utils import get_graphql_content-from ...enums import AttributeInputTypeEnum, AttributeTypeEnum+from ...enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnumCREATE_ATTRIBUTE_MUTATION = """mutation createAttribute(@@ -20,6 +20,7 @@ CREATE_ATTRIBUTE_MUTATION = """slugtypeinputType+ entityTypefilterableInStorefrontfilterableInDashboardavailableInGrid@@ -137,6 +138,93 @@ def test_create_attribute_with_file_input_type(assert data["attribute"]["inputType"] == AttributeInputTypeEnum.FILE.name+def test_create_attribute_with_reference_input_type(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.REFERENCE.name,+ "entityType": AttributeEntityTypeEnum.PAGE.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["attributeCreate"]["attributeErrors"]+ data = content["data"]["attributeCreate"]++ # Check if the attribute was correctly created+ assert data["attribute"]["name"] == attribute_name+ assert data["attribute"]["slug"] == slugify(+ attribute_name+ ), "The default slug should be the slugified name"+ assert (+ data["attribute"]["productTypes"]["edges"] == []+ ), "The attribute should not have been assigned to a product type"++ # Check if the attribute values were correctly created+ assert len(data["attribute"]["values"]) == 0+ assert data["attribute"]["type"] == AttributeTypeEnum.PRODUCT_TYPE.name+ assert data["attribute"]["inputType"] == AttributeInputTypeEnum.REFERENCE.name+ assert data["attribute"]["entityType"] == AttributeEntityTypeEnum.PAGE.name+++def test_create_attribute_with_reference_input_type_entity_type_not_given(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.REFERENCE.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ errors = data["attributeErrors"]++ assert not data["attribute"]+ assert len(errors) == 1+ assert errors[0]["field"] == "entityType"+ assert errors[0]["code"] == AttributeErrorCode.REQUIRED.name++def test_create_page_attribute_and_attribute_values(staff_api_client,permission_manage_page_types_and_attributes,@@ -328,6 +416,54 @@ def test_create_attribute_with_file_input_type_and_invalid_settings(assert {error["code"] for error in errors} == {AttributeErrorCode.INVALID.name}+def test_create_attribute_with_reference_input_type_invalid_settings(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.REFERENCE.name,+ "entityType": AttributeEntityTypeEnum.PAGE.name,+ "filterableInStorefront": True,+ "filterableInDashboard": True,+ "availableInGrid": True,+ "storefrontSearchPosition": 1,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ errors = data["attributeErrors"]++ assert not data["attribute"]+ assert len(errors) == 4+ assert {error["field"] for error in errors} == {+ "filterableInStorefront",+ "filterableInDashboard",+ "availableInGrid",+ "storefrontSearchPosition",+ }+ assert {error["code"] for error in errors} == {AttributeErrorCode.INVALID.name}++@pytest.mark.parametrize("field, value",[@@ -378,6 +514,97 @@ def test_create_attribute_with_file_input_type_and_invalid_one_settings_value(assert errors[0]["code"] == AttributeErrorCode.INVALID.name+ "field, value",+ [+ ("filterableInStorefront", True),+ ("filterableInDashboard", True),+ ("availableInGrid", True),+ ("storefrontSearchPosition", 4),+ ],+)+def test_create_attribute_with_reference_input_type_invalid_one_settings_value(+ field,+ value,+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.REFERENCE.name,+ "entityType": AttributeEntityTypeEnum.PAGE.name,+ field: value,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ errors = data["attributeErrors"]++ assert not data["attribute"]+ assert len(errors) == 1+ assert errors[0]["field"] == field+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name+++def test_create_attribute_with_reference_input_type_values_given(+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+):+ # given+ query = CREATE_ATTRIBUTE_MUTATION++ attribute_name = "Example name"+ variables = {+ "input": {+ "name": attribute_name,+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ "inputType": AttributeInputTypeEnum.REFERENCE.name,+ "entityType": AttributeEntityTypeEnum.PAGE.name,+ "values": [{"name": "test-value"}],+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ errors = data["attributeErrors"]++ assert not data["attribute"]+ assert len(errors) == 1+ assert errors[0]["field"] == "values"+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name++@pytest.mark.parametrize("input_slug, expected_slug",(diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.pyindex 3ded69852a..7421e4b3e2 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py@@ -65,6 +65,7 @@ query($id: ID!) {slugnameinputType+ entityTypetypevalues {slug@@ -249,6 +250,51 @@ def test_get_single_product_attribute_with_file_value(assert data in attribute_data["values"]+def test_get_single_reference_attribute_by_staff(+ staff_api_client, page_reference_attribute, permission_manage_products+):+ staff_api_client.user.user_permissions.add(permission_manage_products)+ attribute_gql_id = graphene.Node.to_global_id(+ "Attribute", page_reference_attribute.id+ )+ query = QUERY_ATTRIBUTE+ content = get_graphql_content(+ staff_api_client.post_graphql(query, {"id": attribute_gql_id})+ )++ assert content["data"]["attribute"], "Should have found an attribute"+ assert content["data"]["attribute"]["id"] == attribute_gql_id+ assert content["data"]["attribute"]["slug"] == page_reference_attribute.slug+ assert (+ content["data"]["attribute"]["valueRequired"]+ == page_reference_attribute.value_required+ )+ assert (+ content["data"]["attribute"]["visibleInStorefront"]+ == page_reference_attribute.visible_in_storefront+ )+ assert (+ content["data"]["attribute"]["filterableInStorefront"]+ == page_reference_attribute.filterable_in_storefront+ )+ assert (+ content["data"]["attribute"]["filterableInDashboard"]+ == page_reference_attribute.filterable_in_dashboard+ )+ assert (+ content["data"]["attribute"]["availableInGrid"]+ == page_reference_attribute.available_in_grid+ )+ assert (+ content["data"]["attribute"]["storefrontSearchPosition"]+ == page_reference_attribute.storefront_search_position+ )+ assert (+ content["data"]["attribute"]["entityType"]+ == page_reference_attribute.entity_type.upper()+ )++QUERY_ATTRIBUTES = """query {attributes(first: 20) {diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex 4aadf57486..6ca1f1d89c 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -14,7 +14,12 @@ from ..translations.fields import TranslationFieldfrom ..translations.types import AttributeTranslation, AttributeValueTranslationfrom .dataloaders import AttributeValuesByAttributeIdLoaderfrom .descriptions import AttributeDescriptions, AttributeValueDescriptions-from .enums import AttributeInputTypeEnum, AttributeTypeEnum, AttributeValueType+from .enums import (+ AttributeEntityTypeEnum,+ AttributeInputTypeEnum,+ AttributeTypeEnum,+ AttributeValueType,+)COLOR_PATTERN = r"^(#[0-9a-fA-F]{3}|#(?:[0-9a-fA-F]{2}){2,4}|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))$" # noqacolor_pattern = re.compile(COLOR_PATTERN)@@ -72,6 +77,9 @@ class AttributeValue(CountableDjangoObjectType):class Attribute(CountableDjangoObjectType):input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)+ entity_type = AttributeEntityTypeEnum(+ description=AttributeDescriptions.ENTITY_TYPE, required=False+ )name = graphene.String(description=AttributeDescriptions.NAME)slug = graphene.String(description=AttributeDescriptions.SLUG)diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 2faf1c6dc8..8d9a23ff0e 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -2262,7 +2262,6 @@ def test_create_product_with_file_attribute(file_attribute,color_attribute,permission_manage_products,- settings,):query = CREATE_PRODUCT_MUTATION@@ -2327,7 +2326,6 @@ def test_create_product_with_file_attribute_new_attribute_value(file_attribute,color_attribute,permission_manage_products,- settings,):query = CREATE_PRODUCT_MUTATION@@ -2395,7 +2393,6 @@ def test_create_product_with_file_attribute_not_required_no_file_url_given(file_attribute,color_attribute,permission_manage_products,- settings,):query = CREATE_PRODUCT_MUTATION@@ -2448,9 +2445,7 @@ def test_create_product_with_file_attribute_required_no_file_url_given(product_type,category,file_attribute,- color_attribute,permission_manage_products,- settings,):query = CREATE_PRODUCT_MUTATION@@ -4022,6 +4017,7 @@ def test_product_type_query_only_variant_selections_value_set(product_type,file_attribute_with_file_input_type_without_values,author_page_attribute,+ page_reference_attribute,product,permission_manage_products,monkeypatch,@@ -4040,7 +4036,9 @@ def test_product_type_query_only_variant_selections_value_set()product_type.variant_attributes.add(- file_attribute_with_file_input_type_without_values, author_page_attribute+ file_attribute_with_file_input_type_without_values,+ author_page_attribute,+ page_reference_attribute,)variables = {diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 0939b68bf5..c61a2c7421 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -393,6 +393,7 @@ type Attribute implements Node & ObjectWithMetadata {privateMetadata: [MetadataItem]!metadata: [MetadataItem]!inputType: AttributeInputTypeEnum+ entityType: AttributeEntityTypeEnumname: Stringslug: Stringtype: AttributeTypeEnum@@ -431,6 +432,7 @@ type AttributeCreate {input AttributeCreateInput {inputType: AttributeInputTypeEnum+ entityType: AttributeEntityTypeEnumname: String!slug: Stringtype: AttributeTypeEnum!@@ -450,6 +452,10 @@ type AttributeDelete {attribute: Attribute}+enum AttributeEntityTypeEnum {+ PAGE+}+type AttributeError {field: Stringmessage: String@@ -490,6 +496,7 @@ enum AttributeInputTypeEnum {DROPDOWNMULTISELECTFILE+ REFERENCE}type AttributeReorderValues {diff --git a/saleor/product/tests/test_get_variant_selection_attributes.py b/saleor/product/tests/test_get_variant_selection_attributes.pyindex 9951287593..28fda8d01e 100644--- a/saleor/product/tests/test_get_variant_selection_attributes.py+++ b/saleor/product/tests/test_get_variant_selection_attributes.py@@ -3,7 +3,9 @@ from ..utils.variants import get_variant_selection_attributesdef test_get_variant_selection_attributes(- product_type_attribute_list, file_attribute_with_file_input_type_without_values+ product_type_attribute_list,+ file_attribute_with_file_input_type_without_values,+ page_reference_attribute,):# givenmultiselect_attr = product_type_attribute_list[0]@@ -11,7 +13,8 @@ def test_get_variant_selection_attributes(multiselect_attr.save(update_fields=["input_type"])attrs = product_type_attribute_list + [- file_attribute_with_file_input_type_without_values+ file_attribute_with_file_input_type_without_values,+ page_reference_attribute,]# whendiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 3b8835b7c0..48b968e614 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -26,7 +26,7 @@ from prices import Money, TaxedMoneyfrom ..account.models import Address, StaffNotificationRecipient, Userfrom ..app.models import App, AppInstallationfrom ..app.types import AppType-from ..attribute import AttributeInputType, AttributeType+from ..attribute import AttributeEntityType, AttributeInputType, AttributeTypefrom ..attribute.models import (Attribute,AttributeTranslation,@@ -822,6 +822,17 @@ def file_attribute_with_file_input_type_without_values(db):)+def page_reference_attribute(db):+ return Attribute.objects.create(+ slug="page-reference",+ name="Page reference",+ type=AttributeType.PRODUCT_TYPE,+ input_type=AttributeInputType.REFERENCE,+ entity_type=AttributeEntityType.PAGE,+ )++@pytest.fixturedef size_page_attribute(db):attribute = Attribute.objects.create(