Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix clean_manifest validation. (#16392)
Artur7a95ee2c6ce2
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.pyindex 2c0b8d2719..8366ce0753 100644--- a/saleor/app/manifest_validations.py+++ b/saleor/app/manifest_validations.py@@ -153,8 +153,11 @@ def clean_manifest_data(manifest_data, raise_for_saleor_version=False):app_permissions = []manifest_data["permissions"] = app_permissions-- if app := App.objects.filter(identifier=manifest_data.get("id")).first():+ if (+ app := App.objects.not_removed()+ .filter(identifier=manifest_data.get("id"))+ .first()+ ):errors["identifier"].append(ValidationError(f"App with the same identifier is already installed: {app.name}"diff --git a/saleor/app/models.py b/saleor/app/models.pyindex 251bcf530e..f853bee322 100644--- a/saleor/app/models.py+++ b/saleor/app/models.py@@ -31,6 +31,12 @@ class AppQueryset(models.QuerySet["App"]):**permissions,)+ def not_removed(self):+ return self.filter(removed_at__isnull=True)++ def marked_to_be_removed(self):+ return self.filter(removed_at__isnull=False)+AppManager = models.Manager.from_queryset(AppQueryset)diff --git a/saleor/graphql/app/tests/mutations/cassettes/test_app_fetch_manifest/test_fetch_manifest_app_with_same_identifier_installed_but_marked_to_be_removed.yaml b/saleor/graphql/app/tests/mutations/cassettes/test_app_fetch_manifest/test_fetch_manifest_app_with_same_identifier_installed_but_marked_to_be_removed.yamlnew file mode 100644index 0000000000..ffa9cc76d3--- /dev/null+++ b/saleor/graphql/app/tests/mutations/cassettes/test_app_fetch_manifest/test_fetch_manifest_app_with_same_identifier_installed_but_marked_to_be_removed.yaml@@ -0,0 +1,95 @@+interactions:+- request:+ body: null+ headers:+ Accept:+ - application/json+ Accept-Encoding:+ - identity+ Connection:+ - keep-alive+ Saleor-Schema-Version:+ - '3.19'+ User-Agent:+ - Saleor/3.19+ method: GET+ uri: http://localhost:3000/api/manifest+ response:+ body:+ string: '{"about":"App connects with Avatax to dynamically calculate taxes","appUrl":"http://localhost:3000","author":"Saleor+ Commerce","brand":{"logo":{"default":"http://localhost:3000/logo.png"}},"dataPrivacyUrl":"https://saleor.io/legal/privacy/","extensions":[],"homepageUrl":"https://github.com/saleor/apps","id":"saleor.app.avatax","name":"Avatax","permissions":["HANDLE_TAXES","MANAGE_ORDERS"],"requiredSaleorVersion":">=3.18+ <4","supportUrl":"https://github.com/saleor/apps/discussions","tokenTargetUrl":"http://localhost:3000/api/register","version":"1.5.2","webhooks":[{"query":"subscription+ CalculateTaxes { event { ...CalculateTaxesEvent }}fragment CalculateTaxesEvent+ on Event { __typename ...WebhookMetadata ... on CalculateTaxes { taxBase {+ ...TaxBase } recipient { privateMetadata { key value } } }}fragment WebhookMetadata+ on Event { issuedAt version}fragment TaxBase on TaxableObject { pricesEnteredWithTax+ currency channel { slug } address { ...Address } shippingPrice { amount }+ lines { ...TaxBaseLine } sourceObject { __typename ... on Checkout { id avataxEntityCode:+ metafield(key: \"avataxEntityCode\") avataxCustomerCode: metafield(key: \"avataxCustomerCode\")+ user { ...User } } ... on Order { id avataxEntityCode: metafield(key: \"avataxEntityCode\")+ avataxCustomerCode: metafield(key: \"avataxCustomerCode\") user { ...User+ } } }}fragment Address on Address { streetAddress1 streetAddress2 city countryArea+ postalCode country { code }}fragment TaxBaseLine on TaxableObjectLine { sourceLine+ { __typename ... on CheckoutLine { id checkoutProductVariant: variant { id+ product { taxClass { id name } } } } ... on OrderLine { id orderProductVariant:+ variant { id product { taxClass { id name } } } } } quantity unitPrice { amount+ } totalPrice { amount }}fragment User on User { id email avataxCustomerCode:+ metafield(key: \"avataxCustomerCode\")}","name":"CheckoutCalculateTaxes","targetUrl":"http://localhost:3000/api/webhooks/checkout-calculate-taxes","isActive":true,"syncEvents":["CHECKOUT_CALCULATE_TAXES"]},{"query":"subscription+ CalculateTaxes { event { ...CalculateTaxesEvent }}fragment CalculateTaxesEvent+ on Event { __typename ...WebhookMetadata ... on CalculateTaxes { taxBase {+ ...TaxBase } recipient { privateMetadata { key value } } }}fragment WebhookMetadata+ on Event { issuedAt version}fragment TaxBase on TaxableObject { pricesEnteredWithTax+ currency channel { slug } address { ...Address } shippingPrice { amount }+ lines { ...TaxBaseLine } sourceObject { __typename ... on Checkout { id avataxEntityCode:+ metafield(key: \"avataxEntityCode\") avataxCustomerCode: metafield(key: \"avataxCustomerCode\")+ user { ...User } } ... on Order { id avataxEntityCode: metafield(key: \"avataxEntityCode\")+ avataxCustomerCode: metafield(key: \"avataxCustomerCode\") user { ...User+ } } }}fragment Address on Address { streetAddress1 streetAddress2 city countryArea+ postalCode country { code }}fragment TaxBaseLine on TaxableObjectLine { sourceLine+ { __typename ... on CheckoutLine { id checkoutProductVariant: variant { id+ product { taxClass { id name } } } } ... on OrderLine { id orderProductVariant:+ variant { id product { taxClass { id name } } } } } quantity unitPrice { amount+ } totalPrice { amount }}fragment User on User { id email avataxCustomerCode:+ metafield(key: \"avataxCustomerCode\")}","name":"OrderCalculateTaxes","targetUrl":"http://localhost:3000/api/webhooks/order-calculate-taxes","isActive":true,"syncEvents":["ORDER_CALCULATE_TAXES"]},{"query":"subscription+ OrderCancelledSubscription { event { ...OrderCancelledEventSubscription }}fragment+ OrderCancelledEventSubscription on Event { __typename ...WebhookMetadata ...+ on OrderCancelled { order { ...OrderCancelledSubscription } recipient { privateMetadata+ { key value } } }}fragment WebhookMetadata on Event { issuedAt version}fragment+ OrderCancelledSubscription on Order { id avataxId: metafield(key: \"avataxId\")+ channel { id slug }}","name":"OrderCancelled","targetUrl":"http://localhost:3000/api/webhooks/order-cancelled","isActive":true,"asyncEvents":["ORDER_CANCELLED"]},{"query":"subscription+ OrderConfirmedSubscription { event { ...OrderConfirmedEventSubscription }}fragment+ OrderConfirmedEventSubscription on Event { __typename ...WebhookMetadata ...+ on OrderConfirmed { order { ...OrderConfirmedSubscription } } recipient {+ privateMetadata { key value } }}fragment WebhookMetadata on Event { issuedAt+ version}fragment OrderConfirmedSubscription on Order { id number userEmail+ user { ...User } avataxCustomerCode: metafield(key: \"avataxCustomerCode\")+ created status channel { id slug taxConfiguration { pricesEnteredWithTax taxCalculationStrategy+ } } shippingAddress { ...Address } billingAddress { ...Address } total { currency+ net { amount } tax { amount } } shippingPrice { gross { amount } net { amount+ } } lines { ...OrderLine } avataxEntityCode: metafield(key: \"avataxEntityCode\")+ avataxTaxCalculationDate: metafield(key: \"avataxTaxCalculationDate\") avataxDocumentCode:+ metafield(key: \"avataxDocumentCode\")}fragment User on User { id email avataxCustomerCode:+ metafield(key: \"avataxCustomerCode\")}fragment Address on Address { streetAddress1+ streetAddress2 city countryArea postalCode country { code }}fragment OrderLine+ on OrderLine { productSku productVariantId productName quantity taxClass {+ id } unitPrice { net { amount } } totalPrice { net { amount } tax { amount+ } gross { amount } }}","name":"OrderConfirmed","targetUrl":"http://localhost:3000/api/webhooks/order-confirmed","isActive":true,"asyncEvents":["ORDER_CONFIRMED"]}]}'+ headers:+ Connection:+ - keep-alive+ Content-Length:+ - '5549'+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Mon, 15 Jul 2024 08:06:12 GMT+ ETag:+ - '"16l6t5qo2d34a5"'+ Keep-Alive:+ - timeout=5+ Vary:+ - Accept-Encoding+ status:+ code: 200+ message: OK+version: 1diff --git a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.pyindex 75bd0e0d17..309810fed7 100644--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py@@ -1,6 +1,6 @@import base64from io import BytesIO-from unittest.mock import ANY, Mock+from unittest.mock import ANY, Mock, patchimport pytestimport requests@@ -9,6 +9,7 @@ from requests_hardened import HTTPSessionfrom ..... import schema_versionfrom .....app.error_codes import AppErrorCode+from .....app.models import Appfrom .....thumbnail import IconThumbnailFormatfrom ....tests.utils import assert_no_permission, get_graphql_contentfrom ...enums import AppExtensionMountEnum, AppExtensionTargetEnum@@ -885,3 +886,42 @@ def test_fetch_manifest_fail_when_app_with_same_identifier_already_installed(assert errors[0]["message"] == (f"App with the same identifier is already installed: {app.name}")+++def test_fetch_manifest_app_with_same_identifier_installed_but_marked_to_be_removed(+ staff_api_client,+ staff_user,+ permission_manage_apps,+ app_marked_to_be_removed,+):+ # given+ app_marked_to_be_removed.identifier = "saleor.app.avatax"+ app_marked_to_be_removed.save()+ manifest_url = "http://localhost:3000/api/manifest"++ query = APP_FETCH_MANIFEST_MUTATION+ variables = {+ "manifest_url": manifest_url,+ }+ staff_user.user_permissions.set([permission_manage_apps])++ # when+ with patch(+ "saleor.graphql.app.mutations.app_fetch_manifest.fetch_brand_data"+ ) as mocked_fetch_brand:+ mocked_fetch_brand.return_value = None+ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ )+ content = get_graphql_content(response)+ errors = content["data"]["appFetchManifest"]["errors"]+ manifest = content["data"]["appFetchManifest"]["manifest"]++ # then+ all_apps = App.objects.all()+ assert not errors+ assert manifest["identifier"] == "saleor.app.avatax"+ assert all_apps.not_removed().count() == 0+ assert all_apps.marked_to_be_removed().count() == 1diff --git a/saleor/graphql/app/tests/mutations/test_app_install.py b/saleor/graphql/app/tests/mutations/test_app_install.pyindex 06fd83d592..aac327d6ec 100644--- a/saleor/graphql/app/tests/mutations/test_app_install.py+++ b/saleor/graphql/app/tests/mutations/test_app_install.py@@ -67,6 +67,42 @@ def test_install_app_mutation(assert app_installation_data["manifestUrl"] == app_installation.manifest_urlmocked_task.assert_called_with(app_installation.pk, True)assert app_installation.uuid is not None+ assert App.objects.count() == 0+++def test_install_app_mutation_with_another_app_installed_but_marked_to_be_removed(+ permission_manage_apps,+ permission_manage_orders,+ staff_api_client,+ staff_user,+ monkeypatch,+ app_marked_to_be_removed,+):+ assert app_marked_to_be_removed.removed_at is not None+ # given+ mocked_task = Mock()+ monkeypatch.setattr(+ "saleor.graphql.app.mutations.app_install.install_app_task.delay", mocked_task+ )+ staff_user.user_permissions.set([permission_manage_apps, permission_manage_orders])+ variables = {+ "app_name": "New external integration",+ "manifest_url": "http://localhost:3000/manifest",+ "permissions": [PermissionEnum.MANAGE_ORDERS.name],+ }+ # when+ data = _mutate_app_install(staff_api_client, variables)++ # then+ app_installation = AppInstallation.objects.get()+ app_installation_data = data["appInstallation"]+ _, app_id = graphene.Node.from_global_id(app_installation_data["id"])+ assert int(app_id) == app_installation.id+ assert app_installation_data["status"] == JobStatus.PENDING.upper()+ assert app_installation_data["manifestUrl"] == app_installation.manifest_url+ mocked_task.assert_called_with(app_installation.pk, True)+ assert app_installation.uuid is not None+ assert App.objects.count() == 1def test_app_is_not_allowed_to_install_app(diff --git a/saleor/graphql/app/tests/mutations/test_app_retry_install.py b/saleor/graphql/app/tests/mutations/test_app_retry_install.pyindex f8c0d91a07..5dcb7fec98 100644--- a/saleor/graphql/app/tests/mutations/test_app_retry_install.py+++ b/saleor/graphql/app/tests/mutations/test_app_retry_install.py@@ -67,6 +67,44 @@ def test_retry_install_app_mutation(assert data["appInstallation"]["status"] == JobStatus.PENDING.upper()assert data["appInstallation"]["manifestUrl"] == app_installation.manifest_urlmocked_task.assert_called_with(app_installation.pk, True)+ assert App.objects.count() == 0+++def test_retry_install_app_mutation_with_another_app_installed_but_marked_to_be_removed(+ monkeypatch,+ app_installation,+ permission_manage_apps,+ staff_api_client,+ permission_manage_orders,+ staff_user,+ app_marked_to_be_removed,+):+ assert app_marked_to_be_removed.removed_at is not None+ # given+ app_installation.status = JobStatus.FAILED+ app_installation.save()+ mocked_task = Mock()+ monkeypatch.setattr(+ "saleor.graphql.app.mutations.app_retry_install.install_app_task.delay",+ mocked_task,+ )+ staff_user.user_permissions.set([permission_manage_apps, permission_manage_orders])+ variables = {+ "id": graphene.Node.to_global_id("AppInstallation", app_installation.id),+ "activate_after_installation": True,+ }++ # when+ data = _mutate_app_install_retry(staff_api_client, variables)++ # then+ app_installation = AppInstallation.objects.get()+ _, app_id = graphene.Node.from_global_id(data["appInstallation"]["id"])+ assert int(app_id) == app_installation.id+ assert data["appInstallation"]["status"] == JobStatus.PENDING.upper()+ assert data["appInstallation"]["manifestUrl"] == app_installation.manifest_url+ mocked_task.assert_called_with(app_installation.pk, True)+ assert App.objects.count() == 1def test_retry_install_app_mutation_by_app(diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 817bbcc32b..05816d92ac 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -7450,6 +7450,18 @@ def app(db):return app+def app_marked_to_be_removed(db):+ app = App.objects.create(+ name="Sample app objects",+ is_active=True,+ identifier="saleor.app.test",+ manifest_url="http://localhost:3000/manifest",+ removed_at=timezone.now(),+ )+ return app++@pytest.fixturedef webhook_app(db,