Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Implement customer events to the API
NyanKiyoshia05c96eef030
diff --git a/saleor/graphql/account/enums.py b/saleor/graphql/account/enums.pyindex 757090f47b..960187ef27 100644--- a/saleor/graphql/account/enums.py+++ b/saleor/graphql/account/enums.py@@ -1,11 +1,13 @@import graphenefrom django_countries import countries+from ...account import CustomerEventsfrom ...checkout import AddressTypefrom ...graphql.core.enums import to_enumfrom ..core.utils import str_to_enumAddressTypeEnum = to_enum(AddressType, type_name="AddressTypeEnum")+CustomerEventsEnum = to_enum(CustomerEvents)CountryCodeEnum = graphene.Enum(diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.pyindex 8111715fa1..8e3d508702 100644--- a/saleor/graphql/account/types.py+++ b/saleor/graphql/account/types.py@@ -7,11 +7,15 @@ from graphql_jwt.decorators import permission_requiredfrom ...account import modelsfrom ...checkout.utils import get_user_checkoutfrom ...core.permissions import get_permissions+from ...order import models as order_modelsfrom ..checkout.types import Checkoutfrom ..core.connection import CountableDjangoObjectTypefrom ..core.fields import PrefetchingConnectionFieldfrom ..core.types import CountryDisplay, Image, PermissionDisplay+from ..core.utils import lazy_resolve+from ..shop.types import get_node_optimizedfrom ..utils import format_permissions_for_display+from .enums import CustomerEventsEnumclass AddressInput(graphene.InputObjectType):@@ -96,6 +100,54 @@ class Address(CountableDjangoObjectType):return False+class CustomerEvent(CountableDjangoObjectType):+ date = graphene.types.datetime.DateTime(+ description="Date when event happened at in ISO 8601 format."+ )+ type = CustomerEventsEnum(description="Customer event type")+ user = graphene.Field(+ lambda: User,+ id=graphene.Argument(graphene.ID),+ description="User who performed the action.",+ )+ message = graphene.String(description="Content of the event.")+ count = graphene.Int(description="Number of objects concerned by the event.")+ order = gql_optimizer.field(+ graphene.Field(+ lazy_resolve("order.types:Order"), description="The concerned order."+ ),+ model_field="order",+ )+ order_line = graphene.Field(+ lazy_resolve("order.types:OrderLine"), description="The concerned order line."+ )++ class Meta:+ description = "History log of the order."+ model = models.CustomerEvent+ interfaces = [relay.Node]+ only_fields = ["id"]++ @staticmethod+ def resolve_message(node, _info):+ return node.parameters.get("message", None)++ @staticmethod+ def resolve_count(node, _info):+ return node.parameters.get("count", None)++ @staticmethod+ def resolve_order_line(node, info):+ if "order_line_pk" in node.parameters:+ try:+ qs = order_models.OrderLine.objects+ order_line_pk = node.parameters["order_line_pk"]+ return get_node_optimized(qs, {"pk": order_line_pk}, info)+ except order_models.OrderLine.DoesNotExist:+ pass+ return None++class User(CountableDjangoObjectType):addresses = gql_optimizer.field(graphene.List(Address, description="List of all user's addresses."),@@ -107,7 +159,7 @@ class User(CountableDjangoObjectType):note = graphene.String(description="A note about the customer")orders = gql_optimizer.field(PrefetchingConnectionField(- "saleor.graphql.order.types.Order", description="List of user's orders."+ lazy_resolve("order.types:Order"), description="List of user's orders."),model_field="orders",)@@ -115,6 +167,12 @@ class User(CountableDjangoObjectType):PermissionDisplay, description="List of user's permissions.")avatar = graphene.Field(Image, size=graphene.Int(description="Size of the avatar."))+ events = gql_optimizer.field(+ graphene.List(+ CustomerEvent, description="List of events associated with the user."+ ),+ model_field="events",+ )class Meta:description = "Represents user data."@@ -154,6 +212,10 @@ class User(CountableDjangoObjectType):def resolve_note(self, _info):return self.note+ @permission_required("account.manage_users")+ def resolve_events(self, _info):+ return self.events.all()+def resolve_orders(self, info, **_kwargs):viewer = info.context.userif viewer.has_perm("order.manage_orders"):diff --git a/saleor/graphql/core/utils.py b/saleor/graphql/core/utils.pyindex cefab64b99..096fb7783b 100644--- a/saleor/graphql/core/utils.py+++ b/saleor/graphql/core/utils.py@@ -1,3 +1,6 @@+import importlib+from typing import Callable+import graphenefrom django.core.exceptions import ValidationError@@ -36,3 +39,18 @@ def from_global_id_strict_type(info, global_id, only_type, field="id"):if graphene_type != only_type:raise ValidationError({field: "Couldn't resolve to a node: %s" % global_id})return _id+++def lazy_resolve(name) -> Callable:+ """Lazy import a graphql object when facing circular imports issues.++ >>> # Request the saleor.graphql.order.types.OrderLine object+ >>> OrderLine = lazy_resolve('order.types:OrderLine')()"""++ import_name, object_name = name.split(":")++ def _lazy_resolve():+ imported_module = importlib.import_module(f"...{import_name}", package=__name__)+ return getattr(imported_module, object_name)++ return _lazy_resolvediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 593a3929cb..db74403d3a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -876,6 +876,24 @@ type CustomerDelete {user: User}+type CustomerEvent implements Node {+ id: ID!+ date: DateTime+ type: CustomerEventsEnum+ user(id: ID): User+ message: String+ count: Int+ order: Order+ orderLine: OrderLine+}++enum CustomerEventsEnum {+ PLACED_ORDER+ NOTE_ADDED_TO_ORDER+ DIGITAL_LINK_DOWNLOADED+ CUSTOMER_DELETED+}+input CustomerFilterInput {dateJoined: DateRangeInputmoneySpent: PriceRangeInput@@ -2898,6 +2916,7 @@ type User implements Node {orders(before: String, after: String, first: Int, last: Int): OrderCountableConnectionpermissions: [PermissionDisplay]avatar(size: Int): Image+ events: [CustomerEvent]}input UserAddressInput {diff --git a/saleor/order/events.py b/saleor/order/events.pyindex 31ef8de93a..2348dfce66 100644--- a/saleor/order/events.py+++ b/saleor/order/events.py@@ -216,7 +216,7 @@ def fulfillment_tracking_updated_event(def order_note_added_event(*, order: Order, user: UserType, message: str):- if not user.is_staff:+ if order.user.pk == user.pk:customer_events.customer_added_to_note_order_event(user=user, order=order, message=message)diff --git a/tests/api/test_account_events.py b/tests/api/test_account_events.pynew file mode 100644index 0000000000..5c1d7f124c--- /dev/null+++ b/tests/api/test_account_events.py@@ -0,0 +1,202 @@+import graphene++from saleor.account import events as account_events++from ..checks import events as events_checks+from .utils import get_graphql_content++QUERY_CUSTOMER_EVENTS = """+query customerEvents($customerId: ID!) {+ user(id: $customerId) {+ id+ events {+ id+ type+ date+ type+ user {+ id+ }+ message+ count+ order {+ id+ }+ orderLine {+ id+ }+ }+ }+}+"""+++def test_account_events_are_properly_restricted(+ staff_api_client, permission_manage_users, staff_user+):+ """Ensure that retrieve events of a customer is properly restricted."""++ # Retrieve the staff user's id+ customer_id = graphene.Node.to_global_id("User", staff_user.id)++ # Test both with and without proper permissions+ content = get_graphql_content(+ staff_api_client.post_graphql(+ QUERY_CUSTOMER_EVENTS,+ variables={"customerId": customer_id},+ permissions=[permission_manage_users],+ )+ )["data"]["user"]++ # Ensure the correct data is returned when the request is valid+ assert content["id"] == customer_id+ assert content["events"] == []+++def test_account_events_resolve_properly(+ staff_api_client, staff_user, customer_user, order_line, permission_manage_users+):+ """Create every possible event and attempt to resolve them and+ check if they properly returned all the expected data."""++ # Prepare test+ staff_api_client.user.user_permissions.add(permission_manage_users)+ expected_event_count = len(account_events.CustomerEvents.CHOICES)++ # Create every event+ placed_order_event = account_events.customer_placed_order_event(+ user=customer_user, order=order_line.order+ )+ note_added_event = account_events.customer_added_to_note_order_event(+ user=customer_user, order=order_line.order, message="418 - I'm a teapot."+ )+ download_event = account_events.customer_downloaded_a_digital_link_event(+ user=customer_user, order_line=order_line+ )+ customer_deleted_event = account_events.staff_user_deleted_a_customer_event(+ staff_user=staff_user, deleted_count=123+ )++ # Test data+ customer_events = [placed_order_event, note_added_event, download_event]+ staff_events = [customer_deleted_event]++ # Ensure all events were created and *will* be tested properly by the maintainers+ assert account_events.CustomerEvent.objects.count() == expected_event_count, (+ "Not all events were created or were improperly created. "+ "Please ensure you test them all."+ )++ # Retrieve the events+ received_customer_events = get_graphql_content(+ staff_api_client.post_graphql(+ QUERY_CUSTOMER_EVENTS,+ variables={+ "customerId": graphene.Node.to_global_id("User", customer_user.id)+ },+ )+ )["data"]["user"]["events"]+ received_staff_events = get_graphql_content(+ staff_api_client.post_graphql(+ QUERY_CUSTOMER_EVENTS,+ variables={"customerId": graphene.Node.to_global_id("User", staff_user.id)},+ )+ )["data"]["user"]["events"]++ # Ensure the correct count of events was returned+ assert len(received_customer_events) == len(+ customer_events+ ), "Not all expected customer events were returned"+ assert len(received_staff_events) == len(+ staff_events+ ), "Not all expected staff events were returned"++ # Ensure the events have the expected base customer event data+ for event_node, db_event_object in zip(received_customer_events, customer_events):+ events_checks.assert_is_proper_customer_event_node(event_node, db_event_object)++ # Prepare the events to check them individually+ received_customer_events = iter(received_customer_events)+ received_staff_events = iter(received_staff_events)++ # Test the order placement event+ placed_order_event = next(received_customer_events)+ events_checks.assert_additional_customer_event_node(+ placed_order_event,+ expected_count=None,+ expected_message=None,+ expected_order_line=None,+ )++ # Test the order note added event+ note_added_event = next(received_customer_events)+ events_checks.assert_additional_customer_event_node(+ note_added_event,+ expected_count=None,+ expected_message="418 - I'm a teapot.",+ expected_order_line=None,+ )++ # Test the a digital good was downloaded event+ download_event = next(received_customer_events)+ events_checks.assert_additional_customer_event_node(+ download_event,+ expected_count=None,+ expected_message=None,+ expected_order_line=order_line,+ )++ # Process the staff event: customers were deleted+ customer_deleted_event = next(received_staff_events)+ events_checks.assert_additional_customer_event_node(+ customer_deleted_event,+ expected_count=123,+ expected_message=None,+ expected_order_line=None,+ )++ # Ensure all events were tested+ assert next(received_customer_events, None) is None+ assert next(received_staff_events, None) is None+++def test_account_invalid_or_deleted_order_line_return_null(+ staff_api_client, permission_manage_users, customer_user, order_line+):+ """Ensure getting an order line does return null if it is no longer existing,+ despite the fact it *shouldn't* happen in production."""++ # Prepare test+ staff_api_client.user.user_permissions.add(permission_manage_users)++ # Create the event+ account_events.customer_downloaded_a_digital_link_event(+ user=customer_user, order_line=order_line+ )++ # Delete the line+ order_line.delete()++ # Retrieve it+ received_customer_events = get_graphql_content(+ staff_api_client.post_graphql(+ """+ query customerEvents($customerId: ID!) {+ user(id: $customerId) {+ id+ events {+ orderLine {+ id+ }+ }+ }+ }+ """,+ variables={+ "customerId": graphene.Node.to_global_id("User", customer_user.id)+ },+ )+ )["data"]["user"]["events"]++ # Ensure the data is valid+ assert received_customer_events == [{"orderLine": None}]diff --git a/tests/api/test_core.py b/tests/api/test_core.pyindex 56d32290b0..77461d40dd 100644--- a/tests/api/test_core.py+++ b/tests/api/test_core.py@@ -12,7 +12,12 @@ from saleor.graphql.core.enums import ReportingPeriodfrom saleor.graphql.core.filters import EnumFilterfrom saleor.graphql.core.mutations import BaseMutationfrom saleor.graphql.core.types import FilterInputObjectType-from saleor.graphql.core.utils import clean_seo_fields, snake_to_camel_case+from saleor.graphql.core.utils import (+ clean_seo_fields,+ lazy_resolve,+ snake_to_camel_case,+)+from saleor.graphql.order import types as order_typesfrom saleor.graphql.product import types as product_typesfrom saleor.graphql.utils import get_database_id, reporting_period_to_datefrom saleor.product.models import Product@@ -301,3 +306,7 @@ def test_verify_token_incorrect_token(api_client):response = api_client.post_graphql(MUTATION_TOKEN_VERIFY, variables)content = get_graphql_content(response)assert not content["data"]["tokenVerify"]+++def test_lazy_object_resolver():+ assert lazy_resolve("order.types:OrderLine")() is order_types.OrderLinediff --git a/tests/checks/events.py b/tests/checks/events.pyindex b66aa930ee..158c4baaaa 100644--- a/tests/checks/events.py+++ b/tests/checks/events.py@@ -1,4 +1,6 @@-from typing import List, Optional+from typing import Dict, List, Optional++import graphenefrom saleor.account import events as customer_eventsfrom saleor.account.models import User@@ -66,3 +68,45 @@ def was_digital_good_download_event_properly_generated(assert download_event.user == expected_userassert download_event.order == expected_order_line.orderassert download_event.parameters == {"order_line_pk": expected_order_line.pk}+++def assert_is_proper_customer_event_node(+ received_node: Dict, event: customer_events.CustomerEvent+):+ expected_event_id = graphene.Node.to_global_id("CustomerEvent", event.id)+ expected_user_id = graphene.Node.to_global_id("User", event.user.id)++ assert received_node["id"] == expected_event_id+ assert received_node["date"] == event.date.isoformat()+ assert received_node["type"] == event.type.upper(), f"got {received_node['type']}"+ assert received_node["user"]["id"] == expected_user_id++ if event.order is not None:+ expected_order_id = graphene.Node.to_global_id("Order", event.order.pk)+ assert received_node["order"]["id"] == expected_order_id+ else:+ assert received_node["order"] is None+++def assert_additional_customer_event_node(+ received_node: Dict,+ *,+ expected_count: Optional[int],+ expected_message: Optional[str],+ expected_order_line: Optional[customer_events.OrderLine],+):+ """This check is here to ensure every field is checked,+ that no field is *ever* forgotten to be checked."""++ assert received_node["count"] == expected_count+ assert received_node["message"] == expected_message++ received_order_line = received_node["orderLine"]+ if expected_order_line:+ expected_order_line_id = graphene.Node.to_global_id(+ "OrderLine", expected_order_line.id+ )+ assert received_order_line is not None, "expected to receive an order line"+ assert received_order_line["id"] == expected_order_line_id+ else:+ assert received_order_line is None