Skip to content

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

Fix export with empty assignment values (#7207)

Iga Karbowiak96bf7ec5bfd2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e37065caa..f5f9423ce4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -61,6 +61,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix core sorting on related fields - #7195 by @tomaszszymanski129
- Performance upgrade on orders query with `actions` field - #7175 by @tomaszszymanski129
- Performance upgrade on orders query with `totalAuthorized` field - #7170 by @tomaszszymanski129
+- Fix export with empty assignment values - #7207 by @IKarbowiak
### Breaking
- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki
diff --git a/saleor/attribute/migrations/0009_auto_20210421_0552.py b/saleor/attribute/migrations/0009_auto_20210421_0552.py
new file mode 100644
index 0000000000..aead95c2ec
--- /dev/null
+++ b/saleor/attribute/migrations/0009_auto_20210421_0552.py
@@ -0,0 +1,30 @@
+# Generated by Django 3.1.8 on 2021-04-21 05:52
+
+from django.db import migrations
+
+
+def clear_assignment_instances_without_values(apps, schema_editor):
+ AssignedProductAttribute = apps.get_model("attribute", "AssignedProductAttribute")
+ AssignedVariantAttribute = apps.get_model("attribute", "AssignedVariantAttribute")
+ AssignedPageAttribute = apps.get_model("attribute", "AssignedPageAttribute")
+
+ for model in [
+ AssignedProductAttribute,
+ AssignedVariantAttribute,
+ AssignedPageAttribute,
+ ]:
+ model.objects.filter(values__isnull=True).delete()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0008_auto_20210407_0632"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ clear_assignment_instances_without_values,
+ migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.py
index 6290335362..7248bcb6dd 100644
--- a/saleor/csv/tests/export/products_data/test_get_products_data.py
+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py
@@ -237,6 +237,7 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product_with_image,
product_with_variant_with_two_attributes,
rich_text_attribute,
+ color_attribute,
variant_with_many_stocks,
):
# given
@@ -315,6 +316,13 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product, product_type_product_reference_attribute, product_product_ref_value
)
+ # create assigned product without values
+ associate_attribute_values_to_instance(
+ product, color_attribute, color_attribute.values.first()
+ )
+ assigned_product = product.attributes.get(assignment__attribute=color_attribute)
+ assigned_product.values.clear()
+
products = Product.objects.all()
export_fields = {"id", "variants__sku"}
warehouse_ids = [str(warehouse.pk) for warehouse in Warehouse.objects.all()]
diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
index 9bd354e192..aa3e64a77a 100644
--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py
+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
@@ -985,6 +985,80 @@ def test_add_reference_info_to_data_update_attribute_data(product, page):
assert result[pk][expected_header] == values
+def test_add_attribute_info_to_data_no_file_url_for_file_attribute(product):
+ # given
+ pk = product.pk
+ slug = "test_attribute_slug"
+ value = "test value"
+ attribute_data = AttributeData(
+ slug=slug,
+ value=value,
+ file_url=None,
+ input_type="file",
+ entity_type=None,
+ rich_text=None,
+ )
+ input_data = {pk: {}}
+
+ # when
+ result = add_attribute_info_to_data(
+ product.pk, attribute_data, "product attribute", input_data
+ )
+
+ # then
+ expected_header = f"{slug} (product attribute)"
+ assert result[pk][expected_header] == {""}
+
+
+def test_add_attribute_info_to_data_no_rich_text_for_rich_text_attribute(product):
+ # given
+ pk = product.pk
+ slug = "test_attribute_slug"
+ value = "test value"
+ attribute_data = AttributeData(
+ slug=slug,
+ value=value,
+ file_url=None,
+ input_type="rich-text",
+ entity_type=None,
+ rich_text=None,
+ )
+ input_data = {pk: {}}
+
+ # when
+ result = add_attribute_info_to_data(
+ product.pk, attribute_data, "product attribute", input_data
+ )
+
+ # then
+ expected_header = f"{slug} (product attribute)"
+ assert result[pk][expected_header] == {""}
+
+
+def test_add_attribute_info_to_data_no_value_for_reference_attribute(product):
+ # given
+ pk = product.pk
+ slug = "test_attribute_slug"
+ attribute_data = AttributeData(
+ slug=slug,
+ value=None,
+ file_url=None,
+ input_type="reference",
+ entity_type=None,
+ rich_text=None,
+ )
+ input_data = {pk: {}}
+
+ # when
+ result = add_attribute_info_to_data(
+ product.pk, attribute_data, "product attribute", input_data
+ )
+
+ # then
+ expected_header = f"{slug} (product attribute)"
+ assert result[pk][expected_header] == {""}
+
+
def test_add_warehouse_info_to_data(product):
# given
pk = product.pk
diff --git a/saleor/csv/tests/export/products_data/test_prepare_headers.py b/saleor/csv/tests/export/products_data/test_prepare_headers.py
index 22ea03f0c6..0d18ea39e4 100644
--- a/saleor/csv/tests/export/products_data/test_prepare_headers.py
+++ b/saleor/csv/tests/export/products_data/test_prepare_headers.py
@@ -43,11 +43,17 @@ def test_get_export_fields_and_headers_no_fields():
assert file_headers == ["id"]
-def test_get_attributes_headers(product_with_multiple_values_attributes):
+def test_get_attributes_headers(
+ product_with_multiple_values_attributes, product_type_without_variant
+):
# given
attribute_ids = Attribute.objects.values_list("id", flat=True)
export_info = {"attributes": attribute_ids}
+ product_type = product_with_multiple_values_attributes.product_type
+ product_attribute = product_type.product_attributes.first()
+ product_type_without_variant.product_attributes.add(product_attribute)
+
# when
attributes_headers = get_attributes_headers(export_info)
diff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.py
index 7b65e5c6cb..b8f72f9387 100644
--- a/saleor/csv/tests/export/products_data/utils.py
+++ b/saleor/csv/tests/export/products_data/utils.py
@@ -30,6 +30,8 @@ def add_variant_attribute_data_to_expected_data(data, variant, attribute_ids, pk
def get_attribute_value(assigned_attribute):
value_instance = assigned_attribute.values.first()
+ if not value_instance:
+ return ""
attribute = assigned_attribute.attribute
if attribute.input_type == AttributeInputType.FILE:
value = value_instance.file_url
diff --git a/saleor/csv/utils/product_headers.py b/saleor/csv/utils/product_headers.py
index 370fdf2365..99f4bf9670 100644
--- a/saleor/csv/utils/product_headers.py
+++ b/saleor/csv/utils/product_headers.py
@@ -78,12 +78,14 @@ def get_attributes_headers(export_info: Dict[str, list]) -> List[str]:
products_headers = (
attributes.filter(product_types__isnull=False)
+ .distinct()
.annotate(header=Concat("slug", V(" (product attribute)")))
.values_list("header", flat=True)
)
variant_headers = (
attributes.filter(product_variant_types__isnull=False)
+ .distinct()
.annotate(header=Concat("slug", V(" (variant attribute)")))
.values_list("header", flat=True)
)
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index 66d9657e20..23d0dc47ed 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -387,10 +387,13 @@ def add_attribute_info_to_data(
header = f"{slug} ({attribute_owner})"
input_type = attribute_data.input_type
if input_type == AttributeInputType.FILE:
- value = build_absolute_uri(
- urljoin(settings.MEDIA_URL, attribute_data.file_url)
+ file_url = attribute_data.file_url
+ value = (
+ build_absolute_uri(urljoin(settings.MEDIA_URL, file_url))
+ if file_url
+ else ""
)
- elif input_type == AttributeInputType.REFERENCE:
+ elif input_type == AttributeInputType.REFERENCE and attribute_data.value:
reference_id = attribute_data.value.split("_")[1]
value = f"{attribute_data.entity_type}_{reference_id}"
elif input_type == AttributeInputType.RICH_TEXT:
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index f6a10fcbe5..81cde8801c 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -398,6 +398,7 @@ class AttributeAssignmentMixin:
:param instance: the product or variant to associate the attribute against.
:param cleaned_input: the cleaned user input (refer to clean_attributes)
"""
+ clean_assignment = []
for attribute, attr_values in cleaned_input:
if attribute.input_type == AttributeInputType.FILE:
attribute_values = cls._pre_save_file_value(
@@ -417,6 +418,14 @@ class AttributeAssignmentMixin:
associate_attribute_values_to_instance(
instance, attribute, *attribute_values
)
+ if not attribute_values:
+ clean_assignment.append(attribute.pk)
+
+ # drop attribute assignment model when values are unassigned from instance
+ if clean_assignment:
+ instance.attributes.filter(
+ assignment__attribute_id__in=clean_assignment
+ ).delete()
def get_variant_selection_attributes(qs: "QuerySet"):
diff --git a/saleor/graphql/csv/enums.py b/saleor/graphql/csv/enums.py
index fddce3203a..216b4ddad5 100644
--- a/saleor/graphql/csv/enums.py
+++ b/saleor/graphql/csv/enums.py
@@ -30,7 +30,6 @@ class ProductFieldEnum(graphene.Enum):
DESCRIPTION = "description"
PRODUCT_TYPE = "product type"
CATEGORY = "category"
- VISIBLE = "visible"
PRODUCT_WEIGHT = "product weight"
COLLECTIONS = "collections"
CHARGE_TAXES = "charge taxes"
diff --git a/saleor/graphql/page/tests/test_page.py b/saleor/graphql/page/tests/test_page.py
index 5739b40813..ad8099b50b 100644
--- a/saleor/graphql/page/tests/test_page.py
+++ b/saleor/graphql/page/tests/test_page.py
@@ -1312,6 +1312,41 @@ def test_update_page_with_file_attribute_new_value_is_not_created(
assert updated_attribute in data["page"]["attributes"]
+def test_update_page_clear_values(staff_api_client, permission_manage_pages, page):
+ # given
+ query = UPDATE_PAGE_MUTATION
+
+ page_attr = page.attributes.first()
+ attribute = page_attr.assignment.attribute
+ attribute.value_required = False
+ attribute.save(update_fields=["value_required"])
+
+ page_file_attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+
+ variables = {
+ "id": page_id,
+ "input": {"attributes": [{"id": page_file_attribute_id, "file": ""}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageUpdate"]
+
+ assert not data["pageErrors"]
+ assert data["page"]
+ assert not data["page"]["attributes"][0]["values"]
+
+ with pytest.raises(page_attr._meta.model.DoesNotExist):
+ page_attr.refresh_from_db()
+
+
def test_update_page_with_page_reference_attribute_new_value(
staff_api_client,
permission_manage_pages,
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index aade8cd8a2..213a806a51 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -4675,6 +4675,51 @@ def test_update_product_with_file_attribute_value_new_value_is_not_created(
updated_webhook_mock.assert_called_once_with(product)
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product_clear_attribute_values(
+ updated_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ permission_manage_products,
+):
+ # given
+ query = MUTATION_UPDATE_PRODUCT
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ product_attr = product.attributes.first()
+ attribute = product_attr.assignment.attribute
+ attribute.value_required = False
+ attribute.save(update_fields=["value_required"])
+
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+
+ variables = {
+ "productId": product_id,
+ "input": {"attributes": [{"id": attribute_id, "values": []}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ assert data["productErrors"] == []
+
+ attributes = data["product"]["attributes"]
+
+ assert len(attributes) == 1
+ assert not attributes[0]["values"]
+ with pytest.raises(product_attr._meta.model.DoesNotExist):
+ product_attr.refresh_from_db()
+
+ updated_webhook_mock.assert_called_once_with(product)
+
+
@freeze_time("2020-03-18 12:00:00")
def test_update_product_rating(
staff_api_client,
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 466ee2facc..37abc79304 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -1571,6 +1571,47 @@ def test_update_product_variant_with_new_attribute(
assert variant.attributes.last().values.first().slug == "big"
+def test_update_product_variant_clear_attributes(
+ staff_api_client,
+ product,
+ permission_manage_products,
+):
+ variant = product.variants.first()
+ sku = str(uuid4())[:12]
+ assert not variant.sku == sku
+
+ variant_attr = variant.attributes.first()
+ attribute = variant_attr.assignment.attribute
+ attribute.input_type = AttributeInputType.MULTISELECT
+ attribute.value_required = False
+ attribute.save(update_fields=["value_required", "input_type"])
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+
+ variables = {
+ "id": variant_id,
+ "sku": sku,
+ "attributes": [
+ {"id": attribute_id, "values": []},
+ ],
+ }
+
+ response = staff_api_client.post_graphql(
+ QUERY_UPDATE_VARIANT_ATTRIBUTES,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ data = content["data"]["productVariantUpdate"]
+ assert not data["errors"]
+ variant.refresh_from_db()
+ assert not data["productVariant"]["attributes"][0]["values"]
+ with pytest.raises(variant_attr._meta.model.DoesNotExist):
+ variant_attr.refresh_from_db()
+
+
def test_update_product_variant_with_duplicated_attribute(
staff_api_client,
product_with_variant_with_two_attributes,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 4f6c3977a3..59779e4347 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -4157,7 +4157,6 @@ enum ProductFieldEnum {
DESCRIPTION
PRODUCT_TYPE
CATEGORY
- VISIBLE
PRODUCT_WEIGHT
COLLECTIONS
CHARGE_TAXES