Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Implemented new customer events (account creation, data change, ...)
NyanKiyoshi7308a99fabd3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1abd7d097b..5490402770 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,8 +13,20 @@ All notable, unreleased changes to this project will be documented in this file.- Order Events containing order lines or fulfillment lines now return the line object in the GraphQL API - #4114 by @NyanKiyoshi- Implement events for customers in backend for the customers actions:- placing an order, adding a note to an order, downloading a digital good- and getting deleted by a staff user.- #4094 by @NyanKiyoshi+ - placing an order,+ - adding a note to an order,+ - downloading a digital good,+ - asking for password reset,+ - resetting the password.++ For staff actions over customers:+ - deleting a customer,+ - assigning a new name to a customer,+ - assigning a new email to a customer,+ - adding a note to a customer,+ - deleting a customer.++ -- #4094 by @NyanKiyoshi...## 2.6.0diff --git a/docs/architecture/events.rst b/docs/architecture/events.rstindex 25e4890cef..c999a8a096 100644--- a/docs/architecture/events.rst+++ b/docs/architecture/events.rst@@ -116,56 +116,26 @@ Email Event TypesCustomer Related Events------------------------+-----------------------------+-----------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------+-| Code | GraphQL API value | Description | Additional Parameters (GraphQL) |-+-----------------------------+-----------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------+-| ``placed_order`` | ``PLACED_ORDER`` | The customer placed an order. | None. |-+-----------------------------+-----------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------+-| ``note_added_to_order`` | ``NOTE_ADDED_TO_ORDER`` | The customer added a note to one of their orders. | ``message`` (string) the message that the customer put as a note. |-+-----------------------------+-----------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------+-| ``digital_link_downloaded`` | ``DIGITAL_LINK_DOWNLOADED`` | The customer or another user (anonymous) downloaded an ordered digital good. | ``order_line`` (OrderLine) the fulfilled digital order line that the user downloaded. |-+-----------------------------+-----------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------+-| ``customer_deleted`` | ``CUSTOMER_DELETED`` | The staff user deleted one or many customers (anonymous). | ``count`` (int) the amount of customers deleted by the user. |-+-----------------------------+-----------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------+---Events Design----------------Each package representing an entity (order, account, etc.) that generate events-define both a model and a ``events.py`` file containing a set of functions-having ``_event`` for suffix.--Those functions are taking care of any logic and required fields for-creating given events.---Creating Events------------------To send an event, simply do the following:--.. code-block:: python-- from saleor.order import events-- # returns an OrderEvent- events.note_added_event(order=order, user=user, message="hello world!")--If now you want to send a 'sent email' event you would do the following:--.. code-block:: python-- from saleor.order import events-- events.email_sent_event(- order=order,- user=user,- email_type=events.OrderEventsEmails.TRACKING_UPDATED,- )--Notice how we are providing the email type.--.. note::-- The methods are using a ``model_action_event`` naming pattern.++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| Code | GraphQL API value | Description | Additional Parameters (GraphQL) |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``account_created`` | ``ACCOUNT_CREATED`` | The customer's account was created. | None. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``password_reset_link_sent`` | ``PASSWORD_RESET_LINK_SENT`` | The password reset email was sent. | None. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``password_reset`` | ``PASSWORD_RESET`` | The customer reset (changed) their password. | None. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``placed_order`` | ``PLACED_ORDER`` | The customer placed an order. | None. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``note_added_to_order`` | ``NOTE_ADDED_TO_ORDER`` | The customer added a note to one of their orders. | ``message`` (string) the message that the customer put as a note. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``digital_link_downloaded`` | ``DIGITAL_LINK_DOWNLOADED`` | The customer or another user (anonymous) downloaded an ordered digital good. | ``order_line`` (OrderLine) the fulfilled digital order line that the user downloaded. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``customer_deleted`` | ``CUSTOMER_DELETED`` | The staff user deleted one or many customers (anonymous). | ``count`` (int) the amount of customers deleted by the user. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``email_assigned`` | ``EMAIL_ASSIGNED`` | The staff user assigned a new email address to a customer. | ``message`` (string) the assigned email address. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``name_assigned`` | ``NAME_ASSIGNED`` | The staff user assigned a new full name to a customer. | ``message`` (string) the assigned full name. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------++| ``note_added`` | ``NOTE_ADDED`` | The staff user added a note to a customer. | ``message`` (string) the note added to the customer. |++------------------------------+------------------------------+------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------+diff --git a/saleor/account/__init__.py b/saleor/account/__init__.pyindex 0d3911b0f2..22db4280f6 100755--- a/saleor/account/__init__.py+++ b/saleor/account/__init__.py@@ -4,6 +4,11 @@ from django.utils.translation import pgettext_lazyclass CustomerEvents:"""The different customer event types."""+ # Account related events+ ACCOUNT_CREATED = "account_created"+ PASSWORD_RESET_LINK_SENT = "password_reset_link_sent"+ PASSWORD_RESET = "password_reset"+# Order related eventsPLACED_ORDER = "placed_order" # created an orderNOTE_ADDED_TO_ORDER = "note_added_to_order" # added a note to one of their orders@@ -11,13 +16,36 @@ class CustomerEvents:# Staff actions over customers eventsCUSTOMER_DELETED = "customer_deleted" # staff user deleted a customer+ EMAIL_ASSIGNED = "email_assigned" # the staff user assigned a email to the customer+ NAME_ASSIGNED = "name_assigned" # the staff user added set a name to the customer+ NOTE_ADDED = "note_added" # the staff user added a note to the customerCHOICES = [+ (+ ACCOUNT_CREATED,+ pgettext_lazy(+ "Event from a customer that got their account created",+ "The account account was created",+ ),+ ),+ (+ PASSWORD_RESET_LINK_SENT,+ pgettext_lazy(+ "Event from a customer that got the password reset link sent by email",+ "Password reset link was sent to the customer",+ ),+ ),+ (+ PASSWORD_RESET,+ pgettext_lazy(+ "Event from a customer that reset their password",+ "The account password was reset",+ ),+ ),(PLACED_ORDER,pgettext_lazy(- "Event from a customer that placed an order",- "An order was placed", # noqa+ "Event from a customer that placed an order", "An order was placed"),),(@@ -41,4 +69,25 @@ class CustomerEvents:"A customer was deleted",),),+ (+ NAME_ASSIGNED,+ pgettext_lazy(+ "Event from a staff user assigned a new name to a customer",+ "A customer's name was edited",+ ),+ ),+ (+ EMAIL_ASSIGNED,+ pgettext_lazy(+ "Event from a staff user assigned a new email address to a customer",+ "A customer's email address was edited",+ ),+ ),+ (+ NOTE_ADDED,+ pgettext_lazy(+ "Event from a staff user assigned a new email address to a customer",+ "A note was added to the customer",+ ),+ ),]diff --git a/saleor/account/emails.py b/saleor/account/emails.pyindex 52c6e3b7d4..21080b9c8a 100644--- a/saleor/account/emails.py+++ b/saleor/account/emails.py@@ -2,13 +2,14 @@ from django.conf import settingsfrom django.urls import reversefrom templated_email import send_templated_mail+from ..account import events as account_eventsfrom ..celeryconf import appfrom ..core.emails import get_email_base_contextfrom ..core.utils import build_absolute_uri@app.task-def send_password_reset_email(context, recipient):+def send_password_reset_email(context, recipient, user_id):reset_url = build_absolute_uri(reverse("account:reset-password-confirm",@@ -23,6 +24,7 @@ def send_password_reset_email(context, recipient):recipient_list=[recipient],context=context,)+ account_events.customer_password_reset_link_sent_event(user_id=user_id)@app.taskdiff --git a/saleor/account/events.py b/saleor/account/events.pyindex 2f3e1962f4..53b55e9a6b 100644--- a/saleor/account/events.py+++ b/saleor/account/events.py@@ -9,6 +9,22 @@ from .models import CustomerEventUserType = AbstractBaseUser+def customer_account_created_event(*, user: UserType) -> Optional[CustomerEvent]:+ return CustomerEvent.objects.create(user=user, type=CustomerEvents.ACCOUNT_CREATED)+++def customer_password_reset_link_sent_event(+ *, user_id: UserType+) -> Optional[CustomerEvent]:+ return CustomerEvent.objects.create(+ user_id=user_id, type=CustomerEvents.PASSWORD_RESET_LINK_SENT+ )+++def customer_password_reset_event(*, user: UserType) -> Optional[CustomerEvent]:+ return CustomerEvent.objects.create(user=user, type=CustomerEvents.PASSWORD_RESET)++def customer_placed_order_event(*, user: UserType, order: Order) -> Optional[CustomerEvent]:@@ -51,3 +67,36 @@ def staff_user_deleted_a_customer_event(type=CustomerEvents.CUSTOMER_DELETED,parameters={"count": deleted_count},)+++def staff_user_assigned_email_to_a_customer_event(+ *, staff_user: UserType, new_email: str+) -> CustomerEvent:+ return CustomerEvent.objects.create(+ user=staff_user,+ order=None,+ type=CustomerEvents.EMAIL_ASSIGNED,+ parameters={"message": new_email},+ )+++def staff_user_added_note_to_a_customer_event(+ *, staff_user: UserType, note: str+) -> CustomerEvent:+ return CustomerEvent.objects.create(+ user=staff_user,+ order=None,+ type=CustomerEvents.NOTE_ADDED,+ parameters={"message": note},+ )+++def staff_user_assigned_name_to_a_customer_event(+ *, staff_user: UserType, new_name: str+) -> CustomerEvent:+ return CustomerEvent.objects.create(+ user=staff_user,+ order=None,+ type=CustomerEvents.NAME_ASSIGNED,+ parameters={"message": new_name},+ )diff --git a/saleor/account/forms.py b/saleor/account/forms.pyindex b1ddf275f3..0bda00e280 100644--- a/saleor/account/forms.py+++ b/saleor/account/forms.py@@ -5,6 +5,7 @@ from django.contrib.auth import forms as django_forms, update_session_auth_hashfrom django.utils.translation import pgettext, pgettext_lazyfrom phonenumbers.phonenumberutil import country_code_for_region+from ..account import events as account_eventsfrom ..account.models import Userfrom . import emailsfrom .i18n import AddressMetaForm, get_address_form_class@@ -107,6 +108,7 @@ class SignupForm(forms.ModelForm, FormWithReCaptcha):user.set_password(password)if commit:user.save()+ account_events.customer_account_created_event(user=user)return user@@ -132,8 +134,8 @@ class PasswordResetForm(django_forms.PasswordResetForm, FormWithReCaptcha):# Passing the user object to the Celery task throws an# error "'User' is not JSON serializable". Since it's not used in our# template, we remove it from the context.- del context["user"]- emails.send_password_reset_email.delay(context, to_email)+ user = context.pop("user")+ emails.send_password_reset_email.delay(context, to_email, user.pk)class NameForm(forms.ModelForm):diff --git a/saleor/account/migrations/0027_customerevent.py b/saleor/account/migrations/0027_customerevent.pyindex a91a5d2c4f..12b2b68b5c 100644--- a/saleor/account/migrations/0027_customerevent.py+++ b/saleor/account/migrations/0027_customerevent.py@@ -39,10 +39,16 @@ class Migration(migrations.Migration):"type",models.CharField(choices=[+ ("ACCOUNT_CREATED", "account_created"),+ ("PASSWORD_RESET_LINK_SENT", "password_reset_link_sent"),+ ("PASSWORD_RESET", "password_reset"),("PLACED_ORDER", "placed_order"),("NOTE_ADDED_TO_ORDER", "note_added_to_order"),("DIGITAL_LINK_DOWNLOADED", "digital_link_downloaded"),("CUSTOMER_DELETED", "customer_deleted"),+ ("NAME_ASSIGNED", "name_assigned"),+ ("EMAIL_ASSIGNED", "email_assigned"),+ ("NOTE_ADDED", "note_added"),],max_length=255,),diff --git a/saleor/account/views.py b/saleor/account/views.pyindex dc4562a996..baa5d70284 100755--- a/saleor/account/views.py+++ b/saleor/account/views.py@@ -9,6 +9,7 @@ from django.urls import reverse, reverse_lazyfrom django.utils.translation import pgettext, ugettext_lazy as _from django.views.decorators.http import require_POST+from ..account import events as account_eventsfrom ..checkout.utils import find_and_assign_anonymous_checkoutfrom ..core.utils import get_paginator_itemsfrom .emails import send_account_delete_confirmation_email@@ -67,6 +68,11 @@ class PasswordResetConfirm(django_views.PasswordResetConfirmView):token = Noneuidb64 = None+ def form_valid(self, form):+ response = super(PasswordResetConfirm, self).form_valid(form)+ account_events.customer_password_reset_event(user=self.user)+ return response+def password_reset_confirm(request, uidb64=None, token=None):kwargs = {diff --git a/saleor/dashboard/customer/forms.py b/saleor/dashboard/customer/forms.pyindex 8bf4d285e7..7d28be62a2 100644--- a/saleor/dashboard/customer/forms.py+++ b/saleor/dashboard/customer/forms.py@@ -1,6 +1,7 @@from django import formsfrom django.utils.translation import pgettext_lazy+from ...account import events as account_eventsfrom ...account.models import CustomerNote, User@@ -69,6 +70,32 @@ class CustomerForm(forms.ModelForm):placeholder = get_name_placeholder(address.last_name)self.fields["last_name"].widget.attrs["placeholder"] = placeholder+ def save(self, commit=True):+ is_user_creation = self.instance.pk is None+ staff_user = self.user++ instance = super(CustomerForm, self).save(commit=commit) # type: User+ if is_user_creation:+ account_events.customer_account_created_event(user=instance)+ return instance++ has_new_email = "email" in self.changed_data+ has_new_name = (+ "first_name" in self.changed_data or "last_name" in self.changed_data+ )++ # Generate the events+ if has_new_email:+ account_events.staff_user_assigned_email_to_a_customer_event(+ staff_user=staff_user, new_email=instance.email+ )+ if has_new_name:+ account_events.staff_user_assigned_name_to_a_customer_event(+ staff_user=staff_user, new_name=instance.get_full_name()+ )++ return instance+class Meta:model = Userfields = ["first_name", "last_name", "email", "note", "is_active"]@@ -98,3 +125,11 @@ class CustomerNoteForm(forms.ModelForm):"Allow customers to see note toggle", "Customer can see this note"),}++ def save(self, commit=True):+ is_creation = self.instance.pk is None+ super().save(commit=commit)+ if is_creation:+ account_events.staff_user_added_note_to_a_customer_event(+ staff_user=self.instance.customer, note=self.instance.content+ )diff --git a/saleor/dashboard/customer/views.py b/saleor/dashboard/customer/views.pyindex 6ac9eafcc3..ee75364a9c 100644--- a/saleor/dashboard/customer/views.py+++ b/saleor/dashboard/customer/views.py@@ -8,7 +8,7 @@ from django.template.context_processors import csrffrom django.template.response import TemplateResponsefrom django.utils.translation import pgettext_lazy-from ...account import events as customer_events+from ...account import events as account_eventsfrom ...account.models import CustomerNote, Userfrom ...core.utils import get_paginator_itemsfrom ..emails import send_set_password_customer_email@@ -127,7 +127,7 @@ def customer_delete(request, pk):)status = 200if request.method == "POST" and form.is_valid():- customer_events.staff_user_deleted_a_customer_event(staff_user=request.user)+ account_events.staff_user_deleted_a_customer_event(staff_user=request.user)customer.delete()msg = pgettext_lazy("Dashboard message", "%(customer_name)s successfully removed"diff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.pyindex bda262b467..a831402222 100644--- a/saleor/graphql/account/mutations.py+++ b/saleor/graphql/account/mutations.py@@ -1,3 +1,5 @@+from copy import copy+import graphenefrom django.conf import settingsfrom django.contrib.auth.tokens import default_token_generator@@ -7,7 +9,7 @@ from django.utils.http import urlsafe_base64_encodefrom graphql_jwt.decorators import staff_member_requiredfrom graphql_jwt.exceptions import PermissionDenied-from ...account import emails, models, utils+from ...account import emails, events as account_events, models, utilsfrom ...account.thumbnails import create_user_avatar_thumbnailsfrom ...account.utils import get_random_avatarfrom ...checkout import AddressType@@ -39,7 +41,7 @@ def send_user_password_reset_email(user, site):"domain": site.domain,"protocol": "https" if settings.ENABLE_SSL else "http",}- emails.send_password_reset_email.delay(context, user.email)+ emails.send_password_reset_email.delay(context, user.email, user.pk)def can_edit_address(user, address):@@ -77,6 +79,7 @@ class CustomerRegister(ModelMutation):password = cleaned_input["password"]user.set_password(password)user.save()+ account_events.customer_account_created_event(user=user)class UserInput(graphene.InputObjectType):@@ -163,8 +166,13 @@ class CustomerCreate(ModelMutation, I18nMixin):default_billing_address.save()instance.default_billing_address = default_billing_address+ is_creation = instance.pk is Nonesuper().save(info, instance, cleaned_input)+ # The instance is a new object in db, create an event+ if is_creation:+ account_events.customer_account_created_event(user=instance)+if cleaned_input.get("send_password_email"):send_set_password_customer_email.delay(instance.pk)@@ -180,6 +188,54 @@ class CustomerUpdate(CustomerCreate):description = "Updates an existing customer."exclude = ["password"]model = models.User+ permissions = ("account.manage_users",)++ @classmethod+ def generate_events(+ cls, info, old_instance: models.User, new_instance: models.User+ ):+ # Retrieve the event base data+ staff_user = info.context.user+ new_email = new_instance.email+ new_fullname = new_instance.get_full_name()++ # Compare the data+ has_new_name = old_instance.get_full_name() != new_fullname+ has_new_email = old_instance.email != new_email++ # Generate the events accordingly+ if has_new_email:+ account_events.staff_user_assigned_email_to_a_customer_event(+ staff_user=staff_user, new_email=new_email+ )+ if has_new_name:+ account_events.staff_user_assigned_name_to_a_customer_event(+ staff_user=staff_user, new_name=new_fullname+ )++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ """Override the base method `perform_mutation` of ModelMutation+ to generate events by comparing the old instance with the new data."""++ # Retrieve the data+ original_instance = cls.get_instance(info, **data)+ data = data.get("input")++ # Clean the input and generate a new instance from the new data+ cleaned_input = cls.clean_input(info, original_instance, data)+ new_instance = cls.construct_instance(copy(original_instance), cleaned_input)++ # Save the new instance data+ cls.clean_instance(new_instance)+ cls.save(info, new_instance, cleaned_input)+ cls._save_m2m(info, new_instance, cleaned_input)++ # Generate events by comparing the instances+ cls.generate_events(info, original_instance, new_instance)++ # Return the response+ return cls.success_response(new_instance)class LoggedUserUpdate(CustomerCreate):@@ -353,6 +409,7 @@ class SetPassword(ModelMutation):def save(cls, info, instance, cleaned_input):instance.set_password(cleaned_input["password"])instance.save()+ account_events.customer_password_reset_event(user=instance)class PasswordReset(BaseMutation):diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.pyindex af3281811b..2b1a495489 100644--- a/saleor/graphql/account/utils.py+++ b/saleor/graphql/account/utils.py@@ -1,6 +1,6 @@from django.core.exceptions import ValidationError-from ...account import events as customer_events+from ...account import events as account_eventsclass UserDeleteMixin:@@ -28,7 +28,7 @@ class CustomerDeleteMixin(UserDeleteMixin):@classmethoddef post_process(cls, info, deleted_count=1):- customer_events.staff_user_deleted_a_customer_event(+ account_events.staff_user_deleted_a_customer_event(staff_user=info.context.user, deleted_count=deleted_count)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex db74403d3a..2f687546ee 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -888,10 +888,16 @@ type CustomerEvent implements Node {}enum CustomerEventsEnum {+ ACCOUNT_CREATED+ PASSWORD_RESET_LINK_SENT+ PASSWORD_RESETPLACED_ORDERNOTE_ADDED_TO_ORDERDIGITAL_LINK_DOWNLOADEDCUSTOMER_DELETED+ NAME_ASSIGNED+ EMAIL_ASSIGNED+ NOTE_ADDED}input CustomerFilterInput {diff --git a/saleor/order/events.py b/saleor/order/events.pyindex 7953fd6074..1dc74a09e1 100644--- a/saleor/order/events.py+++ b/saleor/order/events.py@@ -1,7 +1,7 @@from decimal import Decimalfrom typing import Dict, List, Optional, Tuple, Union-from ..account import events as customer_events+from ..account import events as account_eventsfrom ..account.models import Address, Userfrom ..order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ..payment.models import Payment@@ -94,7 +94,7 @@ def order_created_event(event_type = OrderEvents.PLACED_FROM_DRAFTelse:event_type = OrderEvents.PLACED- customer_events.customer_placed_order_event(user=user, order=order)+ account_events.customer_placed_order_event(user=user, order=order)if user.is_anonymous:user = None@@ -223,7 +223,7 @@ def fulfillment_tracking_updated_event(def order_note_added_event(*, order: Order, user: UserType, message: str) -> OrderEvent:if order.user.pk == user.pk:- customer_events.customer_added_to_note_order_event(+ account_events.customer_added_to_note_order_event(user=user, order=order, message=message)diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 164d5b7aa0..d8a7667f26 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -21,7 +21,6 @@ from versatileimagefield.fields import PPOIField, VersatileImageFieldfrom saleor.core.utils import build_absolute_uri-from ..account import events as customer_eventsfrom ..core import TaxRateTypefrom ..core.exceptions import InsufficientStockfrom ..core.models import PublishableModel, SortableModel@@ -400,18 +399,6 @@ class DigitalContentUrl(models.Model):self.token = str(uuid4()).replace("-", "")super().save(force_insert, force_update, using, update_fields)- def increment_download_count(self):- self.download_num += 1- self.save(update_fields=["download_num"])-- line = self.line- user = line.order.user if line else None-- if user is not None:- customer_events.customer_downloaded_a_digital_link_event(- user=user, order_line=line- )-def get_absolute_url(self) -> str:url = reverse("product:digital-product", kwargs={"token": str(self.token)})return build_absolute_uri(url)diff --git a/saleor/product/utils/digital_products.py b/saleor/product/utils/digital_products.pyindex e27b9c3183..259a1b4c62 100644--- a/saleor/product/utils/digital_products.py+++ b/saleor/product/utils/digital_products.py@@ -3,6 +3,7 @@ from datetime import timedeltafrom django.contrib.sites.models import Sitefrom django.utils.timezone import now+from ...account import events as account_eventsfrom ..models import DigitalContentUrl@@ -36,3 +37,16 @@ def digital_content_url_is_valid(content_url: DigitalContentUrl) -> bool:if max_downloads is not None and max_downloads <= content_url.download_num:return Falsereturn True+++def increment_download_count(self: DigitalContentUrl):+ self.download_num += 1+ self.save(update_fields=["download_num"])++ line = self.line+ user = line.order.user if line else None++ if user is not None:+ account_events.customer_downloaded_a_digital_link_event(+ user=user, order_line=line+ )diff --git a/saleor/product/views.py b/saleor/product/views.pyindex 36aba37820..922cc6d3d8 100644--- a/saleor/product/views.py+++ b/saleor/product/views.py@@ -30,7 +30,10 @@ from .utils import ()from .utils.attributes import get_product_attributes_datafrom .utils.availability import get_product_availability-from .utils.digital_products import digital_content_url_is_valid+from .utils.digital_products import (+ digital_content_url_is_valid,+ increment_download_count,+)from .utils.variants_picker import get_variant_picker_data@@ -123,7 +126,7 @@ def digital_product(request, token: str) -> Union[FileResponse, HttpResponseNotFresponse["Content-Type"] = content_typeresponse["Content-Disposition"] = "attachment; {}".format(file_expr)- content_url.increment_download_count()+ increment_download_count(content_url)return responsediff --git a/tests/api/test_account.py b/tests/api/test_account.pyindex 01399a4ec5..11955de96a 100644--- a/tests/api/test_account.py+++ b/tests/api/test_account.py@@ -13,6 +13,7 @@ from django.shortcuts import reversefrom freezegun import freeze_timefrom prices import Money+from saleor.account import events as account_eventsfrom saleor.account.models import Address, Userfrom saleor.checkout import AddressTypefrom saleor.graphql.account.mutations import (@@ -535,7 +536,7 @@ def test_customer_register(user_api_client):content = get_graphql_content(response)data = content["data"]["customerRegister"]assert not data["errors"]- assert User.objects.filter(email=email).exists()+ new_user = User.objects.get(email=email)response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response)@@ -544,6 +545,10 @@ def test_customer_register(user_api_client):assert data["errors"][0]["field"] == "email"assert data["errors"][0]["message"] == ("User with this Email already exists.")+ customer_creation_event = account_events.CustomerEvent.objects.get()+ assert customer_creation_event.type == account_events.CustomerEvents.ACCOUNT_CREATED+ assert customer_creation_event.user == new_user+@patch("saleor.dashboard.emails.send_set_password_customer_email.delay")def test_customer_create(@@ -610,11 +615,11 @@ def test_customer_create(content = get_graphql_content(response)User = get_user_model()- customer = User.objects.get(email=email)+ new_customer = User.objects.get(email=email)shipping_address, billing_address = (- customer.default_shipping_address,- customer.default_billing_address,+ new_customer.default_shipping_address,+ new_customer.default_billing_address,)assert shipping_address == addressassert billing_address == address@@ -632,11 +637,15 @@ def test_customer_create(assert send_set_password_customer_email_mock.call_count == 1args, kwargs = send_set_password_customer_email_mock.call_argscall_pk = args[0]- assert call_pk == customer.pk+ assert call_pk == new_customer.pk++ customer_creation_event = account_events.CustomerEvent.objects.get()+ assert customer_creation_event.type == account_events.CustomerEvents.ACCOUNT_CREATED+ assert customer_creation_event.user == new_customerdef test_customer_update(- staff_api_client, customer_user, address, permission_manage_users+ staff_api_client, staff_user, customer_user, address, permission_manage_users):query = """mutation UpdateCustomer(@@ -679,7 +688,7 @@ def test_customer_update(billing_address_pk = customer_user.default_billing_address.pkshipping_address_pk = customer_user.default_shipping_address.pk- id = graphene.Node.to_global_id("User", customer_user.id)+ user_id = graphene.Node.to_global_id("User", customer_user.id)first_name = "new_first_name"last_name = "new_last_name"note = "Test update note"@@ -689,7 +698,7 @@ def test_customer_update(address_data["streetAddress1"] = new_street_addressvariables = {- "id": id,+ "id": user_id,"firstName": first_name,"lastName": last_name,"isActive": False,@@ -723,6 +732,93 @@ def test_customer_update(assert data["user"]["note"] == noteassert not data["user"]["isActive"]+ # The name was changed, an event should have been triggered+ name_changed_event = account_events.CustomerEvent.objects.get()+ assert name_changed_event.type == account_events.CustomerEvents.NAME_ASSIGNED+ assert name_changed_event.user.pk == staff_user.pk+ assert name_changed_event.parameters == {"message": customer.get_full_name()}+++def test_customer_update_generates_event_when_changing_email(+ staff_api_client, staff_user, customer_user, address, permission_manage_users+):+ query = """+ mutation UpdateCustomer(+ $id: ID!, $firstName: String, $lastName: String, $email: String) {+ customerUpdate(id: $id, input: {+ firstName: $firstName,+ lastName: $lastName,+ email: $email+ }) {+ errors {+ field+ message+ }+ }+ }+ """++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ address_data = convert_dict_keys_to_camel_case(address.as_data())++ new_street_address = "Updated street address"+ address_data["streetAddress1"] = new_street_address++ variables = {+ "id": user_id,+ "firstName": customer_user.first_name,+ "lastName": customer_user.last_name,+ "email": "[email protected]",+ }+ staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )++ # The email was changed, an event should have been triggered+ email_changed_event = account_events.CustomerEvent.objects.get()+ assert email_changed_event.type == account_events.CustomerEvents.EMAIL_ASSIGNED+ assert email_changed_event.user.pk == staff_user.pk+ assert email_changed_event.parameters == {"message": "[email protected]"}+++def test_customer_update_without_any_changes_generates_no_event(+ staff_api_client, customer_user, address, permission_manage_users+):+ query = """+ mutation UpdateCustomer(+ $id: ID!, $firstName: String, $lastName: String, $email: String) {+ customerUpdate(id: $id, input: {+ firstName: $firstName,+ lastName: $lastName,+ email: $email+ }) {+ errors {+ field+ message+ }+ }+ }+ """++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ address_data = convert_dict_keys_to_camel_case(address.as_data())++ new_street_address = "Updated street address"+ address_data["streetAddress1"] = new_street_address++ variables = {+ "id": user_id,+ "firstName": customer_user.first_name,+ "lastName": customer_user.last_name,+ "email": customer_user.email,+ }+ staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )++ # No event should have been generated+ assert not account_events.CustomerEvent.objects.exists()+UPDATE_LOGGED_CUSTOMER_QUERY = """mutation UpdateLoggedCustomer($billing: AddressInput,@@ -782,7 +878,7 @@ def test_logged_customer_update_anonymus_user(api_client):@patch(- "saleor.graphql.account.utils.customer_events.staff_user_deleted_a_customer_event"+ "saleor.graphql.account.utils.account_events.staff_user_deleted_a_customer_event")def test_customer_delete(mocked_deletion_event,@@ -1043,6 +1139,10 @@ def test_set_password(user_api_client, customer_user):customer_user.refresh_from_db()assert customer_user.check_password(password)+ password_resent_event = account_events.CustomerEvent.objects.get()+ assert password_resent_event.type == account_events.CustomerEvents.PASSWORD_RESET+ assert password_resent_event.user == customer_user+@patch("saleor.account.emails.send_password_reset_email.delay")def test_password_reset_email(@@ -1070,8 +1170,10 @@ def test_password_reset_email(args, kwargs = send_password_reset_mock.call_argscall_context = args[0]call_email = args[1]+ call_user_pk = args[2]assert call_email == emailassert "token" in call_context+ assert call_user_pk == customer_user.pk@patch("saleor.account.emails.send_password_reset_email.delay")diff --git a/tests/api/test_account_events.py b/tests/api/test_account_events.pyindex dbe758e191..5555ca5f70 100644--- a/tests/api/test_account_events.py+++ b/tests/api/test_account_events.py@@ -73,6 +73,71 @@ def _get_event_from_graphql(staff_api_client, requested_user: User, permission)return received_events[0]+def test_account_event_customer_account_was_created(+ staff_api_client, customer_user, permission_manage_users+):+ event = account_events.customer_account_created_event(user=customer_user)+ expected_data = {+ "id": _model_to_node_id(event),+ "user": {"id": _model_to_node_id(customer_user)},+ "count": None,+ "message": None,+ "order": None,+ "orderLine": None,+ "type": account_events.CustomerEvents.ACCOUNT_CREATED.upper(),+ }++ received_data = _get_event_from_graphql(+ staff_api_client, customer_user, permission_manage_users+ )++ assert expected_data == received_data+++def test_account_event_sent_password_reset_email_to_customer_event(+ staff_api_client, customer_user, permission_manage_users+):+ event = account_events.customer_password_reset_link_sent_event(+ user_id=customer_user.pk+ )+ expected_data = {+ "id": _model_to_node_id(event),+ "user": {"id": _model_to_node_id(customer_user)},+ "count": None,+ "message": None,+ "order": None,+ "orderLine": None,+ "type": account_events.CustomerEvents.PASSWORD_RESET_LINK_SENT.upper(),+ }++ received_data = _get_event_from_graphql(+ staff_api_client, customer_user, permission_manage_users+ )++ assert expected_data == received_data+++def test_account_event_customer_reset_password_from_link_event(+ staff_api_client, customer_user, permission_manage_users+):+ event = account_events.customer_password_reset_event(user=customer_user)+ expected_data = {+ "id": _model_to_node_id(event),+ "user": {"id": _model_to_node_id(customer_user)},+ "count": None,+ "message": None,+ "order": None,+ "orderLine": None,+ "type": account_events.CustomerEvents.PASSWORD_RESET.upper(),+ }++ received_data = _get_event_from_graphql(+ staff_api_client, customer_user, permission_manage_users+ )++ assert expected_data == received_data++def test_account_event_customer_placed_order_event_resolves_properly(staff_api_client, customer_user, order_line, permission_manage_users):@@ -206,3 +271,72 @@ def test_account_invalid_or_deleted_order_line_return_null(# Ensure the data is validassert received_customer_events == [{"orderLine": None}]+++def test_account_event_staff_user_assigned_new_name_to_customer_event_resolves_properly(+ staff_api_client, staff_user, permission_manage_users+):+ event = account_events.staff_user_assigned_name_to_a_customer_event(+ staff_user=staff_user, new_name="Hello World!"+ )+ expected_data = {+ "id": _model_to_node_id(event),+ "user": {"id": _model_to_node_id(staff_user)},+ "count": None,+ "message": "Hello World!",+ "order": None,+ "orderLine": None,+ "type": account_events.CustomerEvents.NAME_ASSIGNED.upper(),+ }++ received_data = _get_event_from_graphql(+ staff_api_client, staff_user, permission_manage_users+ )++ assert expected_data == received_data+++def test_account_event_staff_user_assigned_email_to_customer_event_resolves_properly(+ staff_api_client, staff_user, permission_manage_users+):+ event = account_events.staff_user_assigned_email_to_a_customer_event(+ staff_user=staff_user, new_email="[email protected]"+ )+ expected_data = {+ "id": _model_to_node_id(event),+ "user": {"id": _model_to_node_id(staff_user)},+ "count": None,+ "message": "[email protected]",+ "order": None,+ "orderLine": None,+ "type": account_events.CustomerEvents.EMAIL_ASSIGNED.upper(),+ }++ received_data = _get_event_from_graphql(+ staff_api_client, staff_user, permission_manage_users+ )++ assert expected_data == received_data+++def test_account_event_staff_user_added_note_to_customer_event_resolves_properly(+ staff_api_client, staff_user, permission_manage_users+):+ event = account_events.staff_user_added_note_to_a_customer_event(+ staff_user=staff_user, note="New note's content!"+ )+ expected_data = {+ "id": _model_to_node_id(event),+ "user": {"id": _model_to_node_id(staff_user)},+ "count": None,+ "message": "New note's content!",+ "order": None,+ "orderLine": None,+ "type": account_events.CustomerEvents.NOTE_ADDED.upper(),+ }++ received_data = _get_event_from_graphql(+ staff_api_client, staff_user, permission_manage_users+ )++ assert expected_data == received_datadiff --git a/tests/api/test_bulk_delete.py b/tests/api/test_bulk_delete.pyindex 766c617360..27fe8db267 100644--- a/tests/api/test_bulk_delete.py+++ b/tests/api/test_bulk_delete.py@@ -237,7 +237,7 @@ def test_delete_collections(@patch(- "saleor.graphql.account.utils.customer_events.staff_user_deleted_a_customer_event"+ "saleor.graphql.account.utils.account_events.staff_user_deleted_a_customer_event")def test_delete_customers(mocked_deletion_event,diff --git a/tests/api/utils.py b/tests/api/utils.pyindex 3dfac47f11..5594a890ae 100644--- a/tests/api/utils.py+++ b/tests/api/utils.py@@ -21,7 +21,7 @@ def get_graphql_content(response):def assert_no_permission(response):content = _get_graphql_content_from_response(response)- assert "errors" in content+ assert "errors" in content, contentassert content["errors"][0]["message"] == ("You do not have permission to perform this action"), content["errors"]diff --git a/tests/dashboard/test_customer.py b/tests/dashboard/test_customer.pyindex b37883bbcb..2aa4322a10 100644--- a/tests/dashboard/test_customer.py+++ b/tests/dashboard/test_customer.py@@ -9,6 +9,7 @@ from django.utils.encoding import force_bytesfrom django.utils.http import urlsafe_base64_encodefrom templated_email import send_templated_mail+from saleor.account import events as account_eventsfrom saleor.account.models import CustomerNote, Userfrom saleor.core.utils import build_absolute_urifrom saleor.dashboard.customer.forms import (@@ -58,9 +59,13 @@ def test_add_customer_form(staff_user):user_count = User.objects.count()customer_form = CustomerForm({"email": "[email protected]"}, user=staff_user)customer_form.is_valid()- customer_form.save()+ new_customer = customer_form.save()assert User.objects.count() == user_count + 1+ event = account_events.CustomerEvent.objects.get()+ assert event.type == account_events.CustomerEvents.ACCOUNT_CREATED+ assert event.user == new_customer+def test_edit_customer_form(customer_user, staff_user):customer = customer_user@@ -75,6 +80,49 @@ def test_edit_customer_form(customer_user, staff_user):assert customer.first_name == "Jan"assert customer.last_name == "Nowak"+ event = account_events.CustomerEvent.objects.get()+ assert event.type == account_events.CustomerEvents.NAME_ASSIGNED+ assert event.user == staff_user+ assert event.parameters == {"message": customer.get_full_name()}+++def test_edit_customer_form_new_email_generates_event(customer_user, staff_user):+ customer = customer_user+ customer_form = CustomerForm(+ {+ "first_name": customer.first_name,+ "last_name": customer.last_name,+ "email": "[email protected]",+ },+ instance=customer,+ user=staff_user,+ )+ customer_form.is_valid()+ customer_form.save()+ customer.refresh_from_db()+ assert customer.email == "[email protected]"++ event = account_events.CustomerEvent.objects.get()+ assert event.type == account_events.CustomerEvents.EMAIL_ASSIGNED+ assert event.user == staff_user+ assert event.parameters == {"message": customer.email}+++def test_edit_customer_form_no_changes_generates_no_event(customer_user, staff_user):+ customer = customer_user+ customer_form = CustomerForm(+ {+ "first_name": customer.first_name,+ "last_name": customer.last_name,+ "email": customer.email,+ },+ instance=customer,+ user=staff_user,+ )+ customer_form.is_valid()+ customer_form.save()+ assert not account_events.CustomerEvent.objects.exists()+def test_add_note_to_customer(admin_user, customer_user):customer = customer_user@@ -83,6 +131,22 @@ def test_add_note_to_customer(admin_user, customer_user):note_form.is_valid()note_form.save()assert customer.notes.first().content == "test_note"+ event = account_events.CustomerEvent.objects.get()+ assert event.type == account_events.CustomerEvents.NOTE_ADDED+ assert event.user == note.customer+ assert event.parameters == {"message": "test_note"}+++def test_update_customer_note_generates_no_event(admin_user, customer_user):+ note = CustomerNote(customer=customer_user, user=admin_user)+ note.save()++ note_form = CustomerNoteForm({"content": "hello world note"}, instance=note)+ note_form.is_valid()+ note_form.save()++ assert customer_user.notes.first().content == "hello world note"+ assert not account_events.CustomerEvent.objects.exists()def test_add_note_to_customer_from_url(admin_client, customer_user):@@ -110,7 +174,7 @@ def test_view_delete_customer(admin_client, admin_user, customer_user):@patch(- "saleor.dashboard.customer.views.customer_events"+ "saleor.dashboard.customer.views.account_events"".staff_user_deleted_a_customer_event")def test_deleting_a_customer_generates_an_event(@@ -185,6 +249,18 @@ def test_add_customer_and_set_password(admin_client):new_user = User.objects.get(email=data["email"])assert new_user.has_usable_password()+ # Retrieve the events and ensure it was properly generated+ account_creation_event, password_reset_email_sent_event = (+ account_events.CustomerEvent.objects.all()+ )+ assert account_creation_event.type == account_events.CustomerEvents.ACCOUNT_CREATED+ assert account_creation_event.user.pk == new_user.pk+ assert (+ password_reset_email_sent_event.type+ == account_events.CustomerEvents.PASSWORD_RESET+ )+ assert password_reset_email_sent_event.user.pk == new_user.pk+def test_send_set_password_customer_email(customer_user, site_settings):site = site_settings.sitediff --git a/tests/test_order.py b/tests/test_order.pyindex cefd842cf6..0a5fbcbed3 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -6,7 +6,7 @@ from django.urls import reversefrom django_countries.fields import Countryfrom prices import Money, TaxedMoney-from saleor.account import events as customer_events+from saleor.account import events as account_eventsfrom saleor.account.models import Userfrom saleor.checkout.utils import create_orderfrom saleor.core.exceptions import InsufficientStock@@ -543,8 +543,8 @@ def test_add_order_note_view(order, authorized_client, customer_user):assert note_event.parameters == {"message": customer_note}# Ensure a customer event was triggered- note_event = customer_events.CustomerEvent.objects.get()- assert note_event.type == customer_events.CustomerEvents.NOTE_ADDED_TO_ORDER+ note_event = account_events.CustomerEvent.objects.get()+ assert note_event.type == account_events.CustomerEvents.NOTE_ADDED_TO_ORDERassert note_event.user == customer_userassert note_event.order == orderassert note_event.parameters == {"message": customer_note}diff --git a/tests/test_product.py b/tests/test_product.pyindex 019c7adfc0..4f7956ee10 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -13,7 +13,7 @@ from django.urls import reversefrom freezegun import freeze_timefrom prices import Money, TaxedMoney, TaxedMoneyRange-from saleor.account import events as customer_events+from saleor.account import events as account_eventsfrom saleor.checkout import utilsfrom saleor.checkout.models import Checkoutfrom saleor.checkout.utils import add_variant_to_checkout@@ -31,6 +31,7 @@ from saleor.product.utils import ()from saleor.product.utils.attributes import get_product_attributes_datafrom saleor.product.utils.availability import get_product_availability_status+from saleor.product.utils.digital_products import increment_download_countfrom saleor.product.utils.variants_picker import get_variant_picker_datafrom .utils import filter_products_by_attribute@@ -785,7 +786,7 @@ def test_digital_product_view(client, digital_content_url):# Ensure an event was generated from downloading a digital good.# The validity of this event is checked in test_digital_product_increment_download- assert customer_events.CustomerEvent.objects.exists()+ assert account_events.CustomerEvent.objects.exists()@pytest.mark.parametrize(@@ -813,17 +814,17 @@ def test_digital_product_increment_download(digital_content_url.line.save(update_fields=["user"])expected_new_download_count = digital_content_url.download_num + 1- digital_content_url.increment_download_count()+ increment_download_count(digital_content_url)assert digital_content_url.download_num == expected_new_download_countif expected_user is None:# Ensure an event was not generated from downloading a digital good# as no user could be found- assert not customer_events.CustomerEvent.objects.exists()+ assert not account_events.CustomerEvent.objects.exists()return- download_event = customer_events.CustomerEvent.objects.get()- assert download_event.type == customer_events.CustomerEvents.DIGITAL_LINK_DOWNLOADED+ download_event = account_events.CustomerEvent.objects.get()+ assert download_event.type == account_events.CustomerEvents.DIGITAL_LINK_DOWNLOADEDassert download_event.user == expected_userassert download_event.order == digital_content_url.line.orderassert download_event.parameters == {"order_line_pk": digital_content_url.line.pk}diff --git a/tests/test_registration.py b/tests/test_registration.pyindex d487e0a6d0..1455c44f48 100644--- a/tests/test_registration.py+++ b/tests/test_registration.py@@ -2,6 +2,7 @@ from django.contrib.auth import get_user_modelfrom django.contrib.auth.models import AnonymousUserfrom django.urls import reverse+from saleor.account import events as account_eventsfrom saleor.account.forms import LoginForm, SignupFormfrom .utils import get_redirect_location@@ -96,10 +97,14 @@ def test_signup_view_create_user(client, db):data = {"email": "[email protected]", "password": "password"}response = client.post(url, data)assert User.objects.count() == 1- assert User.objects.filter(email="[email protected]").exists()+ new_user = User.objects.get(email="[email protected]")redirect_location = get_redirect_location(response)assert redirect_location == reverse("home")+ event = account_events.CustomerEvent.objects.get()+ assert event.type == account_events.CustomerEvents.ACCOUNT_CREATED+ assert event.user == new_user+def test_signup_view_redirect(client, customer_user):url = reverse("account:signup")@@ -120,13 +125,18 @@ def test_signup_view_fail(client, db, customer_user):assert User.objects.count() == 1-def test_password_reset_view_post(client, db):+def test_password_reset_view_post(client, db, customer_user):url = reverse("account:reset-password")- data = {"email": "[email protected]"}+ data = {"email": customer_user.email}response = client.post(url, data)redirect_location = get_redirect_location(response)assert redirect_location == reverse("account:reset-password-done")+ # Retrieve the event and ensure it was properly generated+ event = account_events.CustomerEvent.objects.get()+ assert event.type == account_events.CustomerEvents.PASSWORD_RESET_LINK_SENT+ assert event.user == customer_user+def test_password_reset_view_get(client, db):url = reverse("account:reset-password")