Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add order as Apollo Federation entity (#12328)
Jono Mb5312839d0a4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f9765ea1af..a5954d0d5d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add `requiredSaleorVersion` validation to `appInstall` and `appFetchManifest` mutations- Add new field `author` to `Manifest` and `App` object types - #12166 by @przlada- Add backwards compatibility for `taxCode` field - #12325 by @maarcingebala+- Support resolving `Order` as an entity in Apollo Federation - #12328 by @binary-koan### Other changes- Create order discounts for all voucher types - #12272 by @IKarbowiakdiff --git a/saleor/graphql/order/resolvers.py b/saleor/graphql/order/resolvers.pyindex ffeaa421d9..5f712027f4 100644--- a/saleor/graphql/order/resolvers.py+++ b/saleor/graphql/order/resolvers.py@@ -15,11 +15,15 @@ from ..utils.filters import filter_by_periodORDER_SEARCH_FIELDS = ("id", "discount_name", "token", "user_email", "user__email")-def resolve_orders(info, channel_slug):+def resolve_orders(+ info, channel_slug=None, requesting_user=None, requestor_has_access_to_all=False+):database_connection_name = get_database_connection_name(info.context)qs = models.Order.objects.using(database_connection_name).non_draft()if channel_slug:qs = qs.filter(channel__slug=str(channel_slug))+ if requesting_user and not requestor_has_access_to_all:+ qs = qs.filter(user_id=requesting_user.id)return qsdiff --git a/saleor/graphql/order/tests/queries/test_order_entity.py b/saleor/graphql/order/tests/queries/test_order_entity.pynew file mode 100644index 0000000000..d569fbd1f7--- /dev/null+++ b/saleor/graphql/order/tests/queries/test_order_entity.py@@ -0,0 +1,158 @@+import graphene++from .....order import OrderStatus+from .....order.models import Order+from ....tests.utils import get_graphql_content++ORDER_FEDERATION_QUERY = """+ query GetOrderInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on Order {+ id+ number+ }+ }+ }+"""+++def test_staff_query_order_by_id_for_federation(+ staff_api_client, fulfilled_order, permission_manage_orders+):+ order_id = graphene.Node.to_global_id("Order", fulfilled_order.id)+ variables = {+ "representations": [+ {+ "__typename": "Order",+ "id": order_id,+ },+ ],+ }++ response = staff_api_client.post_graphql(+ ORDER_FEDERATION_QUERY,+ variables,+ permissions=[permission_manage_orders],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [+ {+ "__typename": "Order",+ "id": order_id,+ "number": str(fulfilled_order.number),+ },+ ]+++def test_staff_query_order_by_id_without_permission_for_federation(+ staff_api_client, fulfilled_order+):+ fulfilled_order_id = graphene.Node.to_global_id("Order", fulfilled_order.id)+ variables = {+ "representations": [+ {+ "__typename": "Order",+ "id": fulfilled_order_id,+ },+ ],+ }++ response = staff_api_client.post_graphql(ORDER_FEDERATION_QUERY, variables)+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [None]+++def test_customer_query_own_orders_for_federation(+ user_api_client, customer_user, order_list+):+ order_unfulfilled = order_list[0]+ order_unfulfilled.user = customer_user++ order_unconfirmed = order_list[1]+ order_unconfirmed.status = OrderStatus.UNCONFIRMED+ order_unconfirmed.user = customer_user++ order_draft = order_list[2]+ order_draft.status = OrderStatus.DRAFT+ order_draft.user = customer_user++ Order.objects.bulk_update(+ [order_unconfirmed, order_draft, order_unfulfilled], ["user", "status"]+ )++ order_unfulfilled_id = graphene.Node.to_global_id("Order", order_unfulfilled.id)+ order_unconfirmed_id = graphene.Node.to_global_id("Order", order_unconfirmed.id)+ order_draft_id = graphene.Node.to_global_id("Order", order_draft.id)+ variables = {+ "representations": [+ {+ "__typename": "Order",+ "id": order_unfulfilled_id,+ },+ {+ "__typename": "Order",+ "id": order_unconfirmed_id,+ },+ {+ "__typename": "Order",+ "id": order_draft_id,+ },+ ],+ }++ response = user_api_client.post_graphql(+ ORDER_FEDERATION_QUERY,+ variables,+ )+ content = get_graphql_content(response)++ assert content["data"]["_entities"] == [+ {+ "__typename": "Order",+ "id": order_unfulfilled_id,+ "number": str(order_unfulfilled.number),+ },+ {+ "__typename": "Order",+ "id": order_unconfirmed_id,+ "number": str(order_unconfirmed.number),+ },+ # Users without permission cannot see draft orders+ None,+ ]+++def test_customer_query_order_without_permission_for_federation(+ user2_api_client, fulfilled_order+):+ fulfilled_order_id = graphene.Node.to_global_id("Order", fulfilled_order.id)+ variables = {+ "representations": [+ {+ "__typename": "Order",+ "id": fulfilled_order_id,+ },+ ],+ }++ response = user2_api_client.post_graphql(ORDER_FEDERATION_QUERY, variables)+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [None]+++def test_unauthenticated_query_order_for_federation(api_client, fulfilled_order):+ fulfilled_order_id = graphene.Node.to_global_id("Order", fulfilled_order.id)+ variables = {+ "representations": [+ {+ "__typename": "Order",+ "id": fulfilled_order_id,+ },+ ],+ }++ response = api_client.post_graphql(ORDER_FEDERATION_QUERY, variables)+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [None]diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex ce06ece66c..beb71dc7cb 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -15,6 +15,9 @@ from ...core.anonymize import obfuscate_address, obfuscate_emailfrom ...core.prices import quantize_pricefrom ...discount import OrderDiscountTypefrom ...graphql.checkout.types import DeliveryMethod+from ...graphql.core.federation.entities import federated_entity+from ...graphql.core.federation.resolvers import resolve_federation_references+from ...graphql.order.resolvers import resolve_ordersfrom ...graphql.utils import get_user_or_app_from_contextfrom ...graphql.warehouse.dataloaders import StockByIdLoader, WarehouseByIdLoaderfrom ...order import OrderStatus, calculations, models@@ -867,6 +870,7 @@ class OrderLine(ModelObjectType[models.OrderLine]):return resolve_metadata(root.tax_class_private_metadata)+@federated_entity("id")class Order(ModelObjectType[models.Order]):id = graphene.GlobalID(required=True)created = graphene.DateTime(required=True)@@ -1828,6 +1832,24 @@ class Order(ModelObjectType[models.Order]):return graphene.Node.to_global_id("Checkout", root.checkout_token)return None+ @staticmethod+ def __resolve_references(roots: List["Order"], info):+ requestor = get_user_or_app_from_context(info.context)+ requestor_has_access_to_all = has_one_of_permissions(+ requestor, [OrderPermissions.MANAGE_ORDERS]+ )++ if requestor:+ qs = resolve_orders(+ info,+ requestor_has_access_to_all=requestor_has_access_to_all,+ requesting_user=info.context.user,+ )+ else:+ qs = models.Order.objects.none()++ return resolve_federation_references(Order, roots, qs)+class OrderCountableConnection(CountableConnection):class Meta:diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a5914f2889..bbbb23369f 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -27641,7 +27641,7 @@ union TaxSourceLine = CheckoutLine | OrderLinescalar _Any"""_Entity union as defined by Federation spec."""-union _Entity = App | Address | User | Group | ProductVariant | Product | ProductType | ProductMedia | Category | Collection | PageType+union _Entity = App | Address | User | Group | ProductVariant | Product | ProductType | ProductMedia | Category | Collection | PageType | Order"""_Service manifest as defined by Federation spec."""type _Service {