Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow to add a gift card to a checkout without email (#13019)
Tomasz Szymański2c44b8eccc2c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 04a649fc3f..389774c289 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ All notable, unreleased changes to this project will be documented in this file.### Breaking changes+- Gift cards can now be applied on a checkout without an email, fields `used_by` and `used_by_email` on GiftCard model are deprecated and will be removed in 4.0. - #13019 by @tomaszszymanski129- The `ProductBulkCreateError.path` field for errors related to product variants input in the `productBulkCreate` mutation will now return more detailed error paths, e.g. `variants.1.stocks.0.warehouse` instead of `variants.1.warehouses` - #12534 by @SzymJ- The `discounts` field has been removed from the listed plugin manager methods. Instead of the `discounts` argument, an applied `discount` is now assigned to each line in the `CheckoutLineInfo` inside the `CheckoutInfo` object. - #11934 by @fowczarekdiff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.pyindex 51fd3fb8a5..fd7b76c620 100644--- a/saleor/giftcard/tests/test_utils.py+++ b/saleor/giftcard/tests/test_utils.py@@ -49,6 +49,17 @@ def test_add_gift_card_code_to_checkout(checkout, gift_card):assert checkout.gift_cards.count() == 1+def test_add_gift_card_code_to_checkout_without_email(checkout, gift_card):+ # given+ assert checkout.gift_cards.count() == 0++ # when+ add_gift_card_code_to_checkout(checkout, None, gift_card.code, gift_card.currency)++ # then+ assert checkout.gift_cards.count() == 1++def test_add_gift_card_code_to_checkout_inactive_card(checkout, gift_card):# givengift_card.is_active = False@@ -111,23 +122,6 @@ def test_add_gift_card_code_to_checkout_used_gift_card(checkout, gift_card_used)assert checkout.gift_cards.count() == 1-def test_add_gift_card_code_to_checkout_used_gift_card_invalid_user(- checkout, gift_card_used-):- # given- email = "[email protected]"- assert gift_card_used.used_by_email- assert gift_card_used.used_by_email != email- assert checkout.gift_cards.count() == 0-- # when- # then- with pytest.raises(InvalidPromoCode):- add_gift_card_code_to_checkout(- checkout, email, gift_card_used.code, gift_card_used.currency- )--def test_remove_gift_card_code_from_checkout(checkout, gift_card):# givencheckout.gift_cards.add(gift_card)diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex d82483e54c..f360830ff6 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -38,10 +38,6 @@ def add_gift_card_code_to_checkout(Raise ValidationError if email is not provided.Raise InvalidPromoCode if gift card cannot be applied."""- from ..checkout.checkout_cleaner import validate_checkout_email-- validate_checkout_email(checkout)-try:# only active gift card with currency the same as channel currency can be usedgift_card = (@@ -52,11 +48,6 @@ def add_gift_card_code_to_checkout(except GiftCard.DoesNotExist:raise InvalidPromoCode()- used_by_email = gift_card.used_by_email- # gift card can be used only by one user- if used_by_email and used_by_email != email:- raise InvalidPromoCode()-checkout.gift_cards.add(gift_card)checkout.save(update_fields=["last_change"])@@ -66,8 +57,7 @@ def remove_gift_card_code_from_checkout(checkout: Checkout, gift_card_code: str)Return information whether promo code was removed."""- gift_card = checkout.gift_cards.filter(code=gift_card_code).first()- if gift_card:+ if gift_card := checkout.gift_cards.filter(code=gift_card_code).first():checkout.gift_cards.remove(gift_card)checkout.save(update_fields=["last_change"])return Truediff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.pyindex 1a8111e658..254e12ec43 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py@@ -789,28 +789,6 @@ def test_checkout_add_used_gift_card_code()-def test_checkout_add_used_gift_card_code_invalid_user(- staff_api_client, checkout_with_item, gift_card_used, staff_user-):- # given- checkout_with_item.user = staff_user- assert gift_card_used.used_by_email != checkout_with_item.user.email-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card_used.code,- }-- # when- data = _mutate_checkout_add_promo_code(staff_api_client, variables)-- # then- assert not data["checkout"]- assert len(data["errors"]) == 1- assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID.name- assert data["errors"][0]["field"] == "promoCode"--def test_checkout_get_total_with_gift_card(api_client, checkout_with_item, gift_card):manager = get_plugins_manager()lines, _ = fetch_checkout_lines(checkout_with_item)@@ -1016,10 +994,31 @@ def test_checkout_add_gift_card_without_checkout_email(# givencheckout_with_item.email = Nonecheckout_with_item.save(update_fields=["email"])+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card.code,+ }- gift_card.expiry_date = date.today() - timedelta(days=1)- gift_card.save()+ # when+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # then+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert data["checkout"]["giftCards"][0]["id"] == gift_card_id+ assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_code++def test_checkout_add_gift_card_without_checkout_email_used_by_someone_else_email(+ api_client, checkout_with_item, gift_card+):+ # given+ checkout_with_item.email = None+ checkout_with_item.save(update_fields=["email"])+ gift_card.used_by_email = "[email protected]"+ gift_card.save(update_fields=["used_by_email"])+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)variables = {"id": to_global_id_or_none(checkout_with_item),"promoCode": gift_card.code,@@ -1029,8 +1028,34 @@ def test_checkout_add_gift_card_without_checkout_email(data = _mutate_checkout_add_promo_code(api_client, variables)# then- assert data["errors"]- assert data["errors"][0]["code"] == CheckoutErrorCode.EMAIL_NOT_SET.name+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert data["checkout"]["giftCards"][0]["id"] == gift_card_id+ assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_code+++def test_checkout_add_gift_card_without_checkout_email_used_by_other_user(+ api_client, checkout_with_item, gift_card, customer_user+):+ # given+ checkout_with_item.email = None+ checkout_with_item.save(update_fields=["email"])+ gift_card.used_by = customer_user+ gift_card.save(update_fields=["used_by"])+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # then+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert data["checkout"]["giftCards"][0]["id"] == gift_card_id+ assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_code@pytest.mark.parametrize("shipping_price", [12, 10, 5])diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card.py b/saleor/graphql/giftcard/tests/queries/test_gift_card.pyindex 55f30fac39..e044c945e7 100644--- a/saleor/graphql/giftcard/tests/queries/test_gift_card.py+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card.py@@ -229,33 +229,6 @@ def test_query_gift_card_by_customer(assert_no_permission(response)-def test_query_used_gift_card_no_permission(- staff_api_client,- gift_card_used,- permission_manage_gift_card,- permission_manage_users,- permission_manage_apps,-):- # given- query = QUERY_GIFT_CARD_BY_ID- gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card_used.pk)- variables = {"id": gift_card_id}-- # when- response = staff_api_client.post_graphql(- query,- variables,- permissions=[- permission_manage_gift_card,- permission_manage_users,- permission_manage_apps,- ],- )-- # then- assert_no_permission(response)--def test_query_used_gift_card_by_owner(staff_api_client,gift_card_used,diff --git a/saleor/graphql/giftcard/types.py b/saleor/graphql/giftcard/types.pyindex 88bb469b80..f270e52f68 100644--- a/saleor/graphql/giftcard/types.py+++ b/saleor/graphql/giftcard/types.py@@ -250,6 +250,7 @@ class GiftCard(ModelObjectType[models.GiftCard]):used_by = graphene.Field("saleor.graphql.account.types.User",description=("The customer who used a gift card." + ADDED_IN_31),+ deprecation_reason=DEPRECATED_IN_3X_FIELD,)created_by_email = graphene.String(required=False,@@ -266,6 +267,7 @@ class GiftCard(ModelObjectType[models.GiftCard]):description=("Email address of the customer who used a gift card." + ADDED_IN_31),+ deprecation_reason=DEPRECATED_IN_3X_FIELD,)last_used_on = graphene.DateTime()expiry_date = Date()@@ -345,15 +347,12 @@ class GiftCard(ModelObjectType[models.GiftCard]):@staticmethoddef resolve_code(root: models.GiftCard, info):def _resolve_code(user):- requestor = get_user_or_app_from_context(info.context)# Gift card code can be fetched by the staff user and app# with manage gift card permission and by the card owner.- if requestor:+ if requestor := get_user_or_app_from_context(info.context):requestor_is_an_owner = user and requestor == user- card_already_used = bool(root.used_by_email)- if requestor_is_an_owner or (- not card_already_used- and requestor.has_perm(GiftcardPermissions.MANAGE_GIFT_CARD)+ if requestor_is_an_owner or requestor.has_perm(+ GiftcardPermissions.MANAGE_GIFT_CARD):return root.codediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex c8996d9da8..d34e966803 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -9784,7 +9784,7 @@ type GiftCard implements Node & ObjectWithMetadata @doc(category: "Gift cards")Added in Saleor 3.1."""- usedBy: User+ usedBy: User @deprecated(reason: "This field will be removed in Saleor 4.0.")"""Email address of the user who bought or issued gift card.@@ -9800,7 +9800,7 @@ type GiftCard implements Node & ObjectWithMetadata @doc(category: "Gift cards")Added in Saleor 3.1."""- usedByEmail: String+ usedByEmail: String @deprecated(reason: "This field will be removed in Saleor 4.0.")lastUsedOn: DateTimeexpiryDate: Datediff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 0fae7df609..36a5e1d073 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -445,14 +445,13 @@ def set_gift_card_user(used_by_user: Optional[User],used_by_email: str,):- """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- if used_by_user- else User.objects.filter(email=used_by_email).first()- )- gift_card.used_by_email = used_by_email+ """Set the user, each time a giftcard is used."""+ 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_emaildef _update_allocations_for_line(