Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Assign user gift cards and orders when it is possible (#8271)
Iga Karbowiak581387023829
diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.pyindex 0d59797396..a94bf90564 100644--- a/saleor/giftcard/tests/test_utils.py+++ b/saleor/giftcard/tests/test_utils.py@@ -16,6 +16,7 @@ from .. import GiftCardEvents, GiftCardLineData, eventsfrom ..models import GiftCard, GiftCardEventfrom ..utils import (add_gift_card_code_to_checkout,+ assign_user_gift_cards,calculate_expiry_date,deactivate_order_gift_cards,fulfill_gift_card_lines,@@ -662,3 +663,53 @@ def test_order_has_gift_card_lines_true(gift_card_shippable_order_line):def test_order_has_gift_card_lines_false(order):assert order_has_gift_card_lines(order) is False+++def test_assign_user_gift_cards(+ customer_user,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ gift_card_created_by_staff,+):+ # given+ card_ids = [+ card.id+ for card in [+ gift_card,+ gift_card_expiry_date,+ gift_card_created_by_staff,+ gift_card_used,+ ]+ ]+ GiftCard.objects.filter(id__in=card_ids).update(created_by=None)++ gift_card_used.used_by = None+ gift_card_used.save(update_fields=["used_by"])++ # when+ assign_user_gift_cards(customer_user)++ # then+ for card in [gift_card, gift_card_expiry_date]:+ card.refresh_from_db()+ assert card.created_by == customer_user++ gift_card_used.refresh_from_db()+ assert gift_card_used.used_by == customer_user+ assert not gift_card_used.created_by+++def test_assign_user_gift_cards_no_gift_cards_to_assign(+ customer_user, gift_card_created_by_staff+):+ # given+ gift_card_created_by_staff.created_by = None+ gift_card_created_by_staff.save(update_fields=["created_by"])++ # when+ assign_user_gift_cards(customer_user)++ # then+ gift_card_created_by_staff.refresh_from_db()+ assert not gift_card_created_by_staff.created_bydiff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex 6aeffc5ec6..71e7aff077 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -250,3 +250,8 @@ def deactivate_order_gift_cards(def order_has_gift_card_lines(order):return any(order.lines.filter(is_gift_card=True))+++def assign_user_gift_cards(user):+ GiftCard.objects.filter(used_by_email=user.email).update(used_by=user)+ GiftCard.objects.filter(created_by_email=user.email).update(created_by=user)diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.pyindex 75d2de0329..cba12f681a 100644--- a/saleor/graphql/account/mutations/account.py+++ b/saleor/graphql/account/mutations/account.py@@ -12,6 +12,8 @@ from ....core.jwt import create_token, jwt_decodefrom ....core.tokens import account_delete_token_generatorfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils.url import validate_storefront_url+from ....giftcard.utils import assign_user_gift_cards+from ....order.utils import match_orders_with_new_userfrom ....settings import JWT_TTL_REQUEST_EMAIL_CHANGEfrom ...account.enums import AddressTypeEnumfrom ...account.types import Address, AddressInput, User@@ -143,6 +145,7 @@ class AccountRegister(ModelMutation):)else:user.save()+account_events.customer_account_created_event(user=user)info.context.plugins.customer_created(customer=user)@@ -534,6 +537,9 @@ class ConfirmEmailChange(BaseMutation):data.get("channel"), error_class=AccountErrorCode).slug+ assign_user_gift_cards(user)+ match_orders_with_new_user(user)+notifications.send_user_change_email_notification(old_email, user, info.context.plugins, channel_slug=channel_slug)diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 91a2dcfe99..e792de9c39 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -15,6 +15,7 @@ from ....core.exceptions import PermissionDeniedfrom ....core.permissions import AccountPermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils.url import validate_storefront_url+from ....giftcard.utils import assign_user_gift_cardsfrom ....graphql.utils import get_user_or_app_from_contextfrom ....order.utils import match_orders_with_new_userfrom ...account.i18n import I18nMixin@@ -228,7 +229,10 @@ class ConfirmAccount(BaseMutation):user.is_active = Trueuser.save(update_fields=["is_active"])+match_orders_with_new_user(user)+ assign_user_gift_cards(user)+return ConfirmAccount(user=user)diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.pyindex 311880162a..31a3f50f02 100644--- a/saleor/graphql/account/mutations/staff.py+++ b/saleor/graphql/account/mutations/staff.py@@ -15,6 +15,8 @@ from ....core.exceptions import PermissionDeniedfrom ....core.permissions import AccountPermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils.url import validate_storefront_url+from ....giftcard.utils import assign_user_gift_cards+from ....order.utils import match_orders_with_new_userfrom ...account.enums import AddressTypeEnumfrom ...account.types import Address, AddressInput, Userfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation@@ -111,6 +113,8 @@ class CustomerUpdate(CustomerCreate):account_events.assigned_email_to_a_customer_event(staff_user=staff_user, app=app, new_email=new_email)+ assign_user_gift_cards(new_instance)+ match_orders_with_new_user(new_instance)if has_new_name:account_events.assigned_name_to_a_customer_event(staff_user=staff_user, app=app, new_name=new_fullname@@ -385,6 +389,17 @@ class StaffUpdate(StaffCreate):if remove_groups:instance.groups.remove(*remove_groups)+ @classmethod+ def perform_mutation(cls, _root, info, **data):+ instance = cls.get_instance(info, **data)+ old_email = instance.email+ response = super().perform_mutation(_root, info, **data)+ user = response.user+ if user.email != old_email:+ assign_user_gift_cards(user)+ match_orders_with_new_user(user)+ return response+class StaffDelete(StaffDeleteMixin, UserDelete):class Meta:diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.pyindex 3adf796c5b..19f3e23687 100644--- a/saleor/graphql/account/tests/test_account.py+++ b/saleor/graphql/account/tests/test_account.py@@ -1061,9 +1061,16 @@ ACCOUNT_REGISTER_MUTATION = """)@patch("saleor.account.notifications.default_token_generator.make_token")@patch("saleor.plugins.manager.PluginsManager.notify")-def test_customer_register(mocked_notify, mocked_generator, api_client, channel_PLN):+def test_customer_register(+ mocked_notify,+ mocked_generator,+ api_client,+ channel_PLN,+ order,+):mocked_generator.return_value = "token"email = "[email protected]"+redirect_url = "http://localhost:3000"variables = {"email": email,@@ -1553,6 +1560,56 @@ def test_customer_update_generates_event_when_changing_email_by_app(assert email_changed_event.parameters == {"message": "[email protected]"}+def test_customer_update_assign_gift_cards_and_orders(+ staff_api_client,+ staff_user,+ customer_user,+ address,+ gift_card,+ order,+ permission_manage_users,+):+ # given+ query = UPDATE_CUSTOMER_EMAIL_MUTATION++ 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+ new_email = "[email protected]"++ gift_card.created_by = None+ gift_card.created_by_email = new_email+ gift_card.save(update_fields=["created_by", "created_by_email"])++ order.user = None+ order.user_email = new_email+ order.save(update_fields=["user_email", "user"])++ variables = {+ "id": user_id,+ "firstName": customer_user.first_name,+ "lastName": customer_user.last_name,+ "email": new_email,+ }++ # when+ staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )++ # then+ email_changed_event = account_events.CustomerEvent.objects.get()+ assert email_changed_event.type == account_events.CustomerEvents.EMAIL_ASSIGNED+ gift_card.refresh_from_db()+ customer_user.refresh_from_db()+ assert gift_card.created_by == customer_user+ assert gift_card.created_by_email == customer_user.email+ order.refresh_from_db()+ assert order.user == customer_user++ACCOUNT_UPDATE_QUERY = """mutation accountUpdate($billing: AddressInput@@ -2831,6 +2888,45 @@ def test_staff_update_deactivate_with_manage_staff_all_perms_manageable(assert staff_user1.is_active is False+def test_staff_update_update_email_assign_gift_cards_and_orders(+ staff_api_client, permission_manage_staff, gift_card, order+):+ # given+ query = STAFF_UPDATE_MUTATIONS+ staff_user = User.objects.create(email="[email protected]", is_staff=True)++ new_email = "[email protected]"++ gift_card.created_by = None+ gift_card.created_by_email = new_email+ gift_card.save(update_fields=["created_by", "created_by_email"])++ order.user = None+ order.user_email = new_email+ order.save(update_fields=["user_email", "user"])++ id = graphene.Node.to_global_id("User", staff_user.id)+ variables = {"id": id, "input": {"email": new_email}}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_staff]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["staffUpdate"]+ assert data["errors"] == []+ assert data["user"]["userPermissions"] == []+ assert data["user"]["email"] == new_email+ gift_card.refresh_from_db()+ staff_user.refresh_from_db()+ assert gift_card.created_by == staff_user+ assert gift_card.created_by_email == staff_user.email+ order.refresh_from_db()+ assert order.user == staff_user++STAFF_DELETE_MUTATION = """mutation DeleteStaff($id: ID!) {staffDelete(id: $id) {@@ -3762,9 +3858,14 @@ def test_account_reset_password(@freeze_time("2018-05-31 12:00:01")+@patch("saleor.graphql.account.mutations.base.assign_user_gift_cards")@patch("saleor.graphql.account.mutations.base.match_orders_with_new_user")def test_account_confirmation(- match_orders_with_new_user_mock, api_client, customer_user, channel_USD+ match_orders_with_new_user_mock,+ assign_gift_cards_mock,+ api_client,+ customer_user,+ channel_USD,):customer_user.is_active = Falsecustomer_user.save()@@ -3780,13 +3881,19 @@ def test_account_confirmation(assert content["data"]["confirmAccount"]["user"]["email"] == customer_user.emailcustomer_user.refresh_from_db()match_orders_with_new_user_mock.assert_called_once_with(customer_user)+ assign_gift_cards_mock.assert_called_once_with(customer_user)assert customer_user.is_active is True@freeze_time("2018-05-31 12:00:01")+@patch("saleor.graphql.account.mutations.base.assign_user_gift_cards")@patch("saleor.graphql.account.mutations.base.match_orders_with_new_user")def test_account_confirmation_invalid_user(- match_orders_with_new_user_mock, user_api_client, customer_user, channel_USD+ match_orders_with_new_user_mock,+ assign_gift_cards_mock,+ user_api_client,+ customer_user,+ channel_USD,):variables = {"email": "[email protected]",@@ -3801,11 +3908,17 @@ def test_account_confirmation_invalid_user(== AccountErrorCode.NOT_FOUND.name)match_orders_with_new_user_mock.assert_not_called()+ assign_gift_cards_mock.assert_not_called()+@patch("saleor.graphql.account.mutations.base.assign_user_gift_cards")@patch("saleor.graphql.account.mutations.base.match_orders_with_new_user")def test_account_confirmation_invalid_token(- match_orders_with_new_user_mock, user_api_client, customer_user, channel_USD+ match_orders_with_new_user_mock,+ assign_gift_cards_mock,+ user_api_client,+ customer_user,+ channel_USD,):variables = {"email": customer_user.email,@@ -3820,6 +3933,7 @@ def test_account_confirmation_invalid_token(== AccountErrorCode.INVALID.name)match_orders_with_new_user_mock.assert_not_called()+ assign_gift_cards_mock.assert_not_called()@freeze_time("2018-05-31 12:00:01")@@ -5041,7 +5155,15 @@ mutation emailUpdate($token: String!, $channel: String) {"""-def test_email_update(user_api_client, customer_user, channel_PLN):+@patch("saleor.graphql.account.mutations.account.match_orders_with_new_user")+@patch("saleor.graphql.account.mutations.account.assign_user_gift_cards")+def test_email_update(+ assign_gift_cards_mock,+ assign_orders_mock,+ user_api_client,+ customer_user,+ channel_PLN,+):new_email = "[email protected]"payload = {"old_email": customer_user.email,@@ -5056,6 +5178,8 @@ def test_email_update(user_api_client, customer_user, channel_PLN):content = get_graphql_content(response)data = content["data"]["confirmEmailChange"]assert data["user"]["email"] == new_email+ assign_gift_cards_mock.assert_called_once_with(customer_user)+ assign_orders_mock.assert_called_once_with(customer_user)def test_email_update_to_existing_email(user_api_client, customer_user, staff_user):diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex 8c65b32ca7..6d911b4c2f 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -120,18 +120,28 @@ def test_change_quantity_update_line_fields(assert line.undiscounted_total_price == line.undiscounted_unit_price * new_quantity-def test_match_orders_with_new_user(customer_user, channel_USD):- address = customer_user.default_billing_address.get_copy()- order = Order.objects.create(- billing_address=address,- user=None,- user_email=customer_user.email,- channel=channel_USD,- )+def test_match_orders_with_new_user(order_list, staff_user, customer_user):+ # given+ for order in order_list[:2]:+ order.user = None+ order.user_email = staff_user.email- match_orders_with_new_user(customer_user)- order.refresh_from_db()- assert order.user == customer_user+ order_with_user = order_list[-1]+ order_with_user.user = customer_user+ order_with_user.user_email = staff_user.email++ Order.objects.bulk_update(order_list, ["user", "user_email"])++ # when+ match_orders_with_new_user(staff_user)++ # then+ for order in order_list[:2]:+ order.refresh_from_db()+ assert order.user == staff_user++ order_with_user.refresh_from_db()+ assert order_with_user.user != staff_userdef test_match_draft_order_with_new_user(customer_user, channel_USD):@@ -286,6 +296,64 @@ def test_add_gift_cards_to_order():# givencheckout = checkout_with_item+ checkout.user = staff_user+ checkout.gift_cards.add(gift_card, gift_card_expiry_date)+ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)++ # when+ add_gift_cards_to_order(+ checkout_info, order, Money(20, gift_card.currency), staff_user, None+ )++ # then+ gift_card.refresh_from_db()+ gift_card_expiry_date.refresh_from_db()+ assert gift_card.current_balance_amount == 0+ assert gift_card_expiry_date.current_balance_amount == 0+ assert gift_card.used_by == staff_user+ assert gift_card.used_by_email == staff_user.email++ gift_card_events = GiftCardEvent.objects.filter(gift_card_id=gift_card.id)+ assert gift_card_events.count() == 1+ gift_card_event = gift_card_events[0]+ assert gift_card_event.type == GiftCardEvents.USED_IN_ORDER+ assert gift_card_event.user == staff_user+ assert gift_card_event.app is None+ assert gift_card_event.parameters == {+ "balance": {+ "currency": "USD",+ "current_balance": "0",+ "old_current_balance": "10.000",+ },+ "order_id": order.id,+ }++ order_created_event = GiftCardEvent.objects.get(+ gift_card_id=gift_card_expiry_date.id+ )+ assert order_created_event.user == staff_user+ assert order_created_event.app is None+ assert order_created_event.parameters == {+ "balance": {+ "currency": "USD",+ "current_balance": "0",+ "old_current_balance": "20.000",+ },+ "order_id": order.id,+ }+++def test_add_gift_cards_to_order_no_checkout_user(+ checkout_with_item, gift_card, gift_card_expiry_date, order, staff_user+):+ # given+ checkout = checkout_with_item+ checkout.user = None+ checkout.email = staff_user.email+ checkout.save(update_fields=["user", "email"])+checkout.gift_cards.add(gift_card, gift_card_expiry_date)manager = get_plugins_manager()lines = fetch_checkout_lines(checkout)@@ -301,6 +369,8 @@ def test_add_gift_cards_to_order(gift_card_expiry_date.refresh_from_db()assert gift_card.current_balance_amount == 0assert gift_card_expiry_date.current_balance_amount == 0+ assert gift_card.used_by == staff_user+ assert gift_card.used_by_email == staff_user.emailgift_card_events = GiftCardEvent.objects.filter(gift_card_id=gift_card.id)assert gift_card_events.count() == 1diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 0dc740f579..ee17b406e3 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -462,7 +462,11 @@ def set_gift_card_user():"""Set user when the gift card is used for the first time."""if gift_card.used_by_email is None:- gift_card.used_by = used_by_user+ gift_card.used_by = (+ used_by_user+ if used_by_user+ else User.objects.filter(email=used_by_email).first()+ )gift_card.used_by_email = used_by_email