Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove attribute file when it is not longer used (#7405)
Iga Karbowiak77c26af427d9
diff --git a/.isort.cfg b/.isort.cfgindex 1cdc05d770..418c8cf5f1 100644--- a/.isort.cfg+++ b/.isort.cfg@@ -1,2 +1,2 @@[settings]-known_third_party = Adyen,PIL,authorizenet,babel,boto3,braintree,celery,dateutil,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html2text,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,micawber,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pybars,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sendgrid,sentry_sdk,storages,stripe,tqdm,urllib3,versatileimagefield,weasyprint+known_third_party = Adyen,PIL,authorizenet,babel,boto3,botocore,braintree,celery,dateutil,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html2text,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,micawber,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pybars,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sendgrid,sentry_sdk,storages,stripe,tqdm,urllib3,versatileimagefield,weasyprintdiff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.pyindex 8916e83d91..484b9cccd6 100644--- a/saleor/attribute/__init__.py+++ b/saleor/attribute/__init__.py@@ -27,6 +27,14 @@ class AttributeInputType:MULTISELECT,]+ # list of the input types that are unique per instances+ TYPES_WITH_UNIQUE_VALUES = [+ FILE,+ REFERENCE,+ RICH_TEXT,+ NUMERIC,+ ]+# list of input types that are allowed for given attribute propertyATTRIBUTE_PROPERTIES_CONFIGURATION = {diff --git a/saleor/attribute/management/__init__.py b/saleor/attribute/management/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/attribute/management/commands/__init__.py b/saleor/attribute/management/commands/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/attribute/management/commands/update_attribute_file_urls.py b/saleor/attribute/management/commands/update_attribute_file_urls.pynew file mode 100644index 0000000000..add3ae2570--- /dev/null+++ b/saleor/attribute/management/commands/update_attribute_file_urls.py@@ -0,0 +1,55 @@+import logging+import re+from urllib.parse import urlparse++from botocore.exceptions import ClientError+from django.conf import settings+from django.core.management.base import BaseCommand, CommandError++from ....core.storages import S3MediaStorage+from ...models import AttributeValue++logger = logging.getLogger(__name__)+++class Command(BaseCommand):+ help = "Move all attributes file to `file_upload` directory on s3 storage."++ def handle(self, *args, **options):+ storage = S3MediaStorage()++ if not storage.bucket_name:+ raise CommandError("No s3 bucket detected.")++ values = AttributeValue.objects.filter(file_url__isnull=False)+ directory = "file_upload"+ for value in values:+ file_url = value.file_url+ if not file_url or file_url.startswith(directory):+ continue+ file_name = re.sub(f"^{settings.MEDIA_URL}", "", urlparse(file_url).path)+ new_file_name = storage._clean_name(fr"{directory}/{file_name}")+ new_file_url = storage._normalize_name(new_file_name)+ old_file_url = storage._normalize_name(storage._clean_name(file_name))+ try:+ storage.bucket.Object(new_file_url).copy_from(+ CopySource={+ "Bucket": storage.bucket_name,+ "Key": old_file_url,+ }+ )+ except ClientError as exc:+ if exc.response["Error"]["Code"] == "NoSuchKey":+ logger.info(f"No object found: {old_file_url}")+ else:+ raise+ else:+ storage.bucket.Object(old_file_url).delete()+ logger.info(f"File {old_file_url} moved to {new_file_url}.")++ value.file_url = new_file_name+ value.save(update_fields=["file_url"])+ logger.info(+ f"File url for AttributeValue {value} with id {value.id} "+ "has been updated."+ )diff --git a/saleor/attribute/migrations/0011_update_values_file_urls.py b/saleor/attribute/migrations/0011_update_values_file_urls.pynew file mode 100644index 0000000000..7b856395f2--- /dev/null+++ b/saleor/attribute/migrations/0011_update_values_file_urls.py@@ -0,0 +1,27 @@+# Generated by Django 3.2.2 on 2021-05-27 08:41+import re+from urllib.parse import urlparse++from django.conf import settings+from django.db import migrations+++def update_file_urls(apps, schema_editor):+ AttributeValue = apps.get_model("attribute", "AttributeValue")+ values = AttributeValue.objects.filter(file_url__isnull=False)+ for value in values.iterator():+ value.file_url = re.sub(+ f"^{settings.MEDIA_URL}", "", urlparse(value.file_url).path+ )+ value.save(update_fields=["file_url"])+++class Migration(migrations.Migration):++ dependencies = [+ ("attribute", "0010_auto_20210412_0736"),+ ]++ operations = [+ migrations.RunPython(update_file_urls, reverse_code=migrations.RunPython.noop),+ ]diff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.pyindex 67e66095a0..db4d5eb277 100644--- a/saleor/csv/tests/export/products_data/utils.py+++ b/saleor/csv/tests/export/products_data/utils.py@@ -34,7 +34,7 @@ def get_attribute_value(assigned_attribute):return ""attribute = assigned_attribute.attributeif attribute.input_type == AttributeInputType.FILE:- value = value_instance.file_url+ value = "http://mirumee.com/media/" + value_instance.file_urlelif attribute.input_type == AttributeInputType.REFERENCE:ref_id = value_instance.slug.split("_")[1]value = f"{attribute.entity_type}_{ref_id}"diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.pyindex db6d74de38..4e33677963 100644--- a/saleor/graphql/attribute/tests/test_utils.py+++ b/saleor/graphql/attribute/tests/test_utils.py@@ -5,7 +5,7 @@ from ....attribute import AttributeInputTypefrom ....page.error_codes import PageErrorCodefrom ....product.error_codes import ProductErrorCodefrom ...product.mutations.products import AttrValuesInput-from ..utils import validate_attributes_input+from ..utils import AttributeAssignmentMixin, validate_attributes_inputdef test_validate_attributes_input_for_product(@@ -1221,3 +1221,19 @@ def test_validate_numeric_attributes_input_for_product_more_than_one_value_givenassert set(error.params["attributes"]) == {graphene.Node.to_global_id("Attribute", numeric_attribute.pk)}+++ "file_url, expected_value",+ [+ ("http://localhost:8000/media/Test.jpg", "Test.jpg"),+ ("/media/Test.jpg", "Test.jpg"),+ ("Test.jpg", "Test.jpg"),+ ("", ""),+ ("/ab/cd.jpg", "/ab/cd.jpg"),+ ],+)+def test_clean_file_url_in_attribute_assignment_mixin(file_url, expected_value):+ result = AttributeAssignmentMixin._clean_file_url(file_url)++ assert result == expected_valuediff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex 3aa78875d6..03a8a948c5 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -1,8 +1,11 @@+import refrom collections import defaultdictfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, Union+from urllib.parse import urlparseimport graphene+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db.models import Qfrom django.template.defaultfilters import truncatechars@@ -335,7 +338,7 @@ class AttributeAssignmentMixin:values = AttrValuesInput(global_id=global_id,values=attribute_input.get("values", []),- file_url=attribute_input.get("file"),+ file_url=cls._clean_file_url(attribute_input.get("file")),content_type=attribute_input.get("content_type"),references=attribute_input.get("references", []),rich_text=attribute_input.get("rich_text"),@@ -395,6 +398,15 @@ class AttributeAssignmentMixin:return cleaned_input+ @staticmethod+ def _clean_file_url(file_url: Optional[str]):+ # extract storage path from file URL+ return (+ re.sub(f"^{settings.MEDIA_URL}", "", urlparse(file_url).path)+ if file_url is not None+ else file_url+ )+@classmethoddef _validate_references(cls, error_class, attribute: attribute_models.Attribute, values: AttrValuesInputdiff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 56c00e4756..e524b84971 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -1,3 +1,5 @@+import os+import secretsfrom itertools import chainfrom typing import Tuple, Union@@ -643,7 +645,13 @@ class FileUpload(BaseMutation):@staff_member_or_app_requireddef perform_mutation(cls, _root, info, **data):file_data = info.context.FILES.get(data["file"])- path = default_storage.save(file_data._name, file_data.file)++ # add unique text fragment to the file name to prevent file overriding+ file_name, format = os.path.splitext(file_data._name)+ hash = secrets.token_hex(nbytes=4)+ new_name = f"file_upload/{file_name}_{hash}{format}"++ path = default_storage.save(new_name, file_data.file)return FileUpload(uploaded_file=File(url=path, content_type=file_data.content_type)diff --git a/saleor/graphql/core/tests/test_file_upload.py b/saleor/graphql/core/tests/test_file_upload.pyindex 8c07b9dec5..cf29e0563a 100644--- a/saleor/graphql/core/tests/test_file_upload.py+++ b/saleor/graphql/core/tests/test_file_upload.py@@ -1,3 +1,6 @@+import os+from urllib.parse import urlparse+from django.core.files.storage import default_storagefrom ....product.tests.utils import create_image@@ -38,11 +41,14 @@ def test_file_upload_by_staff(staff_api_client, site_settings, media_root):data = content["data"]["fileUpload"]errors = data["errors"]- expected_path = "http://testserver/media/" + image_file._nameassert not errorsassert data["uploadedFile"]["contentType"] == "image/png"- assert data["uploadedFile"]["url"] == expected_path- assert default_storage.exists(image_file._name)+ file_name, format = os.path.splitext(image_file._name)+ returned_url = data["uploadedFile"]["url"]+ file_path = urlparse(returned_url).path+ assert file_path.startswith(f"/media/file_upload/{file_name}")+ assert file_path.endswith(format)+ assert default_storage.exists(file_path.lstrip("/media"))def test_file_upload_by_customer(user_api_client, media_root):@@ -76,11 +82,14 @@ def test_file_upload_by_app(app_api_client, media_root):data = content["data"]["fileUpload"]errors = data["errors"]- expected_path = "http://testserver/media/" + image_file._nameassert not errorsassert data["uploadedFile"]["contentType"] == "image/png"- assert data["uploadedFile"]["url"] == expected_path- assert default_storage.exists(image_file._name)+ file_name, format = os.path.splitext(image_file._name)+ returned_url = data["uploadedFile"]["url"]+ file_path = urlparse(returned_url).path+ assert file_path.startswith(f"/media/file_upload/{file_name}")+ assert file_path.endswith(format)+ assert default_storage.exists(file_path.lstrip("/media"))def test_file_upload_by_superuser(superuser_api_client, media_root):@@ -99,11 +108,14 @@ def test_file_upload_by_superuser(superuser_api_client, media_root):data = content["data"]["fileUpload"]errors = data["errors"]- expected_path = "http://testserver/media/" + image_file._nameassert not errorsassert data["uploadedFile"]["contentType"] == "image/png"- assert data["uploadedFile"]["url"] == expected_path- assert default_storage.exists(image_file._name)+ file_name, format = os.path.splitext(image_file._name)+ returned_url = data["uploadedFile"]["url"]+ file_path = urlparse(returned_url).path+ assert file_path.startswith(f"/media/file_upload/{file_name}")+ assert file_path.endswith(format)+ assert default_storage.exists(file_path.lstrip("/media"))def test_file_upload_file_with_the_same_name_already_exists(diff --git a/saleor/graphql/page/mutations/pages.py b/saleor/graphql/page/mutations/pages.pyindex 30e986a581..b5a78d27ff 100644--- a/saleor/graphql/page/mutations/pages.py+++ b/saleor/graphql/page/mutations/pages.py@@ -5,7 +5,8 @@ from typing import TYPE_CHECKING, Dict, Listimport graphenefrom django.core.exceptions import ValidationError-from ....attribute import AttributeType+from ....attribute import AttributeInputType, AttributeType+from ....attribute import models as attribute_modelsfrom ....core.permissions import PagePermissions, PageTypePermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....page import models@@ -14,8 +15,13 @@ from ...attribute.types import AttributeValueInputfrom ...attribute.utils import AttributeAssignmentMixinfrom ...core.mutations import ModelDeleteMutation, ModelMutationfrom ...core.types.common import PageError, SeoInput-from ...core.utils import clean_seo_fields, validate_slug_and_generate_if_needed+from ...core.utils import (+ clean_seo_fields,+ from_global_id_or_error,+ validate_slug_and_generate_if_needed,+)from ...utils.validators import check_for_duplicates+from ..types import PageTypeif TYPE_CHECKING:from ....attribute.models import Attribute@@ -143,12 +149,21 @@ class PageDelete(ModelDeleteMutation):error_type_field = "page_errors"@classmethod+ @traced_atomic_transaction()def perform_mutation(cls, _root, info, **data):page = cls.get_instance(info, **data)+ cls.delete_assigned_attribute_values(page)response = super().perform_mutation(_root, info, **data)info.context.plugins.page_deleted(page)return response+ @staticmethod+ def delete_assigned_attribute_values(instance):+ attribute_models.AttributeValue.objects.filter(+ pageassignments__page_id=instance.id,+ attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ ).delete()+class PageTypeCreateInput(graphene.InputObjectType):name = graphene.String(description="Name of the page type.")@@ -300,3 +315,20 @@ class PageTypeDelete(ModelDeleteMutation):permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)error_type_class = PageErrorerror_type_field = "page_errors"++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info, **data):+ node_id = data.get("id")+ _type, page_type_pk = from_global_id_or_error(+ node_id, only_type=PageType, field="pk"+ )+ cls.delete_assigned_attribute_values(page_type_pk)+ return super().perform_mutation(_root, info, **data)++ @staticmethod+ def delete_assigned_attribute_values(instance_pk):+ attribute_models.AttributeValue.objects.filter(+ attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ pageassignments__assignment__page_type_id=instance_pk,+ ).delete()diff --git a/saleor/graphql/page/tests/test_page.py b/saleor/graphql/page/tests/test_page.pyindex 7118439532..3f54c2c2dd 100644--- a/saleor/graphql/page/tests/test_page.py+++ b/saleor/graphql/page/tests/test_page.py@@ -495,7 +495,10 @@ def test_create_page_with_file_attribute({"slug": f"{attr_value.slug}-2","name": attr_value.name,- "file": {"url": attr_value.file_url, "contentType": None},+ "file": {+ "url": f"http://testserver/media/{attr_value.file_url}",+ "contentType": None,+ },"reference": None,}],@@ -1062,6 +1065,38 @@ def test_page_delete_trigger_webhook()[email protected]("saleor.attribute.signals.delete_from_storage_task.delay")+def test_page_delete_with_file_attribute(+ delete_from_storage_task_mock,+ staff_api_client,+ page,+ permission_manage_pages,+ page_file_attribute,+):+ # given+ page_type = page.page_type+ page_type.page_attributes.add(page_file_attribute)+ existing_value = page_file_attribute.values.first()+ associate_attribute_values_to_instance(page, page_file_attribute, existing_value)++ variables = {"id": graphene.Node.to_global_id("Page", page.id)}++ # when+ response = staff_api_client.post_graphql(+ PAGE_DELETE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageDelete"]+ assert data["page"]["title"] == page.title+ with pytest.raises(page._meta.model.DoesNotExist):+ page.refresh_from_db()+ with pytest.raises(existing_value._meta.model.DoesNotExist):+ existing_value.refresh_from_db()+ delete_from_storage_task_mock.assert_called_once_with(existing_value.file_url)++UPDATE_PAGE_MUTATION = """mutation updatePage($id: ID!, $input: PageInput!@@ -1303,7 +1338,7 @@ def test_update_page_with_file_attribute_new_value_is_not_created("name": existing_value.name,"reference": None,"file": {- "url": existing_value.file_url,+ "url": f"http://testserver/media/{existing_value.file_url}","contentType": existing_value.content_type,},}diff --git a/saleor/graphql/page/tests/test_page_type_delete.py b/saleor/graphql/page/tests/test_page_type_delete.pyindex 74837f9f35..d103828510 100644--- a/saleor/graphql/page/tests/test_page_type_delete.py+++ b/saleor/graphql/page/tests/test_page_type_delete.py@@ -1,6 +1,9 @@+from unittest.mock import patch+import grapheneimport pytest+from ....attribute.utils import associate_attribute_values_to_instancefrom ....page.models import Pagefrom ...tests.utils import assert_no_permission, get_graphql_content@@ -114,3 +117,43 @@ def test_page_type_delete_by_app_no_perm(# thenassert_no_permission(response)+++@patch("saleor.attribute.signals.delete_from_storage_task.delay")+def test_page_type_delete_with_file_attributes(+ delete_from_storage_task_mock,+ staff_api_client,+ page_type,+ page,+ page_file_attribute,+ permission_manage_page_types_and_attributes,+):+ # given+ staff_api_client.user.user_permissions.add(+ permission_manage_page_types_and_attributes+ )+ page_type = page.page_type+ page_type.page_attributes.add(page_file_attribute)++ value = page_file_attribute.values.first()+ associate_attribute_values_to_instance(page, page_file_attribute, value)+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)++ variables = {"id": page_type_id}++ # when+ response = staff_api_client.post_graphql(DELETE_PAGE_TYPE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageTypeDelete"]++ assert not data["errors"]+ assert data["pageType"]["id"] == page_type_id++ with pytest.raises(page_type._meta.model.DoesNotExist):+ page_type.refresh_from_db()+ with pytest.raises(value._meta.model.DoesNotExist):+ value.refresh_from_db()++ delete_from_storage_task_mock.assert_called_once_with(value.file_url)diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.pyindex b7336cc444..dae315734c 100644--- a/saleor/graphql/product/bulk_mutations/products.py+++ b/saleor/graphql/product/bulk_mutations/products.py@@ -3,8 +3,11 @@ from collections import defaultdictimport graphenefrom django.core.exceptions import ValidationErrorfrom django.db import transaction+from django.db.models import Qfrom graphene.types import InputObjectType+from ....attribute import AttributeInputType+from ....attribute import models as attribute_modelsfrom ....core.permissions import ProductPermissions, ProductTypePermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....order import OrderStatus@@ -38,7 +41,7 @@ from ..mutations.products import (ProductVariantInput,StockInput,)-from ..types import Product, ProductVariant+from ..types import Product, ProductType, ProductVariantfrom ..utils import create_stocks, get_used_variants_attribute_values@@ -116,6 +119,7 @@ class ProductBulkDelete(ModelBulkDeleteMutation):).values("pk", "order_id")line_pks = {line["pk"] for line in lines_id_and_orders_id}orders_id = {line["order_id"] for line in lines_id_and_orders_id}+ cls.delete_assigned_attribute_values(pks)response = super().perform_mutation(_root,info,@@ -131,6 +135,13 @@ class ProductBulkDelete(ModelBulkDeleteMutation):return response+ @staticmethod+ def delete_assigned_attribute_values(instance_pks):+ attribute_models.AttributeValue.objects.filter(+ productassignments__product_id__in=instance_pks,+ attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ ).delete()+@classmethoddef bulk_action(cls, info, queryset, product_to_variant):product_variant_map = defaultdict(list)@@ -534,6 +545,7 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):))+ cls.delete_assigned_attribute_values(pks)response = super().perform_mutation(_root, info, ids, **data)transaction.on_commit(@@ -558,6 +570,13 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):return response+ @staticmethod+ def delete_assigned_attribute_values(instance_pks):+ attribute_models.AttributeValue.objects.filter(+ variantassignments__variant_id__in=instance_pks,+ attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ ).delete()+class ProductVariantStocksCreate(BaseMutation):product_variant = graphene.Field(@@ -731,6 +750,23 @@ class ProductTypeBulkDelete(ModelBulkDeleteMutation):error_type_class = ProductErrorerror_type_field = "product_errors"+ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info, ids, **data):+ _, pks = resolve_global_ids_to_primary_keys(ids, ProductType)+ cls.delete_assigned_attribute_values(pks)+ return super().perform_mutation(_root, info, ids, **data)++ @staticmethod+ def delete_assigned_attribute_values(instance_pks):+ attribute_models.AttributeValue.objects.filter(+ Q(attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES)+ & (+ Q(productassignments__assignment__product_type_id__in=instance_pks)+ | Q(variantassignments__assignment__product_type_id__in=instance_pks)+ )+ ).delete()+class ProductMediaBulkDelete(ModelBulkDeleteMutation):class Arguments:diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex d8dffced06..1989ca54f0 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -5,6 +5,7 @@ from typing import List, Tupleimport graphenefrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db import transaction+from django.db.models import Qfrom django.utils.text import slugifyfrom ....attribute import AttributeInputType, AttributeType@@ -699,6 +700,7 @@ class ProductDelete(ModelDeleteMutation):return super().success_response(instance)@classmethod+ @traced_atomic_transaction()def perform_mutation(cls, _root, info, **data):node_id = data.get("id")@@ -710,6 +712,8 @@ class ProductDelete(ModelDeleteMutation):).values("pk", "order_id")line_pks = {line["pk"] for line in lines_id_and_orders_id}orders_id = {line["order_id"] for line in lines_id_and_orders_id}++ cls.delete_assigned_attribute_values(instance)response = super().perform_mutation(_root, info, **data)# delete order lines for deleted variantorder_models.OrderLine.objects.filter(pk__in=line_pks).delete()@@ -719,6 +723,13 @@ class ProductDelete(ModelDeleteMutation):return response+ @staticmethod+ def delete_assigned_attribute_values(instance):+ attribute_models.AttributeValue.objects.filter(+ productassignments__product_id=instance.id,+ attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ ).delete()+class ProductVariantInput(graphene.InputObjectType):attributes = graphene.List(@@ -1025,6 +1036,7 @@ class ProductVariantDelete(ModelDeleteMutation):)).get(id=instance.id)+ cls.delete_assigned_attribute_values(variant)response = super().perform_mutation(_root, info, **data)# delete order lines for deleted variant@@ -1038,6 +1050,13 @@ class ProductVariantDelete(ModelDeleteMutation):return response+ @staticmethod+ def delete_assigned_attribute_values(instance):+ attribute_models.AttributeValue.objects.filter(+ variantassignments__variant_id=instance.id,+ attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ ).delete()+class ProductTypeInput(graphene.InputObjectType):name = graphene.String(description="Name of the product type.")@@ -1184,6 +1203,7 @@ class ProductTypeDelete(ModelDeleteMutation):error_type_field = "product_errors"@classmethod+ @traced_atomic_transaction()def perform_mutation(cls, _root, info, **data):node_id = data.get("id")_type, product_type_pk = from_global_id_or_error(@@ -1198,6 +1218,7 @@ class ProductTypeDelete(ModelDeleteMutation):variant__pk__in=variants_pks, order__status=OrderStatus.DRAFT).values_list("pk", flat=True))+ cls.delete_assigned_attribute_values(product_type_pk)response = super().perform_mutation(_root, info, **data)@@ -1206,6 +1227,16 @@ class ProductTypeDelete(ModelDeleteMutation):return response+ @staticmethod+ def delete_assigned_attribute_values(instance_pk):+ attribute_models.AttributeValue.objects.filter(+ Q(attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES)+ & (+ Q(productassignments__assignment__product_type_id=instance_pk)+ | Q(variantassignments__assignment__product_type_id=instance_pk)+ )+ ).delete()+class ProductMediaCreateInput(graphene.InputObjectType):alt = graphene.String(description="Alt text for a product media.")diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.pyindex 172ce459aa..df2b805b48 100644--- a/saleor/graphql/product/tests/test_bulk_delete.py+++ b/saleor/graphql/product/tests/test_bulk_delete.py@@ -5,6 +5,7 @@ import pytestfrom django.utils import timezonefrom prices import Money, TaxedMoney+from ....attribute.utils import associate_attribute_values_to_instancefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantityfrom ....order import OrderStatus@@ -514,6 +515,51 @@ def test_delete_products_removes_checkout_lines(assert old_quantity == calculate_checkout_quantity(lines) + 3+@patch("saleor.attribute.signals.delete_from_storage_task.delay")+@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_products_with_file_attributes(+ mocked_recalculate_orders_task,+ delete_from_storage_task_mock,+ staff_api_client,+ product_list,+ file_attribute,+ permission_manage_products,+ channel_USD,+ settings,+):+ # given+ query = DELETE_PRODUCTS_MUTATION++ values = [value for value in file_attribute.values.all()]+ for i, product in enumerate(product_list[: len(values)]):+ product_type = product.product_type+ product_type.product_attributes.add(file_attribute)+ existing_value = values[i]+ associate_attribute_values_to_instance(product, file_attribute, existing_value)++ variables = {+ "ids": [+ graphene.Node.to_global_id("Product", product.id)+ for product in product_list+ ]+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ assert content["data"]["productBulkDelete"]["count"] == 3+ mocked_recalculate_orders_task.assert_not_called()+ for value in values:+ with pytest.raises(value._meta.model.DoesNotExist):+ value.refresh_from_db()++ assert delete_from_storage_task_mock.call_count == len(values)+ assert set(+ data.args[0] for data in delete_from_storage_task_mock.call_args_list+ ) == {v.file_url for v in values}++@patch("saleor.order.tasks.recalculate_orders_task.delay")def test_delete_products_variants_in_draft_order(mocked_recalculate_orders_task,@@ -573,16 +619,19 @@ def test_delete_product_media().exists()-def test_delete_product_types(- staff_api_client, product_type_list, permission_manage_product_types_and_attributes-):- query = """+PRODUCT_TYPE_BULK_DELETE_MUTATION = """mutation productTypeBulkDelete($ids: [ID]!) {productTypeBulkDelete(ids: $ids) {count}}- """+"""+++def test_delete_product_types(+ staff_api_client, product_type_list, permission_manage_product_types_and_attributes+):+ query = PRODUCT_TYPE_BULK_DELETE_MUTATIONvariables = {"ids": [@@ -601,6 +650,50 @@ def test_delete_product_types().exists()+@patch("saleor.attribute.signals.delete_from_storage_task.delay")+def test_delete_product_types_with_file_attributes(+ delete_from_storage_task_mock,+ staff_api_client,+ product_type_list,+ product_list,+ file_attribute,+ permission_manage_product_types_and_attributes,+):+ query = PRODUCT_TYPE_BULK_DELETE_MUTATION++ values = [value for value in file_attribute.values.all()]+ for i, product_type in enumerate(product_type_list[: len(values)]):+ product_type.product_attributes.add(file_attribute)+ product = product_list[i]+ product.product_type = product_type+ product.save()+ existing_value = values[i]+ associate_attribute_values_to_instance(product, file_attribute, existing_value)++ variables = {+ "ids": [+ graphene.Node.to_global_id("ProductType", type.id)+ for type in product_type_list+ ]+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)++ assert content["data"]["productTypeBulkDelete"]["count"] == 3+ assert not ProductType.objects.filter(+ id__in=[type.id for type in product_type_list]+ ).exists()+ for value in values:+ with pytest.raises(value._meta.model.DoesNotExist):+ value.refresh_from_db()+ assert delete_from_storage_task_mock.call_count == len(values)+ assert set(+ data.args[0] for data in delete_from_storage_task_mock.call_args_list+ ) == {v.file_url for v in values}++PRODUCT_VARIANT_BULK_DELETE_MUTATION = """mutation productVariantBulkDelete($ids: [ID]!) {productVariantBulkDelete(ids: $ids) {@@ -745,6 +838,62 @@ def test_delete_product_variants_with_images(delete_versatile_image_mock.assert_not_called()+@patch("saleor.attribute.signals.delete_from_storage_task.delay")+@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")+@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_product_variants_with_file_attribute(+ mocked_recalculate_orders_task,+ product_variant_deleted_webhook_mock,+ delete_from_storage_task_mock,+ staff_api_client,+ product_variant_list,+ permission_manage_products,+ file_attribute,+):+ query = PRODUCT_VARIANT_BULK_DELETE_MUTATION++ assert ProductVariantChannelListing.objects.filter(+ variant_id__in=[variant.id for variant in product_variant_list]+ ).exists()++ values = [value for value in file_attribute.values.all()]+ for i, variant in enumerate(product_variant_list[: len(values)]):+ product_type = variant.product.product_type+ product_type.variant_attributes.add(file_attribute)+ existing_value = values[i]+ associate_attribute_values_to_instance(variant, file_attribute, existing_value)++ variables = {+ "ids": [+ graphene.Node.to_global_id("ProductVariant", variant.id)+ for variant in product_variant_list+ ]+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()++ assert content["data"]["productVariantBulkDelete"]["count"] == 3+ assert not ProductVariant.objects.filter(+ id__in=[variant.id for variant in product_variant_list]+ ).exists()+ assert (+ product_variant_deleted_webhook_mock.call_count+ == content["data"]["productVariantBulkDelete"]["count"]+ )+ mocked_recalculate_orders_task.assert_not_called()+ for value in values:+ with pytest.raises(value._meta.model.DoesNotExist):+ value.refresh_from_db()++ assert delete_from_storage_task_mock.call_count == len(values)+ assert set(+ data.args[0] for data in delete_from_storage_task_mock.call_args_list+ ) == {v.file_url for v in values}++@patch("saleor.order.tasks.recalculate_orders_task.delay")def test_delete_product_variants_in_draft_orders(mocked_recalculate_orders_task,diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex c071bddcf3..d31b3c5d26 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -3372,7 +3372,10 @@ def test_create_product_with_file_attribute({"name": existing_value.name,"slug": f"{existing_value.slug}-2",- "file": {"url": existing_value.file_url, "contentType": None},+ "file": {+ "url": f"http://testserver/media/{existing_value.file_url}",+ "contentType": None,+ },"reference": None,"richText": None,}@@ -4970,7 +4973,7 @@ def test_update_product_with_file_attribute_value_new_value_is_not_created("slug": existing_value.slug,"reference": None,"file": {- "url": existing_value.file_url,+ "url": f"http://testserver/media/{existing_value.file_url}","contentType": existing_value.content_type,},}@@ -6187,6 +6190,39 @@ def test_delete_product_trigger_webhook(mocked_recalculate_orders_task.assert_not_called()+@patch("saleor.attribute.signals.delete_from_storage_task.delay")+@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_product_with_file_attribute(+ mocked_recalculate_orders_task,+ delete_from_storage_task_mock,+ staff_api_client,+ product,+ permission_manage_products,+ file_attribute,+):+ query = DELETE_PRODUCT_MUTATION+ product_type = product.product_type+ product_type.product_attributes.add(file_attribute)+ existing_value = file_attribute.values.first()+ associate_attribute_values_to_instance(product, file_attribute, existing_value)++ node_id = graphene.Node.to_global_id("Product", product.id)+ variables = {"id": node_id}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productDelete"]+ assert data["product"]["name"] == product.name+ with pytest.raises(product._meta.model.DoesNotExist):+ product.refresh_from_db()+ assert node_id == data["product"]["id"]+ mocked_recalculate_orders_task.assert_not_called()+ with pytest.raises(existing_value._meta.model.DoesNotExist):+ existing_value.refresh_from_db()+ delete_from_storage_task_mock.assert_called_once_with(existing_value.file_url)++def test_delete_product_removes_checkout_lines(staff_api_client,checkout_with_items,@@ -7133,6 +7169,43 @@ def test_product_type_delete_mutation_deletes_also_images(delete_versatile_image_mock.assert_called_once_with(media_obj.image.name)+@patch("saleor.attribute.signals.delete_from_storage_task.delay")+def test_product_type_delete_with_file_attributes(+ delete_from_storage_task_mock,+ staff_api_client,+ product_with_variant_with_file_attribute,+ file_attribute,+ permission_manage_product_types_and_attributes,+):+ query = PRODUCT_TYPE_DELETE_MUTATION+ product_type = product_with_variant_with_file_attribute.product_type++ product_type.product_attributes.add(file_attribute)+ associate_attribute_values_to_instance(+ product_with_variant_with_file_attribute,+ file_attribute,+ file_attribute.values.last(),+ )+ values = list(file_attribute.values.all())++ variables = {"id": graphene.Node.to_global_id("ProductType", product_type.id)}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )+ content = get_graphql_content(response)+ data = content["data"]["productTypeDelete"]+ assert data["productType"]["name"] == product_type.name+ with pytest.raises(product_type._meta.model.DoesNotExist):+ product_type.refresh_from_db()+ for value in values:+ with pytest.raises(value._meta.model.DoesNotExist):+ value.refresh_from_db()+ assert delete_from_storage_task_mock.call_count == len(values)+ assert set(+ data.args[0] for data in delete_from_storage_task_mock.call_args_list+ ) == {v.file_url for v in values}++def test_product_type_delete_mutation_variants_in_draft_order(staff_api_client,permission_manage_product_types_and_attributes,diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex 4289ff983e..028dbd600e 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -1911,7 +1911,10 @@ def test_update_product_variant_with_file_attribute_new_value_is_not_created(value_data = variant_data["attributes"][0]["values"][0]assert value_data["slug"] == existing_value.slugassert value_data["name"] == existing_value.name- assert value_data["file"]["url"] == existing_value.file_url+ assert (+ value_data["file"]["url"]+ == f"http://testserver/media/{existing_value.file_url}"+ )assert value_data["file"]["contentType"] == existing_value.content_type@@ -2303,6 +2306,45 @@ def test_delete_variant_with_image(delete_versatile_image_mock.assert_not_called()+@patch("saleor.attribute.signals.delete_from_storage_task.delay")+@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")+@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_variant_with_file_attribute(+ mocked_recalculate_orders_task,+ product_variant_deleted_webhook_mock,+ delete_from_storage_task_mock,+ staff_api_client,+ product,+ permission_manage_products,+ file_attribute,+):+ query = DELETE_VARIANT_MUTATION+ variant = product.variants.first()++ product_type = product.product_type+ product_type.variant_attributes.add(file_attribute)+ existing_value = file_attribute.values.first()+ associate_attribute_values_to_instance(variant, file_attribute, existing_value)++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {"id": variant_id}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantDelete"]++ product_variant_deleted_webhook_mock.assert_called_once_with(variant)+ assert data["productVariant"]["sku"] == variant.sku+ with pytest.raises(variant._meta.model.DoesNotExist):+ variant.refresh_from_db()+ mocked_recalculate_orders_task.assert_not_called()+ with pytest.raises(existing_value._meta.model.DoesNotExist):+ existing_value.refresh_from_db()+ delete_from_storage_task_mock.assert_called_once_with(existing_value.file_url)++@patch("saleor.order.tasks.recalculate_orders_task.delay")def test_delete_variant_in_draft_order(mocked_recalculate_orders_task,diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 11e504ea54..6008e6d9b4 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -896,14 +896,14 @@ def file_attribute(db):attribute=attribute,name="test_file.txt",slug="test_filetxt",- file_url="http://mirumee.com/test_media/test_file.txt",+ file_url="test_file.txt",content_type="text/plain",)AttributeValue.objects.create(attribute=attribute,name="test_file.jpeg",slug="test_filejpeg",- file_url="http://mirumee.com/test_media/test_file.jpeg",+ file_url="test_file.jpeg",content_type="image/jpeg",)return attribute@@ -1019,14 +1019,14 @@ def page_file_attribute(db):attribute=attribute,name="test_file.txt",slug="test_filetxt",- file_url="http://mirumee.com/test_media/test_file.txt",+ file_url="test_file.txt",content_type="text/plain",)AttributeValue.objects.create(attribute=attribute,name="test_file.jpeg",slug="test_filejpeg",- file_url="http://mirumee.com/test_media/test_file.jpeg",+ file_url="test_file.jpeg",content_type="image/jpeg",)return attribute