Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `ACCOUNT_CONFIRMED` webhook event. (#13510)
Artur78775ac61bd7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1d81ccc5f5..6f7b75e997 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -93,6 +93,8 @@ Shipping methods can be removed by the user after it has been assigned to a chec- Add `CHANNEL_METADATA_UPDATED` webhook - #13448, by @Air-t- Called when metadata is changed for the Channel object via the generic metadata API or the `channelUpdate` mutation.+- Add `ACCOUNT_CONFIRMED` webhook - #13471, by @Air-t+ - Called when user confirm an account with `confirmAccount` mutation.### Other changes- Add possibility to log without confirming email - #13059 by @kadewudiff --git a/saleor/graphql/account/mutations/account/confirm_account.py b/saleor/graphql/account/mutations/account/confirm_account.pyindex 84d4a97aa4..013a5f6983 100644--- a/saleor/graphql/account/mutations/account/confirm_account.py+++ b/saleor/graphql/account/mutations/account/confirm_account.py@@ -6,10 +6,13 @@ from .....account import modelsfrom .....account.error_codes import AccountErrorCodefrom .....giftcard.utils import assign_user_gift_cardsfrom .....order.utils import match_orders_with_new_user+from .....webhook.event_types import WebhookEventAsyncTypefrom ....core import ResolveInfofrom ....core.doc_category import DOC_CATEGORY_USERSfrom ....core.mutations import BaseMutationfrom ....core.types import AccountError+from ....core.utils import WebhookEventInfo+from ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import UserINVALID_TOKEN = "Invalid or expired token."@@ -35,6 +38,12 @@ class ConfirmAccount(BaseMutation):doc_category = DOC_CATEGORY_USERSerror_type_class = AccountErrorerror_type_field = "account_errors"+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.ACCOUNT_CONFIRMED,+ description="Account was confirmed.",+ ),+ ]@classmethoddef perform_mutation(cls, _root, info: ResolveInfo, /, **data):@@ -66,4 +75,11 @@ class ConfirmAccount(BaseMutation):match_orders_with_new_user(user)assign_user_gift_cards(user)+ cls.post_save_action(info, user)+return ConfirmAccount(user=user)++ @classmethod+ def post_save_action(cls, info: ResolveInfo, instance):+ manager = get_plugin_manager_promise(info.context).get()+ cls.call_event(manager.account_confirmed, instance)diff --git a/saleor/graphql/account/tests/mutations/account/test_account_register.py b/saleor/graphql/account/tests/mutations/account/test_account_register.pyindex 61b0c72a6b..db345a7b67 100644--- a/saleor/graphql/account/tests/mutations/account/test_account_register.py+++ b/saleor/graphql/account/tests/mutations/account/test_account_register.py@@ -80,7 +80,6 @@ def test_customer_register(}query = ACCOUNT_REGISTER_MUTATIONmutation_name = "accountRegister"-response = api_client.post_graphql(query, variables)new_user = User.objects.get(email=email)diff --git a/saleor/graphql/account/tests/mutations/account/test_confirm_account.py b/saleor/graphql/account/tests/mutations/account/test_confirm_account.pyindex b89a528e13..3d6e2e14d3 100644--- a/saleor/graphql/account/tests/mutations/account/test_confirm_account.py+++ b/saleor/graphql/account/tests/mutations/account/test_confirm_account.py@@ -29,9 +29,11 @@ CONFIRM_ACCOUNT_MUTATION = """@patch("saleor.graphql.account.mutations.account.confirm_account.match_orders_with_new_user")+@patch("saleor.plugins.manager.PluginsManager.account_confirmed")def test_account_confirmation(match_orders_with_new_user_mock,assign_gift_cards_mock,+ mocked_account_confirmed,api_client,customer_user,channel_USD,@@ -52,6 +54,7 @@ def test_account_confirmation(match_orders_with_new_user_mock.assert_called_once_with(customer_user)assign_gift_cards_mock.assert_called_once_with(customer_user)assert customer_user.is_confirmed is True+ mocked_account_confirmed.assert_called_once_with(customer_user)@freeze_time("2018-05-31 12:00:01")diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4e50d216de..6ce436fd63 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1725,6 +1725,13 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""Account email change is requested."""ACCOUNT_CHANGE_EMAIL_REQUESTED+ """+ An account is confirmed.++ Added in Saleor 3.15.+ """+ ACCOUNT_CONFIRMED+"""An account delete is requested."""ACCOUNT_DELETE_REQUESTED@@ -2376,6 +2383,13 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""Account email change is requested."""ACCOUNT_CHANGE_EMAIL_REQUESTED+ """+ An account is confirmed.++ Added in Saleor 3.15.+ """+ ACCOUNT_CONFIRMED+"""An account delete is requested."""ACCOUNT_DELETE_REQUESTED@@ -3382,6 +3396,7 @@ scalar JSONStringenum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {ACCOUNT_CONFIRMATION_REQUESTEDACCOUNT_CHANGE_EMAIL_REQUESTED+ ACCOUNT_CONFIRMEDACCOUNT_DELETE_REQUESTEDADDRESS_CREATEDADDRESS_UPDATED@@ -17904,14 +17919,19 @@ type Mutation {redirectUrl: String!): SendConfirmationEmail @doc(category: "Users") @webhookEventsInfo(asyncEvents: [NOTIFY_USER, ACCOUNT_CONFIRMATION_REQUESTED], syncEvents: [])- """Confirm user account with token sent by email during registration."""+ """+ Confirm user account with token sent by email during registration.++ Triggers the following webhook events:+ - ACCOUNT_CONFIRMED (async): Account was confirmed.+ """confirmAccount("""E-mail of the user performing account confirmation."""email: String!"""A one-time token required to confirm the account."""token: String!- ): ConfirmAccount @doc(category: "Users")+ ): ConfirmAccount @doc(category: "Users") @webhookEventsInfo(asyncEvents: [ACCOUNT_CONFIRMED], syncEvents: [])"""Sets the user's password from the token sent by email using the RequestPasswordReset mutation.@@ -28109,8 +28129,13 @@ enum SendConfirmationEmailErrorCode @doc(category: "Users") {MISSING_CHANNEL_SLUG}-"""Confirm user account with token sent by email during registration."""-type ConfirmAccount @doc(category: "Users") {+"""+Confirm user account with token sent by email during registration.++Triggers the following webhook events:+- ACCOUNT_CONFIRMED (async): Account was confirmed.+"""+type ConfirmAccount @doc(category: "Users") @webhookEventsInfo(asyncEvents: [ACCOUNT_CONFIRMED], syncEvents: []) {"""An activated user account."""user: UseraccountErrors: [AccountError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")@@ -29139,6 +29164,40 @@ type AccountChangeEmailRequested implements Event @doc(category: "Users") {newEmail: String}+"""+Event sent when account is confirmed.++Added in Saleor 3.15.+"""+type AccountConfirmed 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 account delete is requested.diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex a76d47996f..7355d6e15f 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -41,6 +41,7 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED: ("Account email change is requested."),+ WebhookEventAsyncType.ACCOUNT_CONFIRMED: "An account is confirmed." + ADDED_IN_315,WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED: "An account delete is requested.",WebhookEventAsyncType.ADDRESS_CREATED: "A new address created.",WebhookEventAsyncType.ADDRESS_UPDATED: "An address updated.",diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex b070f730cb..1e18eebcb2 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -175,6 +175,14 @@ class AccountOperationBase(AbstractType):return Shop()+class AccountConfirmed(SubscriptionObjectType, AccountOperationBase):+ class Meta:+ root_type = "User"+ enable_dry_run = False+ interfaces = (Event,)+ description = "Event sent when account is confirmed." + ADDED_IN_315++class AccountConfirmationRequested(SubscriptionObjectType, AccountOperationBase):class Meta:root_type = "User"@@ -2133,6 +2141,7 @@ class ThumbnailCreated(SubscriptionObjectType):WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED: AccountConfirmationRequested,WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED: AccountChangeEmailRequested,+ WebhookEventAsyncType.ACCOUNT_CONFIRMED: AccountConfirmed,WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED: AccountDeleteRequested,WebhookEventAsyncType.ADDRESS_CREATED: AddressCreated,WebhookEventAsyncType.ADDRESS_UPDATED: AddressUpdated,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 2934c773a8..d26a8e2402 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -151,6 +151,12 @@ class BasePlugin:def __str__(self):return self.PLUGIN_NAME+ # Trigger when account is confirmed by user.+ #+ # Overwrite this method if you need to trigger specific logic after an account+ # is confirmed.+ account_confirmed: Callable[["User", None], None]+# Trigger when account confirmation is requested.## Overwrite this method if you need to trigger specific logic after an accountdiff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 4e1909118f..9fda752e05 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -1052,6 +1052,10 @@ class PluginsManager(PaymentInterface):"transaction_item_metadata_updated", default_value, transaction_item)+ def account_confirmed(self, user: "User"):+ default_value = None+ return self.__run_method_on_plugins("account_confirmed", default_value, user)+def account_confirmation_requested(self, user: "User", channel_slug: str, token: str, redirect_url: Optional[str]):diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 937f66fee0..cc548c4398 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -151,7 +151,7 @@ class WebhookPlugin(BasePlugin):metadata_updated_data, event_type, webhooks, instance, self.requestor)- def _trigger_account_event(+ def _trigger_account_request_event(self, event_type, user, channel_slug, token, redirect_url, new_email=None):if webhooks := get_webhooks_for_event(event_type):@@ -179,6 +179,28 @@ class WebhookPlugin(BasePlugin):self.requestor,)+ def _trigger_account_event(self, event_type, user):+ if webhooks := get_webhooks_for_event(event_type):+ raw_payload = {+ "id": graphene.Node.to_global_id("User", user.id),+ }+ data = {"user": user}+ trigger_webhooks_async(+ self._serialize_payload(raw_payload),+ event_type,+ webhooks,+ data,+ self.requestor,+ )++ def account_confirmed(self, user: "User", previous_value: None) -> None:+ if not self.active:+ return previous_value+ self._trigger_account_event(+ WebhookEventAsyncType.ACCOUNT_CONFIRMED,+ user,+ )+def account_confirmation_requested(self,user: "User",@@ -189,7 +211,7 @@ class WebhookPlugin(BasePlugin):) -> None:if not self.active:return previous_value- self._trigger_account_event(+ self._trigger_account_request_event(WebhookEventAsyncType.ACCOUNT_CONFIRMATION_REQUESTED,user,channel_slug,@@ -208,7 +230,7 @@ class WebhookPlugin(BasePlugin):) -> None:if not self.active:return previous_value- self._trigger_account_event(+ self._trigger_account_request_event(WebhookEventAsyncType.ACCOUNT_CHANGE_EMAIL_REQUESTED,user,channel_slug,@@ -227,7 +249,7 @@ class WebhookPlugin(BasePlugin):) -> None:if not self.active:return previous_value- self._trigger_account_event(+ self._trigger_account_request_event(WebhookEventAsyncType.ACCOUNT_DELETE_REQUESTED,user,channel_slug,diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.pyindex d543f30b89..fe1dad05ca 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_confirmed_webhook(subscription_webhook):+ return subscription_webhook(+ queries.ACCOUNT_CONFIRMED,+ WebhookEventAsyncType.ACCOUNT_CONFIRMED,+ )++@pytest.fixturedef subscription_account_change_email_requested_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 73e9dc92c6..04ce15b9e0 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py@@ -9,7 +9,15 @@ from .....graphql.shop.types import SHOP_IDfrom .....product.models import Product-def generate_account_events_payload(customer_user, channel, new_email=None):+def generate_account_events_payload(customer_user):+ payload = {+ **generate_customer_payload(customer_user),+ }++ return json.dumps(payload)+++def generate_account_requested_events_payload(customer_user, channel, new_email=None):payload = {**generate_customer_payload(customer_user),**{@@ -22,7 +30,6 @@ def generate_account_events_payload(customer_user, channel, new_email=None):"shop": {"domain": {"host": "mirumee.com", "url": "http://mirumee.com/"}},},}-if new_email:payload["newEmail"] = new_emaildiff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.pyindex 1ba66fe8d5..ae32130da8 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py@@ -27,6 +27,21 @@ ACCOUNT_CONFIRMATION_REQUESTED = (""")+ACCOUNT_CONFIRMED = (+ fragments.CUSTOMER_DETAILS+ + """+ subscription{+ event{+ ...on AccountConfirmed{+ user{+ ...CustomerDetails+ }+ }+ }+ }+"""+)+ACCOUNT_CHANGE_EMAIL_REQUESTED = (fragments.CUSTOMER_DETAILSdiff --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 9961bb755b..88ed0e7e01 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@@ -17,6 +17,7 @@ from ...tasks import create_deliveries_for_subscriptions, loggerfrom . import subscription_queriesfrom .payloads import (generate_account_events_payload,+ generate_account_requested_events_payload,generate_address_payload,generate_app_payload,generate_attribute_payload,@@ -101,7 +102,27 @@ def test_account_confirmation_requested()# then- expected_payload = generate_account_events_payload(customer_user, channel_USD)+ expected_payload = generate_account_requested_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_confirmed(customer_user, subscription_account_confirmed_webhook):+ # given+ webhooks = [subscription_account_confirmed_webhook]+ event_type = WebhookEventAsyncType.ACCOUNT_CONFIRMED++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, {"user": customer_user}, webhooks+ )++ # then+ expected_payload = generate_account_events_payload(customer_user)assert deliveries[0].payload.payload == expected_payloadassert len(deliveries) == len(webhooks)@@ -130,7 +151,7 @@ def test_account_change_email_requested()# then- expected_payload = generate_account_events_payload(+ expected_payload = generate_account_requested_events_payload(customer_user, channel_USD, new_email=new_email)assert deliveries[0].payload.payload == expected_payload@@ -158,7 +179,9 @@ def test_account_delete_requested()# then- expected_payload = generate_account_events_payload(customer_user, channel_USD)+ expected_payload = generate_account_requested_events_payload(+ customer_user, channel_USD+ )assert deliveries[0].payload.payload == expected_payloadassert len(deliveries) == len(webhooks)diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 46df36bc72..1d64548090 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -24,6 +24,7 @@ class WebhookEventAsyncType:ACCOUNT_CONFIRMATION_REQUESTED = "account_confirmation_requested"ACCOUNT_CHANGE_EMAIL_REQUESTED = "account_change_email_requested"+ ACCOUNT_CONFIRMED = "account_confirmed"ACCOUNT_DELETE_REQUESTED = "account_delete_requested"ADDRESS_CREATED = "address_created"@@ -188,6 +189,10 @@ class WebhookEventAsyncType:"name": "Account change email requested","permission": AccountPermissions.MANAGE_USERS,},+ ACCOUNT_CONFIRMED: {+ "name": "Account confirmed",+ "permission": AccountPermissions.MANAGE_USERS,+ },ACCOUNT_DELETE_REQUESTED: {"name": "Account delete requested","permission": AccountPermissions.MANAGE_USERS,