Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Implement customer deletion events

NyanKiyoshi189b3f65553c
diff --git a/saleor/account/events.py b/saleor/account/events.py
index 3c5331cb7b..2c68346444 100644
--- a/saleor/account/events.py
+++ b/saleor/account/events.py
@@ -31,10 +31,21 @@ def customer_added_to_note_order_event(*, user: UserType, order: Order, message:
)
-def customer_downloaded_a_digital_link(*, user: UserType, order_line: OrderLine):
+def customer_downloaded_a_digital_link_event(*, user: UserType, order_line: OrderLine):
return _new_customer_event(
user=user,
order=order_line.order,
type=CustomerEvents.DIGITAL_LINK_DOWNLOADED,
parameters={"order_line_pk": order_line.pk},
)
+
+
+def staff_user_deleted_a_customer_event(
+ *, staff_user: UserType, deleted_count: int = 1
+):
+ return _new_customer_event(
+ user=staff_user,
+ order=None,
+ type=CustomerEvents.CUSTOMER_DELETED,
+ parameters={"count": deleted_count},
+ )
diff --git a/saleor/dashboard/customer/views.py b/saleor/dashboard/customer/views.py
index 7563754603..6ac9eafcc3 100644
--- a/saleor/dashboard/customer/views.py
+++ b/saleor/dashboard/customer/views.py
@@ -8,6 +8,7 @@ from django.template.context_processors import csrf
from django.template.response import TemplateResponse
from django.utils.translation import pgettext_lazy
+from ...account import events as customer_events
from ...account.models import CustomerNote, User
from ...core.utils import get_paginator_items
from ..emails import send_set_password_customer_email
@@ -126,6 +127,7 @@ def customer_delete(request, pk):
)
status = 200
if request.method == "POST" and form.is_valid():
+ customer_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/bulk_mutations.py b/saleor/graphql/account/bulk_mutations.py
index 5852755258..53636971f2 100644
--- a/saleor/graphql/account/bulk_mutations.py
+++ b/saleor/graphql/account/bulk_mutations.py
@@ -22,6 +22,12 @@ class CustomerBulkDelete(CustomerDeleteMixin, UserBulkDelete):
model = models.User
permissions = ("account.manage_users",)
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ count, errors = super().perform_mutation(root, info, **data)
+ cls.post_process(info, count)
+ return count, errors
+
class StaffBulkDelete(StaffDeleteMixin, UserBulkDelete):
class Meta:
diff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.py
index 091152e82f..bda262b467 100644
--- a/saleor/graphql/account/mutations.py
+++ b/saleor/graphql/account/mutations.py
@@ -218,6 +218,12 @@ class CustomerDelete(CustomerDeleteMixin, UserDelete):
class Arguments:
id = graphene.ID(required=True, description="ID of a customer to delete.")
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ results = super().perform_mutation(root, info, **data)
+ cls.post_process(info)
+ return results
+
class StaffCreate(ModelMutation):
class Arguments:
diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.py
index 501f1994cb..af3281811b 100644
--- a/saleor/graphql/account/utils.py
+++ b/saleor/graphql/account/utils.py
@@ -1,5 +1,7 @@
from django.core.exceptions import ValidationError
+from ...account import events as customer_events
+
class UserDeleteMixin:
class Meta:
@@ -24,6 +26,12 @@ class CustomerDeleteMixin(UserDeleteMixin):
if instance.is_staff:
raise ValidationError({"id": "Cannot delete a staff account."})
+ @classmethod
+ def post_process(cls, info, deleted_count=1):
+ customer_events.staff_user_deleted_a_customer_event(
+ staff_user=info.context.user, deleted_count=deleted_count
+ )
+
class StaffDeleteMixin(UserDeleteMixin):
class Meta:
diff --git a/saleor/product/views.py b/saleor/product/views.py
index c061b3eb40..aca08be780 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -130,7 +130,9 @@ def digital_product(request, token: str) -> Union[FileResponse, HttpResponseNotF
content_url.save(update_fields=["download_num"])
if user is not None:
- customer_events.customer_downloaded_a_digital_link(user=user, order_line=line)
+ customer_events.customer_downloaded_a_digital_link_event(
+ user=user, order_line=line
+ )
return response
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index 20ba9f4744..d747fc6835 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -27,6 +27,7 @@ from saleor.order.models import FulfillmentStatus, Order
from tests.api.utils import get_graphql_content
from tests.utils import create_image
+from ..checks import events as events_checks
from .utils import (
assert_no_permission,
convert_dict_keys_to_camel_case,
@@ -781,7 +782,12 @@ def test_logged_customer_update_anonymus_user(api_client):
assert_no_permission(response)
-def test_customer_delete(staff_api_client, customer_user, permission_manage_users):
+def test_customer_delete(
+ staff_api_client, staff_user, customer_user, permission_manage_users
+):
+ """Ensure deleting a customer actually deletes the customer and creates proper
+ related events"""
+
query = """
mutation CustomerDelete($id: ID!) {
customerDelete(id: $id){
@@ -805,6 +811,10 @@ def test_customer_delete(staff_api_client, customer_user, permission_manage_user
assert data["errors"] == []
assert data["user"]["id"] == customer_id
+ # Ensure the customer was properly deleted
+ # and any related event was properly triggered
+ events_checks.was_customer_properly_deleted(staff_user, customer_user)
+
def test_customer_delete_errors(customer_user, admin_user, staff_user):
info = Mock(context=Mock(user=admin_user))
diff --git a/tests/api/test_bulk_delete.py b/tests/api/test_bulk_delete.py
index ae53425f78..7abf62dbf3 100644
--- a/tests/api/test_bulk_delete.py
+++ b/tests/api/test_bulk_delete.py
@@ -18,6 +18,7 @@ from saleor.product.models import (
)
from saleor.shipping.models import ShippingMethod, ShippingZone
+from ..checks import events as events_checks
from .utils import get_graphql_content
MUTATION_DELETE_ORDER_LINES = """
@@ -234,7 +235,9 @@ def test_delete_collections(
).exists()
-def test_delete_customers(staff_api_client, user_list, permission_manage_users):
+def test_delete_customers(
+ staff_api_client, staff_user, user_list, permission_manage_users
+):
user_1, user_2, *users = user_list
query = """
@@ -254,10 +257,10 @@ def test_delete_customers(staff_api_client, user_list, permission_manage_users):
content = get_graphql_content(response)
assert content["data"]["customerBulkDelete"]["count"] == 2
- assert not User.objects.filter(
- id__in=[user.id for user in [user_1, user_2]]
- ).exists()
- assert User.objects.filter(id__in=[user.id for user in users]).count() == len(users)
+
+ # Ensure the customer was properly deleted
+ # and any related event was properly triggered
+ events_checks.were_customers_properly_deleted(staff_user, [user_1, user_2], users)
def test_delete_draft_orders(staff_api_client, order_list, permission_manage_orders):
diff --git a/tests/checks/__init__.py b/tests/checks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/checks/events.py b/tests/checks/events.py
new file mode 100644
index 0000000000..b53c842bd0
--- /dev/null
+++ b/tests/checks/events.py
@@ -0,0 +1,53 @@
+from typing import List
+
+from saleor.account import events as customer_events
+from saleor.account.models import User
+
+
+def _check_customer_deleted_event_is_valid(
+ deletion_event: customer_events.CustomerEvent,
+ staff_user: User,
+ expected_deletion_count=1,
+):
+ # Ensure the proper event data was set
+ assert deletion_event.user == staff_user
+ assert deletion_event.type == customer_events.CustomerEvents.CUSTOMER_DELETED
+ assert deletion_event.order is None
+ assert deletion_event.parameters == {"count": expected_deletion_count}
+
+
+def was_customer_properly_deleted(staff_user: User, customer_user: User):
+ """Ensure the customer was properly deleted
+ and any related event was properly triggered"""
+
+ # Ensure the user was properly deleted
+ assert not User.objects.filter(pk=customer_user.pk).exists()
+
+ # Ensure the proper event was generated
+ deletion_event = customer_events.CustomerEvent.objects.get()
+
+ # Ensure the proper event data was set
+ _check_customer_deleted_event_is_valid(deletion_event, staff_user)
+
+
+def were_customers_properly_deleted(
+ staff_user: User, deleted_customers: List[User], saved_customers: List[User]
+):
+ """Ensure given customers were properly deleted and others properly saved
+ and any related event was properly triggered"""
+
+ # Ensure the customers were properly deleted and others were preserved
+ assert not User.objects.filter(
+ id__in=[user.id for user in deleted_customers]
+ ).exists()
+ assert User.objects.filter(
+ id__in=[user.id for user in saved_customers]
+ ).count() == len(saved_customers)
+
+ # Ensure the proper event was generated
+ deletion_event = customer_events.CustomerEvent.objects.get()
+
+ # Ensure the proper event data was set for the bulk action
+ _check_customer_deleted_event_is_valid(
+ deletion_event, staff_user, len(deleted_customers)
+ )
diff --git a/tests/dashboard/test_customer.py b/tests/dashboard/test_customer.py
index d6295900dc..8912a5e2ba 100644
--- a/tests/dashboard/test_customer.py
+++ b/tests/dashboard/test_customer.py
@@ -17,6 +17,8 @@ from saleor.dashboard.customer.forms import (
)
from saleor.settings import DEFAULT_FROM_EMAIL
+from ..checks import events as events_checks
+
def test_ajax_users_list(admin_client, admin_user, customer_user):
users = sorted([admin_user, customer_user], key=lambda user: user.email)
@@ -108,9 +110,25 @@ def test_view_delete_customer(admin_client, admin_user, customer_user):
assert response.status_code == 302
+def test_deleting_a_customer_generates_an_event(
+ admin_client, admin_user, customer_user
+):
+ """Deleting a customer as a staff admin should generate an event
+ and this event should remain anonymous as a customer point of view (GDPR)."""
+
+ url = reverse("dashboard:customer-delete", args=[customer_user.pk])
+ response = admin_client.post(url, data={"csrf": "exampledata"})
+ assert response.status_code == 302
+
+ # Ensure the customer was properly deleted
+ # and any related event was properly triggered
+ events_checks.was_customer_properly_deleted(admin_user, customer_user)
+
+
def test_form_delete_customer(
staff_user, customer_user, admin_user, permission_manage_staff
):
+ # Deleting a customer with valid data should be valid
data = {"csrf": "example-data"}
form = CustomerDeleteForm(data, instance=customer_user, user=staff_user)
assert form.is_valid()
@@ -123,11 +141,12 @@ def test_form_delete_customer(
form = CustomerDeleteForm(data, instance=admin_user, user=staff_user)
assert not form.is_valid()
- # Deleting another staff is not allowed without relevant permission
+ # Deleting another staff is not allowed without relevant permissions
another_staff_user = User.objects.create(is_staff=True, email="[email protected]")
form = CustomerDeleteForm(data, instance=another_staff_user, user=staff_user)
assert not form.is_valid()
+ # Deleting another staff user is allowed with relevant permissions
staff_user.user_permissions.add(permission_manage_staff)
staff_user = User.objects.get(pk=staff_user.pk)
form = CustomerDeleteForm({}, instance=another_staff_user, user=staff_user)