Skip to content

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

Sort attribute values during assignment

IKarbowiak2cce8c40af32
diff --git a/saleor/attribute/tests/test_utils.py b/saleor/attribute/tests/test_utils.py
index 37a06a7c60..0e90cc130e 100644
--- a/saleor/attribute/tests/test_utils.py
+++ b/saleor/attribute/tests/test_utils.py
@@ -45,3 +45,64 @@ def test_associate_attribute_to_product_instance_without_values(product):
# Ensure the values were cleared and no new assignment entry was created
assert new_assignment.pk == old_assignment.pk
assert new_assignment.values.count() == 0
+
+
+def test_associate_attribute_to_product_instance_multiply_values(product):
+ """Ensure multiply values in proper order are assigned."""
+ old_assignment = product.attributes.first()
+ assert old_assignment is not None, "The product doesn't have attribute-values"
+ assert old_assignment.values.count() == 1
+
+ attribute = old_assignment.attribute
+ values = attribute.values.all()
+
+ # Assign new values
+ new_assignment = associate_attribute_values_to_instance(
+ product, attribute, values[1], values[0]
+ )
+
+ # Ensure the new assignment was created and ordered correctly
+ assert new_assignment.pk == old_assignment.pk
+ assert new_assignment.values.count() == 2
+ assert list(
+ new_assignment.productvalueassignment.values_list("value__pk", "sort_order")
+ ) == [(values[1].pk, 0), (values[0].pk, 1)]
+
+
+def test_associate_attribute_to_page_instance_multiply_values(page):
+ """Ensure multiply values in proper order are assigned."""
+ old_assignment = page.attributes.first()
+ assert old_assignment is not None, "The page doesn't have attribute-values"
+ assert old_assignment.values.count() == 1
+
+ attribute = old_assignment.attribute
+ values = attribute.values.all()
+
+ # Clear the values
+ new_assignment = associate_attribute_values_to_instance(
+ page, attribute, values[1], values[0]
+ )
+
+ # Ensure the new assignment was created and ordered correctly
+ assert new_assignment.pk == old_assignment.pk
+ assert new_assignment.values.count() == 2
+ assert list(
+ new_assignment.pagevalueassignment.values_list("value__pk", "sort_order")
+ ) == [(values[1].pk, 0), (values[0].pk, 1)]
+
+
+def test_associate_attribute_to_variant_instance_multiply_values(variant):
+ """Ensure multiply values in proper order are assigned."""
+
+ attribute = variant.product.product_type.variant_attributes.first()
+ values = attribute.values.all()
+
+ new_assignment = associate_attribute_values_to_instance(
+ variant, attribute, values[0], values[1]
+ )
+
+ # Ensure the new assignment was created and ordered correctly
+ assert new_assignment.values.count() == 2
+ assert list(
+ new_assignment.variantvalueassignment.values_list("value__pk", "sort_order")
+ ) == [(values[0].pk, 0), (values[1].pk, 1)]
diff --git a/saleor/attribute/utils.py b/saleor/attribute/utils.py
index f59c648caa..22a701850b 100644
--- a/saleor/attribute/utils.py
+++ b/saleor/attribute/utils.py
@@ -1,11 +1,14 @@
-from typing import TYPE_CHECKING, Set, Union
+from typing import TYPE_CHECKING, Iterable, Set, Union
from ..page.models import Page
from ..product.models import Product, ProductVariant
from .models import (
AssignedPageAttribute,
+ AssignedPageAttributeValue,
AssignedProductAttribute,
+ AssignedProductAttributeValue,
AssignedVariantAttribute,
+ AssignedVariantAttributeValue,
Attribute,
AttributeValue,
)
@@ -13,14 +16,50 @@ from .models import (
AttributeAssignmentType = Union[
AssignedProductAttribute, AssignedVariantAttribute, AssignedPageAttribute
]
+T_INSTANCE = Union[Product, ProductVariant, Page]
if TYPE_CHECKING:
from .models import AttributePage, AttributeProduct, AttributeVariant
+def associate_attribute_values_to_instance(
+ instance: T_INSTANCE,
+ attribute: Attribute,
+ *values: AttributeValue,
+) -> AttributeAssignmentType:
+ """Assign given attribute values to a product or variant.
+
+ Note: be award this function invokes the ``set`` method on the instance's
+ attribute association. Meaning any values already assigned or concurrently
+ assigned will be overridden by this call.
+ """
+ values_ids = {value.pk for value in values}
+
+ # Ensure the values are actually form the given attribute
+ validate_attribute_owns_values(attribute, values_ids)
+
+ # Associate the attribute and the passed values
+ assignment = _associate_attribute_to_instance(instance, attribute.pk)
+ assignment.values.set(values)
+ sort_assigned_attribute_values(instance, assignment, values)
+
+ return assignment
+
+
+def validate_attribute_owns_values(attribute: Attribute, value_ids: Set[int]) -> None:
+ """Check given value IDs are belonging to the given attribute.
+
+ :raise: AssertionError
+ """
+ attribute_actual_value_ids = set(attribute.values.values_list("pk", flat=True))
+ found_associated_ids = attribute_actual_value_ids & value_ids
+ if found_associated_ids != value_ids:
+ raise AssertionError("Some values are not from the provided attribute.")
+
+
def _associate_attribute_to_instance(
- instance: Union[Product, ProductVariant, Page], attribute_pk: int
+ instance: T_INSTANCE, attribute_pk: int
) -> AttributeAssignmentType:
"""Associate a given attribute to an instance."""
assignment: AttributeAssignmentType
@@ -51,34 +90,28 @@ def _associate_attribute_to_instance(
return assignment
-def validate_attribute_owns_values(attribute: Attribute, value_ids: Set[int]) -> None:
- """Check given value IDs are belonging to the given attribute.
-
- :raise: AssertionError
- """
- attribute_actual_value_ids = set(attribute.values.values_list("pk", flat=True))
- found_associated_ids = attribute_actual_value_ids & value_ids
- if found_associated_ids != value_ids:
- raise AssertionError("Some values are not from the provided attribute.")
-
-
-def associate_attribute_values_to_instance(
- instance: Union[Product, ProductVariant, Page],
- attribute: Attribute,
- *values: AttributeValue,
-) -> AttributeAssignmentType:
- """Assign given attribute values to a product or variant.
-
- Note: be award this function invokes the ``set`` method on the instance's
- attribute association. Meaning any values already assigned or concurrently
- assigned will be overridden by this call.
- """
- values_ids = {value.pk for value in values}
-
- # Ensure the values are actually form the given attribute
- validate_attribute_owns_values(attribute, values_ids)
-
- # Associate the attribute and the passed values
- assignment = _associate_attribute_to_instance(instance, attribute.pk)
- assignment.values.set(values)
- return assignment
+def sort_assigned_attribute_values(
+ instance: T_INSTANCE,
+ assignment: AttributeAssignmentType,
+ values: Iterable[AttributeValue],
+) -> None:
+ """Sort assigned attribute values based on values list order."""
+
+ instance_to_value_assignment_mapping = {
+ "Product": ("productvalueassignment", AssignedProductAttributeValue),
+ "ProductVariant": ("variantvalueassignment", AssignedVariantAttributeValue),
+ "Page": ("pagevalueassignment", AssignedPageAttributeValue),
+ }
+ assignment_lookup, assignment_model = instance_to_value_assignment_mapping[
+ instance.__class__.__name__
+ ]
+ values_pks = [value.pk for value in values]
+
+ values_assignment = list(
+ getattr(assignment, assignment_lookup).select_related("value")
+ )
+ values_assignment.sort(key=lambda e: values_pks.index(e.value.pk))
+ for index, value_assignment in enumerate(values_assignment):
+ value_assignment.sort_order = index
+
+ assignment_model.objects.bulk_update(values_assignment, ["sort_order"])
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index e4f424a2ad..086e02bc04 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -2480,6 +2480,80 @@ def test_create_product_with_product_reference_attribute(
assert product_type_product_reference_attribute.values.count() == values_count + 1
+def test_create_product_with_product_reference_attribute_values_saved_in_order(
+ staff_api_client,
+ product_type,
+ category,
+ color_attribute,
+ product_type_product_reference_attribute,
+ permission_manage_products,
+ product_list,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ values_count = product_type_product_reference_attribute.values.count()
+
+ 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"
+
+ # Add second attribute
+ product_type.product_attributes.set([product_type_product_reference_attribute])
+ reference_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ reference_1 = graphene.Node.to_global_id("Product", product_list[0].pk)
+ reference_2 = graphene.Node.to_global_id("Product", product_list[1].pk)
+ reference_3 = graphene.Node.to_global_id("Product", product_list[2].pk)
+
+ # test creating root product
+ reference_ids = [reference_3, reference_1, reference_2]
+ reference_instances = [product_list[2], product_list[0], product_list[1]]
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": reference_attr_id, "references": reference_ids}],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert data["productErrors"] == []
+ assert data["product"]["name"] == product_name
+ assert data["product"]["slug"] == product_slug
+ assert data["product"]["productType"]["name"] == product_type.name
+ assert data["product"]["category"]["name"] == category.name
+ _, product_id = graphene.Node.from_global_id(data["product"]["id"])
+ expected_values = [
+ {
+ "slug": f"{product_id}_{product.id}",
+ "name": product.name,
+ "file": None,
+ "reference": reference,
+ }
+ for product, reference in zip(reference_instances, reference_ids)
+ ]
+
+ assert len(data["product"]["attributes"]) == 1
+ attribute_data = data["product"]["attributes"][0]
+ assert (
+ attribute_data["attribute"]["slug"]
+ == product_type_product_reference_attribute.slug
+ )
+ assert len(attribute_data["values"]) == 3
+ assert attribute_data["values"] == expected_values
+
+ product_type_product_reference_attribute.refresh_from_db()
+ assert product_type_product_reference_attribute.values.count() == values_count + 3
+
+
def test_create_product_with_file_attribute_new_attribute_value(
staff_api_client,
product_type,