Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add a new field for checkouts for logged-in users (#6503)
Filip Owczarekff7b42ebad3a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 09e70af1ae..8070b84716 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@ All notable, unreleased changes to this project will be documented in this file.- Drop deprecated service accounts and webhooks API - #6431 by @maarcingebala- Add editorjs sanitizer - #6456 by @IKarbowiak- Add generic FileUpload mutation - #6470 by @IKarbowiak+- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki# 2.11.1diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.pyindex 3199d45061..e44b6f6b59 100644--- a/saleor/graphql/account/tests/test_account.py+++ b/saleor/graphql/account/tests/test_account.py@@ -621,6 +621,102 @@ def test_me_query_checkout_with_inactive_channel(user_api_client, checkout):assert not data["checkout"]+QUERY_ME_CHECKOUT_TOKENS = """+query getCheckoutTokens($channel: String) {+ me {+ checkoutTokens(channel: $channel)+ }+}+"""+++def test_me_checkout_tokens_without_channel_param(+ user_api_client, checkouts_assigned_to_customer+):+ # given+ checkouts = checkouts_assigned_to_customer++ # when+ response = user_api_client.post_graphql(QUERY_ME_CHECKOUT_TOKENS)++ # then+ content = get_graphql_content(response)+ data = content["data"]["me"]+ assert len(data["checkoutTokens"]) == len(checkouts)+ for checkout in checkouts:+ assert str(checkout.token) in data["checkoutTokens"]+++def test_me_checkout_tokens_without_channel_param_inactive_channel(+ user_api_client, channel_PLN, checkouts_assigned_to_customer+):+ # given+ channel_PLN.is_active = False+ channel_PLN.save()+ checkouts = checkouts_assigned_to_customer++ # when+ response = user_api_client.post_graphql(QUERY_ME_CHECKOUT_TOKENS)++ # then+ content = get_graphql_content(response)+ data = content["data"]["me"]+ assert str(checkouts[0].token) in data["checkoutTokens"]+ assert not str(checkouts[1].token) in data["checkoutTokens"]+++def test_me_checkout_tokens_with_channel(+ user_api_client, channel_USD, checkouts_assigned_to_customer+):+ # given+ checkouts = checkouts_assigned_to_customer++ # when+ response = user_api_client.post_graphql(+ QUERY_ME_CHECKOUT_TOKENS, {"channel": channel_USD.slug}+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["me"]+ assert str(checkouts[0].token) in data["checkoutTokens"]+ assert not str(checkouts[1].token) in data["checkoutTokens"]+++def test_me_checkout_tokens_with_inactive_channel(+ user_api_client, channel_USD, checkouts_assigned_to_customer+):+ # given+ channel_USD.is_active = False+ channel_USD.save()++ # when+ response = user_api_client.post_graphql(+ QUERY_ME_CHECKOUT_TOKENS, {"channel": channel_USD.slug}+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["me"]+ assert not data["checkoutTokens"]+++def test_me_checkout_tokens_with_not_existing_channel(+ user_api_client, checkouts_assigned_to_customer+):+ # given++ # when+ response = user_api_client.post_graphql(+ QUERY_ME_CHECKOUT_TOKENS, {"channel": "Not-existing"}+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["me"]+ assert not data["checkoutTokens"]++def test_me_with_cancelled_fulfillments(user_api_client, fulfilled_order_with_cancelled_fulfillment):diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.pyindex f818d92998..18eea8c639 100644--- a/saleor/graphql/account/types.py+++ b/saleor/graphql/account/types.py@@ -8,9 +8,11 @@ from ...checkout.utils import get_user_checkoutfrom ...core.exceptions import PermissionDeniedfrom ...core.permissions import AccountPermissions, OrderPermissionsfrom ...order import models as order_models+from ..checkout.dataloaders import CheckoutByUserAndChannelLoader, CheckoutByUserLoaderfrom ..checkout.types import Checkoutfrom ..core.connection import CountableDjangoObjectTypefrom ..core.fields import PrefetchingConnectionField+from ..core.scalars import UUIDfrom ..core.types import CountryDisplay, Image, Permissionfrom ..core.utils import from_global_id_strict_typefrom ..decorators import one_of_permissions_required, permission_required@@ -190,7 +192,18 @@ class UserPermission(Permission):class User(CountableDjangoObjectType):addresses = graphene.List(Address, description="List of all user's addresses.")checkout = graphene.Field(- Checkout, description="Returns the last open checkout of this user."+ Checkout,+ description="Returns the last open checkout of this user.",+ deprecation_reason=(+ "Use the `checkout_tokens` field to fetch the user checkouts."+ ),+ )+ checkout_tokens = graphene.List(+ graphene.NonNull(UUID),+ description="Returns the checkout UUID's assigned to this user.",+ channel=graphene.String(+ description="Slug of a channel for which the data should be returned."+ ),)gift_cards = PrefetchingConnectionField("saleor.graphql.giftcard.types.GiftCard",@@ -254,6 +267,28 @@ class User(CountableDjangoObjectType):def resolve_checkout(root: models.User, _info, **_kwargs):return get_user_checkout(root)+ @staticmethod+ def resolve_checkout_tokens(root: models.User, info, channel=None, **_kwargs):+ def return_checkout_tokens(checkouts):+ if not checkouts:+ return []+ checkout_global_ids = []+ for checkout in checkouts:+ checkout_global_ids.append(checkout.token)+ return checkout_global_ids++ if not channel:+ return (+ CheckoutByUserLoader(info.context)+ .load(root.id)+ .then(return_checkout_tokens)+ )+ return (+ CheckoutByUserAndChannelLoader(info.context)+ .load((root.id, channel))+ .then(return_checkout_tokens)+ )+@staticmethoddef resolve_gift_cards(root: models.User, info, **_kwargs):return root.gift_cards.all()diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex beff859174..54215cbe7f 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -1,5 +1,7 @@from collections import defaultdict+from django.db.models import F+from ...checkout.models import Checkout, CheckoutLinefrom ..core.dataloaders import DataLoader@@ -12,6 +14,35 @@ class CheckoutByIdLoader(DataLoader):return [checkouts.get(checkout_id) for checkout_id in keys]+class CheckoutByUserLoader(DataLoader):+ context_key = "checkout_by_user"++ def batch_load(self, keys):+ checkouts = Checkout.objects.filter(user_id__in=keys, channel__is_active=True)+ checkout_by_user_map = defaultdict(list)+ for checkout in checkouts:+ checkout_by_user_map[checkout.user_id].append(checkout)+ return [checkout_by_user_map.get(user_id) for user_id in keys]+++class CheckoutByUserAndChannelLoader(DataLoader):+ context_key = "checkout_by_user_and_channel"++ def batch_load(self, keys):+ user_ids = [key[0] for key in keys]+ channel_slugs = [key[1] for key in keys]+ checkouts = Checkout.objects.filter(+ user_id__in=user_ids,+ channel__slug__in=channel_slugs,+ channel__is_active=True,+ ).annotate(channel_slug=F("channel__slug"))+ checkout_by_user_and_channel_map = defaultdict(list)+ for checkout in checkouts:+ key = (checkout.user_id, checkout.channel_slug)+ checkout_by_user_and_channel_map[key].append(checkout)+ return [checkout_by_user_and_channel_map.get(key) for key in keys]++class CheckoutLineByIdLoader(DataLoader):context_key = "checkout_line_by_id"diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 24c403d413..9697cfd23e 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -5016,7 +5016,8 @@ type User implements Node & ObjectWithMetadata {privateMetadata: [MetadataItem]!metadata: [MetadataItem]!addresses: [Address]- checkout: Checkout+ checkout: Checkout @deprecated(reason: "Use the `checkout_tokens` field to fetch the user checkouts.")+ checkoutTokens(channel: String): [UUID!]giftCards(before: String, after: String, first: Int, last: Int): GiftCardCountableConnectionorders(before: String, after: String, first: Int, last: Int): OrderCountableConnectionpermissions: [Permission] @deprecated(reason: "Will be removed in Saleor 2.11.Use the `userPermissions` instead.")diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f40bdecc8d..5c42f44c46 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -274,6 +274,24 @@ def checkouts_list(channel_USD, channel_PLN):return [*checkouts_pln, *checkouts_usd]+def checkouts_assigned_to_customer(channel_USD, channel_PLN, customer_user):+ return Checkout.objects.bulk_create(+ [+ Checkout(+ currency=channel_USD.currency_code,+ channel=channel_USD,+ user=customer_user,+ ),+ Checkout(+ currency=channel_PLN.currency_code,+ channel=channel_PLN,+ user=customer_user,+ ),+ ]+ )++@pytest.fixturedef checkout_ready_to_complete(checkout_with_item, address, shipping_method, gift_card):checkout = checkout_with_item