Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add ACCOUNT_DELETE_REQUESTED event (#13170)
SzymJb0245506e69b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cb86f0b491..1e482a0c2a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -40,7 +40,8 @@ All notable, unreleased changes to this project will be documented in this file.- Add missing descriptions to csv module. - #13184 by @fowczarek- Add missing descriptions to Account module. - #13155 by @fowczarek- Add `ACCOUNT_CONFIRMATION_REQUESTED` async event - #13162 by @SzymJ-+- Add `ACCOUNT_DELETE_REQUESTED` async event - #13170 by @SzymJ+-# 3.14.0### Breaking changesdiff --git a/saleor/account/notifications.py b/saleor/account/notifications.pyindex 24db8b054d..e9734d0d65 100644--- a/saleor/account/notifications.py+++ b/saleor/account/notifications.py@@ -124,10 +124,11 @@ def send_user_change_email_notification(recipient_email, user, manager, channel_def send_account_delete_confirmation_notification(- redirect_url, user, manager, channel_slug+ redirect_url, user, manager, channel_slug, token=None):"""Trigger sending an account delete notification for the given user."""- token = account_delete_token_generator.make_token(user)+ if not token:+ token = account_delete_token_generator.make_token(user)params = urlencode({"token": token})delete_url = prepare_url(params, redirect_url)payload = {diff --git a/saleor/graphql/account/mutations/account/account_request_deletion.py b/saleor/graphql/account/mutations/account/account_request_deletion.pyindex 2b4551eb60..e561e42dab 100644--- a/saleor/graphql/account/mutations/account/account_request_deletion.py+++ b/saleor/graphql/account/mutations/account/account_request_deletion.py@@ -1,9 +1,12 @@+from urllib.parse import urlencode+import graphenefrom django.core.exceptions import ValidationErrorfrom .....account import notificationsfrom .....account.error_codes import AccountErrorCode-from .....core.utils.url import validate_storefront_url+from .....core.tokens import account_delete_token_generator+from .....core.utils.url import prepare_url, validate_storefront_urlfrom .....permission.auth_filters import AuthorizationFiltersfrom ....channel.utils import clean_channelfrom ....core import ResolveInfo@@ -51,7 +54,21 @@ class AccountRequestDeletion(BaseMutation):)channel_slug = clean_channel(channel, error_class=AccountErrorCode).slugmanager = get_plugin_manager_promise(info.context).get()+ token = account_delete_token_generator.make_token(user) # type: ignore++ # Notifications will be deprecated in the futurenotifications.send_account_delete_confirmation_notification(- redirect_url, user, manager, channel_slug=channel_slug+ redirect_url, user, manager, channel_slug=channel_slug, token=token)+ params = urlencode({"token": token})+ delete_url = prepare_url(params, redirect_url)++ cls.call_event(+ manager.account_delete_requested,+ user,+ channel_slug,+ token,+ delete_url,+ )+return AccountRequestDeletion()diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.pyindex c9292ff362..1fe3967167 100644--- a/saleor/graphql/account/tests/test_account.py+++ b/saleor/graphql/account/tests/test_account.py@@ -2796,6 +2796,36 @@ def test_account_request_deletion()+@patch("saleor.account.notifications.account_delete_token_generator.make_token")+@patch("saleor.plugins.manager.PluginsManager.account_delete_requested")+def test_account_request_deletion_send_account_delete_requested_event(+ account_delete_requested_mock,+ mocked_token,+ user_api_client,+ channel_PLN,+ site_settings,+):+ mocked_token.return_value = "token"+ user = user_api_client.user+ redirect_url = "https://www.example.com"+ variables = {"redirectUrl": redirect_url, "channel": channel_PLN.slug}+ response = user_api_client.post_graphql(+ ACCOUNT_REQUEST_DELETION_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["accountRequestDeletion"]+ assert not data["errors"]+ params = urlencode({"token": "token"})+ delete_url = prepare_url(params, redirect_url)++ account_delete_requested_mock.assert_called_once_with(+ user,+ channel_PLN.slug,+ "token",+ delete_url,+ )++@freeze_time("2018-05-31 12:00:01")@patch("saleor.plugins.manager.PluginsManager.notify")def test_account_request_deletion_token_validation(diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex bbdfb4c06c..0cf88a495d 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1688,9 +1688,12 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""All the events."""ANY_EVENTS- """An account confirmation requested."""+ """An account confirmation is requested."""ACCOUNT_CONFIRMATION_REQUESTED+ """An account delete is requested."""+ ACCOUNT_DELETE_REQUESTED+"""A new address created."""ADDRESS_CREATED@@ -2322,9 +2325,12 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""All the events."""ANY_EVENTS- """An account confirmation requested."""+ """An account confirmation is requested."""ACCOUNT_CONFIRMATION_REQUESTED+ """An account delete is requested."""+ ACCOUNT_DELETE_REQUESTED+"""A new address created."""ADDRESS_CREATED@@ -3324,6 +3330,7 @@ scalar JSONString"""An enumeration."""enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {ACCOUNT_CONFIRMATION_REQUESTED+ ACCOUNT_DELETE_REQUESTEDADDRESS_CREATEDADDRESS_UPDATEDADDRESS_DELETED@@ -27468,6 +27475,40 @@ type AccountConfirmationRequested implements Event @doc(category: "Users") {shop: Shop}+"""+Event sent when account delete is requested.++Added in Saleor 3.15.+"""+type AccountDeleteRequested implements Event @doc(category: "Users") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The URL to redirect the user after he accepts the request."""+ redirectUrl: String++ """The user the event relates to."""+ user: User++ """The channel data."""+ channel: Channel++ """The token required to confirm request."""+ token: String++ """Shop data."""+ shop: Shop+}+"""Event sent when new address is created.diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex cea1a18f4e..45191b6a4c 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -34,8 +34,9 @@ order_updated_event_enum_description = (WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED: (- "An account confirmation requested."+ "An account confirmation is requested."),+ WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED: "An account delete is requested.",WebhookEventAsyncType.ADDRESS_CREATED: "A new address created.",WebhookEventAsyncType.ADDRESS_UPDATED: "An address updated.",WebhookEventAsyncType.ADDRESS_DELETED: "An address deleted.",diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 77eeedbb06..6f2a1e190a 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -187,6 +187,14 @@ class AccountConfirmationRequested(SubscriptionObjectType, AccountOperationBase))+class AccountDeleteRequested(SubscriptionObjectType, AccountOperationBase):+ class Meta:+ root_type = "User"+ enable_dry_run = False+ interfaces = (Event,)+ description = "Event sent when account delete is requested." + ADDED_IN_315++class AddressBase(AbstractType):address = graphene.Field("saleor.graphql.account.types.Address",@@ -2085,6 +2093,7 @@ class ThumbnailCreated(SubscriptionObjectType):WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED: AccountConfirmationRequested,+ WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED: AccountDeleteRequested,WebhookEventAsyncType.ADDRESS_CREATED: AddressCreated,WebhookEventAsyncType.ADDRESS_UPDATED: AddressUpdated,WebhookEventAsyncType.ADDRESS_DELETED: AddressDeleted,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 0524718f89..92f20316ff 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -157,6 +157,12 @@ class BasePlugin:["User", str, str, Optional[str], None], None]+ # Trigger when account delete is requested.+ #+ # Overwrite this method if you need to trigger specific logic after an account+ # delete is requested.+ account_delete_requested: Callable[["User", str, str, str, None], None]+# Trigger when address is created.## Overwrite this method if you need to trigger specific logic after an address isdiff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 8fb4afefa4..2925aeb615 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -1074,6 +1074,19 @@ class PluginsManager(PaymentInterface):redirect_url=redirect_url,)+ def account_delete_requested(+ self, user: "User", channel_slug: str, token: str, redirect_url: str+ ):+ default_value = None+ return self.__run_method_on_plugins(+ "account_delete_requested",+ default_value,+ user,+ channel_slug,+ token=token,+ redirect_url=redirect_url,+ )+def address_created(self, address: "Address"):default_value = Nonereturn self.__run_method_on_plugins("address_created", default_value, address)diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 5c39c825e2..44a0577e2e 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -150,22 +150,28 @@ class WebhookPlugin(BasePlugin):metadata_updated_data, event_type, webhooks, instance, self.requestor)- def _trigger_address_event(self, event_type, address):+ def _trigger_account_event(+ self, event_type, user, channel_slug, token, redirect_url+ ):if webhooks := get_webhooks_for_event(event_type):payload = self._serialize_payload({- "id": graphene.Node.to_global_id("Address", address.id),- "city": address.city,- "country": {- "code": address.country.code,- "name": address.country.name,- },- "company_name": address.company_name,- "meta": self._generate_meta(),+ "id": graphene.Node.to_global_id("User", user.id),+ "token": token,+ "redirect_url": redirect_url,})trigger_webhooks_async(- payload, event_type, webhooks, address, self.requestor+ payload,+ event_type,+ webhooks,+ {+ "user": user,+ "channel_slug": channel_slug,+ "token": token,+ "redirect_url": redirect_url,+ },+ self.requestor,)def account_confirmation_requested(@@ -178,27 +184,48 @@ class WebhookPlugin(BasePlugin):) -> None:if not self.active:return previous_value- if webhooks := get_webhooks_for_event(- WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED- ):+ self._trigger_account_event(+ WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED,+ user,+ channel_slug,+ token,+ redirect_url,+ )++ def account_delete_requested(+ self,+ user: "User",+ channel_slug: str,+ token: str,+ redirect_url: str,+ previous_value: None,+ ) -> None:+ if not self.active:+ return previous_value+ self._trigger_account_event(+ WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED,+ user,+ channel_slug,+ token,+ redirect_url,+ )++ def _trigger_address_event(self, event_type, address):+ if webhooks := get_webhooks_for_event(event_type):payload = self._serialize_payload({- "id": graphene.Node.to_global_id("User", user.id),- "token": token,- "redirect_url": redirect_url,+ "id": graphene.Node.to_global_id("Address", address.id),+ "city": address.city,+ "country": {+ "code": address.country.code,+ "name": address.country.name,+ },+ "company_name": address.company_name,+ "meta": self._generate_meta(),})trigger_webhooks_async(- payload,- WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED,- webhooks,- {- "user": user,- "channel_slug": channel_slug,- "token": token,- "redirect_url": redirect_url,- },- self.requestor,+ payload, event_type, webhooks, address, self.requestor)def address_created(self, address: "Address", previous_value: None) -> None:diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.pyindex a0694af9a2..e8ba605fef 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py@@ -28,6 +28,14 @@ def subscription_account_confirmation_requested_webhook(subscription_webhook):)+def subscription_account_delete_requested_webhook(subscription_webhook):+ return subscription_webhook(+ queries.ACCOUNT_DELETE_REQUESTED,+ WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED,+ )++@pytest.fixturedef subscription_address_created_webhook(subscription_webhook):return subscription_webhook(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.pyindex 98c7edebe1..2abec6a245 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py@@ -8,6 +8,25 @@ from .....graphql.attribute.enums import AttributeInputTypeEnum, AttributeTypeEnfrom .....product.models import Product+def generate_account_events_payload(customer_user, channel):+ return json.dumps(+ {+ **generate_customer_payload(customer_user),+ **{+ "token": "token",+ "redirectUrl": "http://www.mirumee.com?token=token",+ "channel": {+ "slug": channel.slug,+ "id": graphene.Node.to_global_id("Channel", channel.id),+ },+ "shop": {+ "domain": {"host": "mirumee.com", "url": "http://mirumee.com/"}+ },+ },+ }+ )++def generate_app_payload(app, app_global_id):return json.dumps({diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.pyindex 66ab6a9d61..e0234d9262 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py@@ -28,6 +28,34 @@ ACCOUNT_CONFIRMATION_REQUESTED = ()+ACCOUNT_DELETE_REQUESTED = (+ fragments.CUSTOMER_DETAILS+ + """+ subscription{+ event{+ ...on AccountDeleteRequested{+ user{+ ...CustomerDetails+ }+ token+ redirectUrl+ channel{+ slug+ id+ }+ shop{+ domain{+ host+ url+ }+ }+ }+ }+ }+"""+)++ADDRESS_CREATED = (fragments.ADDRESS_DETAILS+ """diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex 927680c01e..1fe393a8c0 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -15,6 +15,7 @@ from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ...tasks import create_deliveries_for_subscriptions, loggerfrom . import subscription_queriesfrom .payloads import (+ generate_account_events_payload,generate_address_payload,generate_app_payload,generate_attribute_payload,@@ -92,29 +93,41 @@ def test_account_confirmation_requested("user": customer_user,"channel_slug": channel_USD.slug,"token": "token",- "redirect_url": "http://www.example.com?token=token",+ "redirect_url": "http://www.mirumee.com?token=token",},webhooks,)# then- expected_payload = json.dumps(+ expected_payload = generate_account_events_payload(customer_user, channel_USD)++ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_account_delete_requested(+ customer_user, channel_USD, subscription_account_delete_requested_webhook+):+ # given+ webhooks = [subscription_account_delete_requested_webhook]+ event_type = WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type,{- **generate_customer_payload(customer_user),- **{- "token": "token",- "redirectUrl": "http://www.example.com?token=token",- "channel": {- "slug": channel_USD.slug,- "id": graphene.Node.to_global_id("Channel", channel_USD.id),- },- "shop": {- "domain": {"host": "mirumee.com", "url": "http://mirumee.com/"}- },- },- }+ "user": customer_user,+ "channel_slug": channel_USD.slug,+ "token": "token",+ "redirect_url": "http://www.mirumee.com?token=token",+ },+ webhooks,)+ # then+ expected_payload = generate_account_events_payload(customer_user, channel_USD)+assert deliveries[0].payload.payload == expected_payloadassert len(deliveries) == len(webhooks)assert deliveries[0].webhook == webhooks[0]diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 0cb34079a0..6f8ea53973 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -20,6 +20,7 @@ class WebhookEventAsyncType:ANY = "any_events"ACCOUNT_CONFIRMATION_REQUESTED = "account_confirmation_requested"+ ACCOUNT_DELETE_REQUESTED = "account_delete_requested"ADDRESS_CREATED = "address_created"ADDRESS_UPDATED = "address_updated"@@ -175,6 +176,7 @@ class WebhookEventAsyncType:DISPLAY_LABELS = {ANY: "Any events",ACCOUNT_CONFIRMATION_REQUESTED: "Account confirmation requested",+ ACCOUNT_DELETE_REQUESTED: "Account delete requested",ADDRESS_CREATED: "Address created",ADDRESS_UPDATED: "Address updated",ADDRESS_DELETED: "Address deleted",@@ -301,6 +303,7 @@ class WebhookEventAsyncType:ACCOUNT_CONFIRMATION_REQUESTED,DISPLAY_LABELS[ACCOUNT_CONFIRMATION_REQUESTED],),+ (ACCOUNT_DELETE_REQUESTED, DISPLAY_LABELS[ACCOUNT_DELETE_REQUESTED]),(ADDRESS_CREATED, DISPLAY_LABELS[ADDRESS_CREATED]),(ADDRESS_UPDATED, DISPLAY_LABELS[ADDRESS_UPDATED]),(ADDRESS_DELETED, DISPLAY_LABELS[ADDRESS_DELETED]),@@ -434,6 +437,7 @@ class WebhookEventAsyncType:PERMISSIONS = {ACCOUNT_CONFIRMATION_REQUESTED: AccountPermissions.MANAGE_USERS,+ ACCOUNT_DELETE_REQUESTED: AccountPermissions.MANAGE_USERS,ADDRESS_CREATED: AccountPermissions.MANAGE_USERS,ADDRESS_UPDATED: AccountPermissions.MANAGE_USERS,ADDRESS_DELETED: AccountPermissions.MANAGE_USERS,