Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extend CheckoutRemovePromoCode mutation with promoCodeId field (#8354)
Iga Karbowiak82e20a5f1aaa
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 9dbc0d7a70..a732e62420 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -7,6 +7,7 @@ from django.conf import settingsfrom django.contrib.auth.models import AnonymousUserfrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.db.models import Q+from graphql.error import GraphQLErrorfrom ...checkout import AddressType, modelsfrom ...checkout.complete_checkout import complete_checkout@@ -28,6 +29,7 @@ from ...checkout.utils import (is_shipping_required,recalculate_checkout_discount,remove_promo_code_from_checkout,+ remove_voucher_from_checkout,validate_variants_in_checkout_lines,)from ...core import analytics@@ -59,6 +61,8 @@ from ..core.validators import (validate_one_of_args_is_in_mutation,validate_variants_available_in_channel,)+from ..discount.types import Voucher+from ..giftcard.types import GiftCardfrom ..order.types import Orderfrom ..product.types import ProductVariantfrom ..shipping.types import ShippingMethod@@ -1537,7 +1541,11 @@ class CheckoutRemovePromoCode(BaseMutation):)token = UUID(description="Checkout token.", required=False)promo_code = graphene.String(- description="Gift card code or voucher code.", required=True+ description="Gift card code or voucher code.", required=False+ )+ promo_code_id = graphene.ID(+ description="Gift card or voucher ID.",+ required=False,)class Meta:@@ -1546,11 +1554,24 @@ class CheckoutRemovePromoCode(BaseMutation):error_type_field = "checkout_errors"@classmethod- def perform_mutation(cls, _root, info, promo_code, checkout_id=None, token=None):+ def perform_mutation(+ cls,+ _root,+ info,+ checkout_id=None,+ token=None,+ promo_code=None,+ promo_code_id=None,+ ):# DEPRECATEDvalidate_one_of_args_is_in_mutation(CheckoutErrorCode, "checkout_id", checkout_id, "token", token)+ validate_one_of_args_is_in_mutation(+ CheckoutErrorCode, "promo_code", promo_code, "promo_code_id", promo_code_id+ )++ object_type, promo_code_pk = cls.clean_promo_code_id(promo_code_id)if token:checkout = get_checkout_by_token(token)@@ -1564,6 +1585,59 @@ class CheckoutRemovePromoCode(BaseMutation):checkout_info = fetch_checkout_info(checkout, [], info.context.discounts, manager)- remove_promo_code_from_checkout(checkout_info, promo_code)+ if promo_code:+ remove_promo_code_from_checkout(checkout_info, promo_code)+ else:+ cls.remove_promo_code_by_id(info, checkout, object_type, promo_code_pk)+manager.checkout_updated(checkout)return CheckoutRemovePromoCode(checkout=checkout)++ @staticmethod+ def clean_promo_code_id(promo_code_id: Optional[str]):+ if promo_code_id is None:+ return None, None+ try:+ object_type, promo_code_pk = from_global_id_or_error(+ promo_code_id, raise_error=True+ )+ except GraphQLError as e:+ raise ValidationError(+ {+ "promo_code_id": ValidationError(+ str(e), code=CheckoutErrorCode.GRAPHQL_ERROR.value+ )+ }+ )++ if object_type not in (str(Voucher), str(GiftCard)):+ raise ValidationError(+ {+ "promo_code_id": ValidationError(+ "Must receive Voucher or GiftCard id.",+ code=CheckoutErrorCode.NOT_FOUND.value,+ )+ }+ )++ return object_type, promo_code_pk++ @classmethod+ def remove_promo_code_by_id(+ cls, info, checkout: models.Checkout, object_type: str, promo_code_pk: int+ ):+ if object_type == str(Voucher) and checkout.voucher_code is not None:+ node = cls._get_node_by_pk(info, graphene_type=Voucher, pk=promo_code_pk)+ if node is None:+ raise ValidationError(+ {+ "promo_code_id": ValidationError(+ f"Couldn't resolve to a node: {promo_code_pk}",+ code=CheckoutErrorCode.NOT_FOUND.value,+ )+ }+ )+ if checkout.voucher_code == node.code:+ remove_voucher_from_checkout(checkout)+ else:+ checkout.gift_cards.remove(promo_code_pk)diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.pyindex de159dae31..9e4ecb0c34 100644--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py@@ -800,11 +800,12 @@ def test_checkout_add_promo_code_invalidate_shipping_method(MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """- mutation($token: UUID, $promoCode: String!) {+ mutation($token: UUID, $promoCode: String, $promoCodeId: ID) {checkoutRemovePromoCode(- token: $token, promoCode: $promoCode) {+ token: $token, promoCode: $promoCode, promoCodeId: $promoCodeId) {errors {field+ codemessage}checkout {@@ -915,3 +916,114 @@ def test_checkout_remove_promo_code_invalid_checkout(api_client, voucher):assert data["errors"]assert data["errors"][0]["field"] == "token"+++def test_checkout_remove_voucher_code_by_id(+ api_client, checkout_with_voucher, voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None+ checkout_with_voucher.gift_cards.add(gift_card)++ variables = {+ "token": checkout_with_voucher.token,+ "promoCodeId": graphene.Node.to_global_id("Voucher", voucher.id),+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ checkout_with_voucher.refresh_from_db()+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_voucher.token)+ assert data["checkout"]["voucherCode"] is None+ assert len(data["checkout"]["giftCards"]) == 1+ assert checkout_with_voucher.voucher_code is None+++def test_checkout_remove_gift_card_by_id(+ api_client, checkout_with_voucher, gift_card, gift_card_expiry_date+):+ assert checkout_with_voucher.voucher_code is not None+ checkout_with_voucher.gift_cards.add(gift_card, gift_card_expiry_date)++ variables = {+ "token": checkout_with_voucher.token,+ "promoCodeId": graphene.Node.to_global_id("GiftCard", gift_card.id),+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ checkout_with_voucher.refresh_from_db()+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_voucher.token)+ assert data["checkout"]["voucherCode"] is not None+ gift_cards = data["checkout"]["giftCards"]+ assert len(gift_cards) == 1+ assert gift_cards[0]["id"] == graphene.Node.to_global_id(+ "GiftCard", gift_card_expiry_date.pk+ )+++def test_checkout_remove_promo_code_id_and_code_given(+ api_client, checkout_with_voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None++ variables = {+ "token": checkout_with_voucher.token,+ "promoCode": checkout_with_voucher.voucher_code,+ "promoCodeId": graphene.Node.to_global_id("GiftCard", gift_card.id),+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name+++def test_checkout_remove_promo_code_no_id_and_code_given(+ api_client, checkout_with_voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None++ variables = {+ "token": checkout_with_voucher.token,+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name+++def test_checkout_remove_promo_code_id_does_not_exist(+ api_client, checkout_with_voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None++ variables = {+ "token": checkout_with_voucher.token,+ "promoCodeId": "Abc",+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name+ assert data["errors"][0]["field"] == "promoCodeId"+++def test_checkout_remove_promo_code_invalid_object_type(+ api_client, checkout_with_voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None++ variables = {+ "token": checkout_with_voucher.token,+ "promoCodeId": graphene.Node.to_global_id("Product", gift_card.id),+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name+ assert data["errors"][0]["field"] == "promoCodeId"diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex f8cebcc2ba..3d27e1846b 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -3910,7 +3910,7 @@ type Mutation {checkoutLineDelete(checkoutId: ID, lineId: ID, token: UUID): CheckoutLineDeletecheckoutLinesAdd(checkoutId: ID, lines: [CheckoutLineInput]!, token: UUID): CheckoutLinesAddcheckoutLinesUpdate(checkoutId: ID, lines: [CheckoutLineInput]!, token: UUID): CheckoutLinesUpdate- checkoutRemovePromoCode(checkoutId: ID, promoCode: String!, token: UUID): CheckoutRemovePromoCode+ checkoutRemovePromoCode(checkoutId: ID, promoCode: String, promoCodeId: ID, token: UUID): CheckoutRemovePromoCodecheckoutPaymentCreate(checkoutId: ID, input: PaymentInput!, token: UUID): CheckoutPaymentCreatecheckoutShippingAddressUpdate(checkoutId: ID, shippingAddress: AddressInput!, token: UUID): CheckoutShippingAddressUpdatecheckoutShippingMethodUpdate(checkoutId: ID, shippingMethodId: ID!, token: UUID): CheckoutShippingMethodUpdate @deprecated(reason: "This field will be removed in Saleor 4.0. Use `checkoutDeliveryMethodUpdate` instead.")