Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add voucherDetails to CheckoutError explaining voucher rejection (#19749)

Lukasz Ostrowski064700028322
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index 6ad52da857..ac264f7d6a 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -7,6 +7,7 @@ from django.core.exceptions import ValidationError
from ..core.exceptions import GiftCardNotApplicable
from ..core.taxes import TaxError
+from ..discount import PromoCodeRejection, PromoCodeRejectionReason
from ..giftcard.models import GiftCard
from ..payment import gateway
from ..payment import models as payment_models
@@ -119,7 +120,9 @@ def _validate_gift_cards(checkout: Checkout):
)
if not all_gift_cards == active_gift_cards:
msg = "Gift card has expired. Order placement cancelled."
- raise GiftCardNotApplicable(msg)
+ raise GiftCardNotApplicable(
+ msg, PromoCodeRejection(reason=PromoCodeRejectionReason.EXPIRED)
+ )
# Re-check restricted gift cards at completion time: a card may have been
# assigned to another customer after it was added to the checkout.
@@ -139,7 +142,8 @@ def _validate_gift_cards(checkout: Checkout):
if restricted.exists():
# Generic message — do not reveal the assignee.
raise GiftCardNotApplicable(
- "Gift card cannot be used. Order placement cancelled."
+ "Gift card cannot be used. Order placement cancelled.",
+ PromoCodeRejection(reason=PromoCodeRejectionReason.NOT_APPLICABLE),
)
@@ -190,6 +194,11 @@ def validate_checkout(
"voucher_code": ValidationError(
"Voucher not applicable",
code=OrderCreateFromCheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
+ params={
+ "promo_code_details": PromoCodeRejection(
+ reason=PromoCodeRejectionReason.NO_LONGER_AVAILABLE
+ )
+ },
)
}
)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index bfb2ad2854..0912d794b2 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -26,7 +26,12 @@ from ..core.taxes import TaxDataError, TaxError, zero_taxed_money
from ..core.tracing import traced_atomic_transaction
from ..core.transactions import transaction_with_commit_on_errors
from ..core.utils.url import validate_storefront_url
-from ..discount import DiscountType, DiscountValueType
+from ..discount import (
+ DiscountType,
+ DiscountValueType,
+ PromoCodeRejection,
+ PromoCodeRejectionReason,
+)
from ..discount.models import CheckoutDiscount, NotApplicable, OrderLineDiscount
from ..discount.utils.promotion import get_sale_id
from ..discount.utils.voucher import (
@@ -120,7 +125,7 @@ def _process_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:
if checkout.voucher_code and not voucher_code:
msg = "Voucher expired in meantime. Order placement aborted."
- raise NotApplicable(msg)
+ raise NotApplicable(msg, reason=PromoCodeRejectionReason.NO_LONGER_AVAILABLE)
if not voucher_code or not voucher:
return {}
@@ -971,6 +976,11 @@ def _prepare_checkout_with_transactions(
"voucher_code": ValidationError(
"Voucher not applicable",
code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
+ params={
+ "promo_code_details": PromoCodeRejection(
+ reason=PromoCodeRejectionReason.NO_LONGER_AVAILABLE
+ )
+ },
)
}
)
@@ -1035,9 +1045,12 @@ def _get_order_data(
raise ValidationError(
"Voucher not applicable",
code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
+ params={"promo_code_details": e.rejection},
) from e
except GiftCardNotApplicable as e:
- raise ValidationError(e.message, code=e.code) from e
+ raise ValidationError(
+ e.message, code=e.code, params={"promo_code_details": e.rejection}
+ ) from e
except TaxError as e:
raise ValidationError(
f"Unable to calculate taxes - {str(e)}",
@@ -1204,7 +1217,11 @@ def complete_checkout_post_payment_part(
voucher=checkout_info.voucher,
payment=payment,
)
- raise ValidationError(code=e.code, message=e.message) from e
+ raise ValidationError(
+ code=e.code,
+ message=e.message,
+ params={"promo_code_details": e.rejection},
+ ) from e
return order, action_required, action_data
@@ -1811,6 +1828,7 @@ def complete_checkout_with_transaction(
"voucher_code": ValidationError(
"Voucher not applicable",
code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
+ params={"promo_code_details": e.rejection},
)
}
) from e
@@ -1818,7 +1836,17 @@ def complete_checkout_with_transaction(
error = prepare_insufficient_stock_checkout_validation_error(e)
raise error from e
except GiftCardNotApplicable as e:
- raise ValidationError({"gift_cards": e}) from e
+ raise ValidationError(
+ {
+ "gift_cards": ValidationError(
+ e.message,
+ # Deliberately no `code`: this path has always reported the
+ # default `INVALID` rather than the exception's
+ # GIFT_CARD_NOT_APPLICABLE, and clients depend on it.
+ params={"promo_code_details": e.rejection},
+ )
+ }
+ ) from e
def complete_checkout_with_payment(
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index b2cb2ac824..ce2565b8ff 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -12,6 +12,7 @@ from prices import Money, TaxedMoney
from ...account.models import Address
from ...core.taxes import zero_money
from ...discount import (
+ NOT_APPLICABLE_MESSAGE,
DiscountType,
DiscountValueType,
RewardType,
@@ -886,7 +887,7 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable_in_country(
checkout_with_items.shipping_address,
)
# then
- assert str(e.value) == "This offer is not valid in your country."
+ assert str(e.value) == NOT_APPLICABLE_MESSAGE
def test_get_discount_for_checkout_shipping_voucher_not_applicable_spent_not_enough(
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index cda8a8a150..526c5895e0 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -32,7 +32,13 @@ from ..core.utils.promo_code import (
)
from ..core.utils.translations import get_translation
from ..core.weight import zero_weight
-from ..discount import DiscountType, VoucherType
+from ..discount import (
+ NOT_APPLICABLE_MESSAGE,
+ DiscountType,
+ PromoCodeRejection,
+ PromoCodeRejectionReason,
+ VoucherType,
+)
from ..discount.interface import fetch_voucher_info
from ..discount.models import CheckoutDiscount, NotApplicable, Voucher, VoucherCode
from ..discount.utils.checkout import (
@@ -443,17 +449,20 @@ def _get_shipping_voucher_discount_for_checkout(
"""Calculate discount value for a voucher of shipping type."""
if not is_shipping_required(lines):
msg = "Your order does not require shipping."
- raise NotApplicable(msg)
+ raise NotApplicable(msg, reason=PromoCodeRejectionReason.SHIPPING_NOT_REQUIRED)
shipping_method = checkout_info.get_delivery_method_info().delivery_method
if not shipping_method:
msg = "Please select a delivery method first."
- raise NotApplicable(msg)
+ raise NotApplicable(
+ msg, reason=PromoCodeRejectionReason.DELIVERY_METHOD_NOT_SET
+ )
# check if voucher is limited to specified countries
if address:
if voucher.countries and address.country.code not in voucher.countries:
- msg = "This offer is not valid in your country."
- raise NotApplicable(msg)
+ raise NotApplicable(
+ NOT_APPLICABLE_MESSAGE, reason=PromoCodeRejectionReason.NOT_APPLICABLE
+ )
shipping_price = base_calculations.base_checkout_undiscounted_delivery_price(
checkout_info=checkout_info, lines=lines
@@ -534,7 +543,7 @@ def _get_products_voucher_discount(
prices = get_prices_of_discounted_specific_product(lines, voucher)
if not prices:
msg = "This offer is only valid for selected items."
- raise NotApplicable(msg)
+ raise NotApplicable(msg, reason=PromoCodeRejectionReason.NO_ELIGIBLE_PRODUCTS)
return get_products_voucher_discount(voucher, prices, checkout_info.channel)
@@ -697,12 +706,7 @@ def add_promo_code_to_checkout(
Raise InvalidPromoCode if promo code does not match to any voucher or gift card.
"""
if promo_code_is_voucher(promo_code):
- add_voucher_code_to_checkout(
- manager,
- checkout_info,
- lines,
- promo_code,
- )
+ add_voucher_code_to_checkout(manager, checkout_info, lines, promo_code)
elif promo_code_is_gift_card(promo_code):
if not checkout_info.channel.allow_legacy_gift_card_use:
raise ValidationError(
@@ -722,7 +726,11 @@ def add_promo_code_to_checkout(
checkout_info.channel.currency_code,
)
else:
- raise InvalidPromoCode()
+ raise InvalidPromoCode(
+ promo_code_rejection=PromoCodeRejection(
+ reason=PromoCodeRejectionReason.NOT_FOUND
+ )
+ )
def add_voucher_code_to_checkout(
@@ -746,6 +754,7 @@ def add_voucher_code_to_checkout(
"promo_code": ValidationError(
"Voucher is not applicable to this checkout.",
code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
+ params={"promo_code_details": e.rejection},
)
}
) from e
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.py
index 6a6052ac54..21b9f319d4 100644
--- a/saleor/core/exceptions.py
+++ b/saleor/core/exceptions.py
@@ -10,6 +10,7 @@ from ..checkout.error_codes import CheckoutErrorCode
if TYPE_CHECKING:
from ..checkout.models import CheckoutLine
+ from ..discount import PromoCodeRejection
from ..order.models import OrderLine
from ..product.models import ProductVariant
@@ -85,10 +86,18 @@ class PermissionDenied(Exception):
class GiftCardNotApplicable(Exception):
- def __init__(self, message: str):
+ """Raised when a gift card on a checkout can no longer be used.
+
+ `rejection` carries a `PromoCodeRejection` so the API can report why. The
+ card is already attached to the checkout by the time this is raised, so the
+ caller has demonstrably held it and the reason discloses nothing new.
+ """
+
+ def __init__(self, message: str, rejection: "PromoCodeRejection | None" = None):
super().__init__(message)
self.message = message
self.code = CheckoutErrorCode.GIFT_CARD_NOT_APPLICABLE.value
+ self.rejection = rejection
class CircularSubscriptionSyncEvent(GraphQLError):
diff --git a/saleor/core/utils/promo_code.py b/saleor/core/utils/promo_code.py
index 7bb9cbea50..ae2097104d 100644
--- a/saleor/core/utils/promo_code.py
+++ b/saleor/core/utils/promo_code.py
@@ -2,17 +2,31 @@ import secrets
from django.core.exceptions import ValidationError
+from ...discount import PromoCodeRejection
from ...discount.models import VoucherCode
from ...giftcard.error_codes import GiftCardErrorCode
from ...giftcard.models import GiftCard
class InvalidPromoCode(ValidationError):
- def __init__(self, message=None, **kwargs):
+ def __init__(
+ self,
+ message=None,
+ promo_code_rejection: PromoCodeRejection | None = None,
+ **kwargs,
+ ):
+ """Carry the reason for a rejected voucher or gift card code, if known."""
+ self.rejection = promo_code_rejection
if message is None:
message = {
"promo_code": ValidationError(
- "Promo code is invalid", code=GiftCardErrorCode.INVALID.value
+ "Promo code is invalid",
+ code=GiftCardErrorCode.INVALID.value,
+ params=(
+ {"promo_code_details": promo_code_rejection}
+ if promo_code_rejection
+ else None
+ ),
)
}
super().__init__(message, **kwargs)
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
index e16538643c..8411feb3b1 100644
--- a/saleor/discount/__init__.py
+++ b/saleor/discount/__init__.py
@@ -1,6 +1,9 @@
from dataclasses import dataclass
+from enum import Enum
from typing import TYPE_CHECKING
+from prices import Money
+
if TYPE_CHECKING:
from .models import PromotionRule
@@ -43,6 +46,59 @@ class VoucherType:
]
+class PromoCodeRejectionReason(Enum):
+ """Specific reason why a promo code cannot be applied.
+
+ Complements the coarse GraphQL error codes (`INVALID`,
+ `VOUCHER_NOT_APPLICABLE`), which stay unchanged, so a storefront can render
+ a precise message instead of a generic "voucher is not applicable".
+
+ Most values describe voucher conditions, but the vocabulary is shared with
+ gift cards so that a rejection is reported the same way whichever kind of
+ promo code was submitted -- the field name alone must not reveal which.
+
+ Submitting a code that matches nothing must stay indistinguishable from
+ submitting one that exists but cannot be used, otherwise the response is an
+ oracle for guessing codes. So before a code is known to be usable only
+ `NOT_FOUND`, `EXPIRED` and `USAGE_LIMIT_REACHED` may be reported -- the
+ latter two are a deliberate product decision to help shoppers holding a
+ real code. Everything else is reported only once the code is proven live
+ (a voucher accepted onto the checkout, a gift card already attached to it),
+ where the caller has demonstrably seen the code work and there is nothing
+ left to disclose. No reason depends on the caller's permissions.
+ """
+
+ NOT_FOUND = "not_found"
+ EXPIRED = "expired"
+ USAGE_LIMIT_REACHED = "usage_limit_reached"
+ NOT_APPLICABLE = "not_applicable"
+ MIN_SPENT_NOT_REACHED = "min_spent_not_reached"
+ MIN_QUANTITY_NOT_REACHED = "min_quantity_not_reached"
+ CUSTOMER_EMAIL_REQUIRED = "customer_email_required"
+ SHIPPING_NOT_REQUIRED = "shipping_not_required"
+ DELIVERY_METHOD_NOT_SET = "delivery_method_not_set"
+ NO_ELIGIBLE_PRODUCTS = "no_eligible_products"
+ NO_LONGER_AVAILABLE = "no_longer_available"
+
+
+NOT_APPLICABLE_MESSAGE = "This offer cannot be applied."
+"""Message paired with `PromoCodeRejectionReason.NOT_APPLICABLE`.
+
+Kept as vague as the reason it accompanies: a message naming the condition
+(staff-only, already redeemed, another country or channel) would disclose
+through the error text exactly what the generic reason withholds.
+"""
+
+
+@dataclass
+class PromoCodeRejection:
+ """Structured details about why a promo code was rejected."""
+
+ reason: PromoCodeRejectionReason
+ min_spent: Money | None = None
+ min_checkout_items_quantity: int | None = None
+
+
class PromotionType:
CATALOGUE = "catalogue"
ORDER = "order"
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 640e1a2048..1df4d54132 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -21,8 +21,11 @@ from ..core.utils.json_serializer import CustomJsonEncoder
from ..core.utils.translations import Translation
from ..permission.enums import DiscountPermissions
from . import (
+ NOT_APPLICABLE_MESSAGE,
DiscountType,
DiscountValueType,
+ PromoCodeRejection,
+ PromoCodeRejectionReason,
PromotionEvents,
PromotionType,
RewardType,
@@ -41,12 +44,32 @@ class NotApplicable(ValueError):
price or the order quantity is below the minimum quantity of items.
Minimum price will be available as the `min_spent` attribute.
Minimum quantity will be available as the `min_checkout_items_quantity` attribute.
+ `reason` carries a `PromoCodeRejectionReason` value so the API can report the
+ precise cause; it is empty for discounts other than vouchers.
"""
- def __init__(self, msg, min_spent=None, min_checkout_items_quantity=None):
+ def __init__(
+ self,
+ msg: str,
+ min_spent: Money | None = None,
+ min_checkout_items_quantity: int | None = None,
+ reason: PromoCodeRejectionReason | None = None,
+ ):
super().__init__(msg)
self.min_spent = min_spent
self.min_checkout_items_quantity = min_checkout_items_quantity
+ self.reason = reason
+
+ @property
+ def rejection(self) -> PromoCodeRejection | None:
+ """Return the structured rejection details, if the cause is known."""
+ if not self.reason:
+ return None
+ return PromoCodeRejection(
+ reason=self.reason,
+ min_spent=self.min_spent,
+ min_checkout_items_quantity=self.min_checkout_items_quantity,
+ )
class VoucherQueryset(models.QuerySet["Voucher"]):
@@ -154,7 +177,10 @@ class Voucher(ModelWithMetadata):
break
if not voucher_channel_listing:
- raise NotApplicable("This voucher is not assigned to this channel")
+ raise NotApplicable(
+ NOT_APPLICABLE_MESSAGE,
+ reason=PromoCodeRejectionReason.NOT_APPLICABLE,
+ )
if self.discount_value_type == DiscountValueType.FIXED:
discount_amount = Money(
voucher_channel_listing.discount_value, voucher_channel_listing.currency
@@ -178,12 +204,19 @@ class Voucher(ModelWithMetadata):
def validate_min_spent(self, value: Money, channel: Channel):
voucher_channel_listing = self.channel_listings.filter(channel=channel).first()
if not voucher_channel_listing:
- raise NotApplicable("This voucher is not assigned to this channel")
+ raise NotApplicable(
+ NOT_APPLICABLE_MESSAGE,
+ reason=PromoCodeRejectionReason.NOT_APPLICABLE,
+ )
min_spent = voucher_channel_listing.min_spent
if min_spent and value < min_spent:
target = min_spent.quantize()
msg = f"This offer is only valid for orders over {target.amount} {target.currency}."
- raise NotApplicable(msg, min_spent=min_spent)
+ raise NotApplicable(
+ msg,
+ min_spent=min_spent,
+ reason=PromoCodeRejectionReason.MIN_SPENT_NOT_REACHED,
+ )
def validate_min_checkout_items_quantity(self, quantity):
min_checkout_items_quantity = self.min_checkout_items_quantity
@@ -195,25 +228,34 @@ class Voucher(ModelWithMetadata):
raise NotApplicable(
msg,
min_checkout_items_quantity=min_checkout_items_quantity,
+ reason=PromoCodeRejectionReason.MIN_QUANTITY_NOT_REACHED,
)
def validate_once_per_customer(self, customer_email):
+ """Reject the voucher if `customer_email` already redeemed it.
+
+ Reported as the generic `NOT_APPLICABLE`: the address on a checkout is
+ attacker-supplied and unverified, so a reason naming the redemption
+ would let anyone probe another customer's history.
+ """
voucher_codes = self.codes.all()
voucher_customer = VoucherCustomer.objects.filter(
Exists(voucher_codes.filter(id=OuterRef("voucher_code_id"))),
customer_email=customer_email,
)
if voucher_customer:
- msg = "This offer is valid only once per customer."
- raise NotApplicable(msg)
+ raise NotApplicable(
+ NOT_APPLICABLE_MESSAGE, reason=PromoCodeRejectionReason.NOT_APPLICABLE
+ )
def validate_only_for_staff(self, customer: Optional["User"]):
if not self.only_for_staff:
return
if not customer or not customer.is_staff:
- msg = "This offer is valid only for staff customers."
- raise NotApplicable(msg)
+ raise NotApplicable(
+ NOT_APPLICABLE_MESSAGE, reason=PromoCodeRejectionReason.NOT_APPLICABLE
+ )
class VoucherCode(models.Model):
diff --git a/saleor/discount/utils/voucher.py b/saleor/discount/utils/voucher.py
index d1ca06703f..9d317a316a 100644
--- a/saleor/discount/utils/voucher.py
+++ b/saleor/discount/utils/voucher.py
@@ -4,7 +4,16 @@ from decimal import Decimal
from typing import TYPE_CHECKING, Optional, Union, cast
from uuid import UUID
-from django.db.models import Case, Exists, F, IntegerField, OuterRef, Value, When
+from django.db.models import (
+ Case,
+ Exists,
+ F,
+ IntegerField,
+ OuterRef,
+ Sum,
+ Value,
+ When,
+)
from django.utils import timezone
from prices import Money
@@ -14,13 +23,20 @@ from ...core.db.connection import allow_writer
from ...core.taxes import zero_money
from ...core.utils.promo_code import InvalidPromoCode
from ...order.models import Order, OrderLine
-from .. import DiscountType, VoucherType
+from .. import (
+ NOT_APPLICABLE_MESSAGE,
+ DiscountType,
+ PromoCodeRejection,
+ PromoCodeRejectionReason,
+ VoucherType,
+)
from ..interface import DiscountInfo, VoucherInfo
from ..models import (
DiscountValueType,
NotApplicable,
OrderLineDiscount,
Voucher,
+ VoucherChannelListing,
VoucherCode,
VoucherCustomer,
)
@@ -113,13 +129,18 @@ def add_voucher_usage_by_customer(
code: "VoucherCode", customer_email: str | None
) -> None:
if not customer_email:
- raise NotApplicable("Unable to apply voucher as customer details are missing.")
+ raise NotApplicable(
+ "Unable to apply voucher as customer details are missing.",
+ reason=PromoCodeRejectionReason.CUSTOMER_EMAIL_REQUIRED,
+ )
_, created = VoucherCustomer.objects.get_or_create(
voucher_code=code, customer_email=customer_email
)
if not created:
- raise NotApplicable("This offer is only valid once per customer.")
+ raise NotApplicable(
+ NOT_APPLICABLE_MESSAGE, reason=PromoCodeRejectionReason.NOT_APPLICABLE
+ )
def remove_voucher_usage_by_customer(code: "VoucherCode", customer_email: str) -> None:
@@ -170,10 +191,80 @@ def get_voucher_code_instance(
):
code_instance = VoucherCode.objects.get(code=voucher_code)
else:
- raise InvalidPromoCode()
+ raise InvalidPromoCode(
+ promo_code_rejection=PromoCodeRejection(
+ reason=diagnose_invalid_voucher_code(
+ voucher_code, channel_slug, validate_usage_limit
+ )
+ )
+ )
return code_instance
+def diagnose_invalid_voucher_code(
+ voucher_code: str,
+ channel_slug: str,
+ validate_usage_limit: bool,
+) -> PromoCodeRejectionReason:
+ """Return the `PromoCodeRejectionReason` explaining why a code was rejected.
+
+ Only called once a code has already been found unusable, so the extra
+ queries never run on the happy path.
+ """
+ code = (
+ VoucherCode.objects.filter(code=voucher_code).select_related("voucher").first()
+ )
+ if code is None:
+ return PromoCodeRejectionReason.NOT_FOUND
+ if reason := diagnose_inactive_voucher(
+ code.voucher, channel_slug, validate_usage_limit
+ ):
+ return reason
+ if not code.is_active:
+ # A code is deactivated only when a single-use code has been redeemed,
+ # which is a usage limit of one, reached.
+ return PromoCodeRejectionReason.USAGE_LIMIT_REACHED
+ return PromoCodeRejectionReason.NOT_FOUND
+
+
+def diagnose_inactive_voucher(
+ voucher: "Voucher",
+ channel_slug: str,
+ validate_usage_limit: bool,
+) -> PromoCodeRejectionReason | None:
+ """Return why a voucher is not currently usable, or None if it is.
+
+ Only called once a voucher has already been found unusable, so the extra
+ queries never run on the happy path.
+
+ An unlaunched voucher and one belonging to another channel are reported as
+ `NOT_FOUND`: both would otherwise confirm a campaign the caller has no
+ access to, and neither is actionable by a shopper. Those checks run first,
+ so a hidden voucher is never reported as `EXPIRED` or `USAGE_LIMIT_REACHED`.
+ """
+ if not VoucherChannelListing.objects.filter(
+ voucher_id=voucher.pk,
+ channel__slug=channel_slug,
+ channel__is_active=True,
+ ).exists():
+ return PromoCodeRejectionReason.NOT_FOUND
+ now = timezone.now()
+ if voucher.start_date > now:
+ return PromoCodeRejectionReason.NOT_FOUND
+ if voucher.end_date and voucher.end_date < now:
+ return PromoCodeRejectionReason.EXPIRED
+ if validate_usage_limit and voucher.usage_limit is not None:
+ used = (
+ VoucherCode.objects.filter(voucher_id=voucher.pk).aggregate(
+ total_used=Sum("used")
+ )["total_used"]
+ or 0
+ )
+ if used >= voucher.usage_limit:
+ return PromoCodeRejectionReason.USAGE_LIMIT_REACHED
+ return None
+
+
def get_active_voucher_code(voucher, channel_slug, validate_usage_limit=True):
"""Return an active VoucherCode instance.
@@ -184,10 +275,21 @@ def get_active_voucher_code(voucher, channel_slug, validate_usage_limit=True):
timezone.now(), channel_slug, validate_usage_limit
)
if not voucher_queryset.filter(pk=voucher.pk).exists():
- raise InvalidPromoCode()
+ reason = (
+ diagnose_inactive_voucher(voucher, channel_slug, validate_usage_limit)
+ or PromoCodeRejectionReason.NOT_FOUND
+ )
+ raise InvalidPromoCode(promo_code_rejection=PromoCodeRejection(reason=reason))
voucher_code = VoucherCode.objects.filter(voucher=voucher, is_active=True).first()
if not voucher_code:
- raise InvalidPromoCode()
+ # Every code redeemed reads as a usage limit reached; a voucher stripped
+ # of all its codes by `voucherCodeBulkDelete` has nothing to find.
+ reason = (
+ PromoCodeRejectionReason.USAGE_LIMIT_REACHED
+ if voucher.codes.exists()
+ else PromoCodeRejectionReason.NOT_FOUND
+ )
+ raise InvalidPromoCode(promo_code_rejection=PromoCodeRejection(reason=reason))
return voucher_code
@@ -315,6 +417,13 @@ def validate_voucher_in_order(
subtotal = order.subtotal
quantity = get_total_quantity(lines)
customer_email = get_customer_email_for_voucher_usage(order)
+ if order.voucher.apply_once_per_customer and not customer_email:
+ # Completing the order records the redemption per customer, so it must
+ # be rejected here rather than fail mid-transaction.
+ raise NotApplicable(
+ "Unable to apply voucher as customer details are missing.",
+ reason=PromoCodeRejectionReason.CUSTOMER_EMAIL_REQUIRED,
+ )
tax_configuration = channel.tax_configuration
prices_entered_with_tax = tax_configuration.prices_entered_with_tax
value = subtotal.gross if prices_entered_with_tax else subtotal.net
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index 3e84bbde67..2303f8c80a 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -18,6 +18,7 @@ from ..core.exceptions import GiftCardNotApplicable
from ..core.tracing import traced_atomic_transaction
from ..core.utils.events import call_event
from ..core.utils.promo_code import InvalidPromoCode, generate_promo_code
+from ..discount import PromoCodeRejection, PromoCodeRejectionReason
from ..order.actions import OrderFulfillmentLineInfo, create_fulfillments
from ..order.models import OrderLine
from ..payment.models import Payment, TransactionItem
@@ -40,6 +41,17 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+def _undisclosed_rejection() -> PromoCodeRejection:
+ """Return the rejection reported for a gift card code that cannot be used.
+
+ Reporting `NOT_FOUND` keeps an unusable gift card indistinguishable from a
+ code that matches nothing at all. Anything else turns the response into an
+ oracle confirming that a guessed gift card code exists. It is a deliberate
+ redaction rather than the literal truth, which the schema documents.
+ """
+ return PromoCodeRejection(reason=PromoCodeRejectionReason.NOT_FOUND)
+
+
def add_gift_card_code_to_checkout(
checkout: Checkout, email: str | None, promo_code: str, currency: str
):
@@ -56,7 +68,7 @@ def add_gift_card_code_to_checkout(
.get(code=promo_code)
)
except GiftCard.DoesNotExist as e:
- raise InvalidPromoCode() from e
+ raise InvalidPromoCode(promo_code_rejection=_undisclosed_rejection()) from e
if rejection_reason := gift_card.usage_restriction_reason(checkout.user_id):
logger.info(
@@ -66,7 +78,7 @@ def add_gift_card_code_to_checkout(
checkout.pk,
)
# Generic error — do not reveal the assignee.
- raise InvalidPromoCode()
+ raise InvalidPromoCode(promo_code_rejection=_undisclosed_rejection())
checkout.gift_cards.add(gift_card)
checkout.save(update_fields=["last_change"])
diff --git a/saleor/graphql/account/enums.py b/saleor/graphql/account/enums.py
index bec9d256f0..4cbffd987b 100644
--- a/saleor/graphql/account/enums.py
+++ b/saleor/graphql/account/enums.py
@@ -30,7 +30,7 @@ def __country_code_enum_description(enum):
return None
-CountryCodeEnum = graphene.Enum(
+CountryCodeEnum: Final[graphene.Enum] = graphene.Enum(
"CountryCode",
[(str_to_enum(country[0]), country[0]) for country in countries],
description=__country_code_enum_description,
diff --git a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
index 8a80719c7d..f2b5b94d9d 100644
--- a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
@@ -100,12 +100,7 @@ class CheckoutAddPromoCode(BaseMutation):
checkout_info = fetch_checkout_info(checkout, lines, manager)
- add_promo_code_to_checkout(
- manager,
- checkout_info,
- lines,
- promo_code,
- )
+ add_promo_code_to_checkout(manager, checkout_info, lines, promo_code)
shipping_update_fields = mark_checkout_deliveries_as_stale_if_needed(
checkout_info.checkout, lines
diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
index 35ba7bd5b9..250555dcdc 100644
--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py
+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
@@ -28,6 +28,10 @@ from ...core.context import SyncWebhookControlContext
from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.mutations import BaseMutation
from ...core.types import Error, NonNullList
+from ...core.types.common import (
+ PROMO_CODE_DETAILS_DESCRIPTION,
+ PromoCodeRejectionDetails,
+)
from ...core.utils import CHECKOUT_CALCULATE_TAXES_MESSAGE, WebhookEventInfo
from ...meta.inputs import MetadataInput, MetadataInputDescription
from ...order.types import Order
@@ -51,6 +55,11 @@ class OrderCreateFromCheckoutError(Error):
description="List of line Ids which cause the error.",
required=False,
)
+ promo_code_details = graphene.Field(
+ PromoCodeRejectionDetails,
+ description=PROMO_CODE_DETAILS_DESCRIPTION,
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -220,14 +229,14 @@ class OrderCreateFromCheckout(BaseMutation):
app = get_app_promise(info.context).get()
requestor = app or user
- cls.validate_checkout(
- checkout_info,
- checkout_lines,
- unavailable_variant_pks,
- manager,
- requestor=requestor,
- )
try:
+ cls.validate_checkout(
+ checkout_info,
+ checkout_lines,
+ unavailable_variant_pks,
+ manager,
+ requestor=requestor,
+ )
order = create_order_from_checkout(
checkout_info=checkout_info,
manager=manager,
@@ -244,6 +253,7 @@ class OrderCreateFromCheckout(BaseMutation):
"voucher_code": ValidationError(
"Voucher not applicable",
code=code,
+ params={"promo_code_details": e.rejection},
)
}
) from e
@@ -251,7 +261,15 @@ class OrderCreateFromCheckout(BaseMutation):
error = prepare_insufficient_stock_checkout_validation_error(e)
raise error from e
except GiftCardNotApplicable as e:
- raise ValidationError({"gift_cards": e}) from e
+ raise ValidationError(
+ {
+ "gift_cards": ValidationError(
+ e.message,
+ code=OrderCreateFromCheckoutErrorCode.GIFT_CARD_NOT_APPLICABLE.value,
+ params={"promo_code_details": e.rejection},
+ )
+ }
+ ) from e
except TaxDataError as e:
raise ValidationError(
"Configured Tax App returned invalid response.",
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code_rejection_details.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code_rejection_details.py
new file mode 100644
index 0000000000..3f80ed8d62
--- /dev/null
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code_rejection_details.py
@@ -0,0 +1,360 @@
+import datetime
+
+from django.utils import timezone
+
+from .....checkout import base_calculations
+from .....checkout.error_codes import CheckoutErrorCode
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....discount.models import VoucherCustomer
+from .....plugins.manager import get_plugins_manager
+from ....core.enums import PromoCodeRejectionReason
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+
+MUTATION_ADD_PROMO_CODE = """
+ mutation($id: ID, $promoCode: String!) {
+ checkoutAddPromoCode(id: $id, promoCode: $promoCode) {
+ errors {
+ field
+ code
+ promoCodeDetails {
+ reason
+ minSpent {
+ amount
+ currency
+ }
+ minCheckoutItemsQuantity
+ }
+ }
+ }
+ }
+"""
+
+NO_PARAMS = {"minSpent": None, "minCheckoutItemsQuantity": None}
+
+
+def _add_promo_code(client, checkout, promo_code):
+ variables = {"id": to_global_id_or_none(checkout), "promoCode": promo_code}
+ response = client.post_graphql(MUTATION_ADD_PROMO_CODE, variables)
+ return get_graphql_content(response)["data"]["checkoutAddPromoCode"]
+
+
+def _assert_single_error(data, expected_code, expected_details):
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "promoCode"
+ assert error["code"] == expected_code.name
+ assert error["promoCodeDetails"] == expected_details
+
+
+def test_min_spent_not_reached(
+ api_client, checkout_with_item, voucher_with_high_min_spent_amount
+):
+ # given
+ min_spent = voucher_with_high_min_spent_amount.channel_listings.get().min_spent
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
+ subtotal = base_calculations.base_checkout_subtotal(
+ lines, checkout_info.channel, checkout_with_item.currency
+ )
+ assert min_spent > subtotal
+
+ # when
+ data = _add_promo_code(
+ api_client, checkout_with_item, voucher_with_high_min_spent_amount.code
+ )
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ NO_PARAMS
+ | {
+ "reason": PromoCodeRejectionReason.MIN_SPENT_NOT_REACHED.name,
+ "minSpent": {
+ "amount": float(min_spent.amount),
+ "currency": min_spent.currency,
+ },
+ },
+ )
+ checkout_with_item.refresh_from_db(fields=("voucher_code",))
+ assert checkout_with_item.voucher_code is None
+
+
+def test_min_quantity_not_reached(api_client, checkout_with_item, voucher):
+ # given
+ min_quantity = 100
+ assert checkout_with_item.lines.count() < min_quantity
+ voucher.min_checkout_items_quantity = min_quantity
+ voucher.save(update_fields=["min_checkout_items_quantity"])
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ NO_PARAMS
+ | {
+ "reason": PromoCodeRejectionReason.MIN_QUANTITY_NOT_REACHED.name,
+ "minCheckoutItemsQuantity": min_quantity,
+ },
+ )
+
+
+def test_staff_only_reports_not_applicable(api_client, checkout_with_item, voucher):
+ # given
+ voucher.only_for_staff = True
+ voucher.save(update_fields=["only_for_staff"])
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.NOT_APPLICABLE.name},
+ )
+
+
+def test_already_used_by_customer_reports_not_applicable(
+ user_api_client, checkout_with_item, voucher
+):
+ # given
+ customer = user_api_client.user
+ voucher.apply_once_per_customer = True
+ voucher.save(update_fields=["apply_once_per_customer"])
+ VoucherCustomer.objects.create(
+ voucher_code=voucher.codes.get(), customer_email=customer.email
+ )
+ checkout_with_item.user = customer
+ checkout_with_item.email = customer.email
+ checkout_with_item.save(update_fields=["user", "email"])
+
+ # when
+ data = _add_promo_code(user_api_client, checkout_with_item, voucher.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.NOT_APPLICABLE.name},
+ )
+
+
+def test_no_eligible_products(
+ api_client, checkout_with_item, voucher_specific_product_type, product_list
+):
+ # given
+ other_product = product_list[0]
+ voucher_specific_product_type.products.set([other_product])
+ checkout_products = {
+ line.variant.product_id for line in checkout_with_item.lines.all()
+ }
+ assert other_product.pk not in checkout_products
+
+ # when
+ data = _add_promo_code(
+ api_client, checkout_with_item, voucher_specific_product_type.code
+ )
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.NO_ELIGIBLE_PRODUCTS.name},
+ )
+
+
+def test_shipping_not_required(
+ api_client, checkout_without_shipping_required, voucher_shipping_type
+):
+ # when
+ data = _add_promo_code(
+ api_client, checkout_without_shipping_required, voucher_shipping_type.code
+ )
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.SHIPPING_NOT_REQUIRED.name},
+ )
+
+
+def test_delivery_method_not_set(api_client, checkout_with_item, voucher_shipping_type):
+ # given
+ assert checkout_with_item.assigned_delivery is None
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher_shipping_type.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.DELIVERY_METHOD_NOT_SET.name},
+ )
+
+
+def test_country_not_eligible_reports_not_applicable(
+ api_client,
+ checkout_with_item,
+ voucher_shipping_type,
+ checkout_delivery,
+ shipping_zone,
+ address_usa,
+):
+ # given
+ eligible_countries = ["IS"]
+ voucher_shipping_type.countries = eligible_countries
+ voucher_shipping_type.save(update_fields=["countries"])
+ checkout_with_item.assigned_delivery = checkout_delivery(checkout_with_item)
+ checkout_with_item.shipping_address = address_usa
+ checkout_with_item.save(update_fields=["assigned_delivery", "shipping_address"])
+ assert address_usa.country.code not in eligible_countries
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher_shipping_type.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.NOT_APPLICABLE.name},
+ )
+
+
+def test_expired(api_client, checkout_with_item, voucher):
+ # given
+ voucher.start_date = timezone.now() - datetime.timedelta(days=10)
+ voucher.end_date = timezone.now() - datetime.timedelta(days=1)
+ voucher.save(update_fields=["start_date", "end_date"])
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.INVALID,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.EXPIRED.name},
+ )
+
+
+def test_not_started_reports_not_found(api_client, checkout_with_item, voucher):
+ """An unlaunched campaign must not be confirmed; see the disclosure tests."""
+ # given
+ voucher.start_date = timezone.now() + datetime.timedelta(days=1)
+ voucher.save(update_fields=["start_date"])
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.INVALID,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.NOT_FOUND.name},
+ )
+
+
+def test_usage_limit_reached(api_client, checkout_with_item, voucher):
+ # given
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+ code = voucher.codes.get()
+ code.used = 1
+ code.save(update_fields=["used"])
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.INVALID,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.USAGE_LIMIT_REACHED.name},
+ )
+
+
+def test_redeemed_single_use_code_reports_usage_limit_reached(
+ api_client, checkout_with_item, voucher
+):
+ """A code is deactivated only once a single-use code has been redeemed."""
+ # given
+ code = voucher.codes.get()
+ code.is_active = False
+ code.save(update_fields=["is_active"])
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.INVALID,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.USAGE_LIMIT_REACHED.name},
+ )
+
+
+def test_not_available_in_channel_reports_not_found(
+ api_client, checkout_with_item, voucher
+):
+ """A campaign in another channel must not be confirmed."""
+ # given
+ voucher.channel_listings.all().delete()
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.INVALID,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.NOT_FOUND.name},
+ )
+
+
+def test_unknown_code(api_client, checkout_with_item):
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, "THIS-CODE-DOES-NOT-EXIST")
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.INVALID,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.NOT_FOUND.name},
+ )
+
+
+def test_unusable_gift_card_reports_not_found(
+ api_client, checkout_with_item, gift_card_expiry_date
+):
+ """An unusable gift card must not be distinguishable from an unknown code."""
+ # given
+ gift_card_expiry_date.expiry_date = datetime.date(1999, 1, 1)
+ gift_card_expiry_date.save(update_fields=["expiry_date"])
+
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, gift_card_expiry_date.code)
+
+ # then
+ _assert_single_error(
+ data,
+ CheckoutErrorCode.INVALID,
+ NO_PARAMS | {"reason": PromoCodeRejectionReason.NOT_FOUND.name},
+ )
+
+
+def test_applicable_voucher_reports_no_errors(api_client, checkout_with_item, voucher):
+ # when
+ data = _add_promo_code(api_client, checkout_with_item, voucher.code)
+
+ # then
+ assert data["errors"] == []
+ checkout_with_item.refresh_from_db(fields=("voucher_code",))
+ assert checkout_with_item.voucher_code == voucher.code
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_gift_card_promo_code_details.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_gift_card_promo_code_details.py
new file mode 100644
index 0000000000..4f5fbacbff
--- /dev/null
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_gift_card_promo_code_details.py
@@ -0,0 +1,123 @@
+"""Report why a gift card already on the checkout can no longer be used.
+
+The card was accepted onto the checkout earlier, so the caller demonstrably
+holds it and the reason discloses nothing a code guesser could use. Add-time
+rejections stay redacted -- see `test_checkout_promo_code_reason_disclosure`.
+"""
+
+import datetime
+
+from .....checkout.error_codes import CheckoutErrorCode
+from .....order.models import Order
+from ....core.enums import PromoCodeRejectionReason
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+from .test_checkout_complete_with_transactions import prepare_checkout_for_test
+
+MUTATION_CHECKOUT_COMPLETE = """
+ mutation checkoutComplete($id: ID, $redirectUrl: String) {
+ checkoutComplete(id: $id, redirectUrl: $redirectUrl) {
+ order {
+ id
+ }
+ errors {
+ field
+ code
+ promoCodeDetails {
+ reason
+ minSpent {
+ amount
+ currency
+ }
+ minCheckoutItemsQuantity
+ }
+ }
+ }
+ }
+"""
+
+NO_PARAMS = {"minSpent": None, "minCheckoutItemsQuantity": None}
+
+
+def _complete(client, checkout):
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+ response = client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ return get_graphql_content(response)["data"]["checkoutComplete"]
+
+
+def _assert_rejected(data, expected_reason):
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "giftCards"
+ assert error["code"] == CheckoutErrorCode.INVALID.name
+ assert error["promoCodeDetails"] == NO_PARAMS | {"reason": expected_reason.name}
+ assert data["order"] is None
+ assert Order.objects.exists() is False
+
+
+def test_expired_gift_card_reports_expired(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ address,
+ checkout_delivery,
+ transaction_item_generator,
+ transaction_events_generator,
+):
+ # given
+ assert checkout_with_gift_card.gift_cards.get() == gift_card
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
+ gift_card.save(update_fields=["expiry_date"])
+ checkout = prepare_checkout_for_test(
+ checkout_with_gift_card,
+ address,
+ address,
+ checkout_delivery(checkout_with_gift_card),
+ transaction_item_generator,
+ transaction_events_generator,
+ )
+
+ # when
+ data = _complete(user_api_client, checkout)
+
+ # then
+ _assert_rejected(data, PromoCodeRejectionReason.EXPIRED)
+
+
+def test_gift_card_restricted_to_another_customer_reports_not_applicable(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ staff_user,
+ address,
+ checkout_delivery,
+ transaction_item_generator,
+ transaction_events_generator,
+):
+ """A card may be assigned to someone else after it was added."""
+ # given
+ assert checkout_with_gift_card.gift_cards.get() == gift_card
+ gift_card.assigned_to = staff_user
+ gift_card.assigned_to_email = staff_user.email
+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])
+ checkout = prepare_checkout_for_test(
+ checkout_with_gift_card,
+ address,
+ address,
+ checkout_delivery(checkout_with_gift_card),
+ transaction_item_generator,
+ transaction_events_generator,
+ user=user_api_client.user,
+ )
+ assert gift_card.assigned_to_id != checkout.user_id
+
+ # when
+ data = _complete(user_api_client, checkout)
+
+ # then
+ _assert_rejected(data, PromoCodeRejectionReason.NOT_APPLICABLE)
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index 62b7fdabf3..5d1f391d01 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -52,6 +52,7 @@ from .....shipping.models import ShippingMethod
from .....tests import race_condition
from .....warehouse.models import Reservation, Stock, WarehouseClickAndCollectOption
from .....warehouse.tests.utils import get_available_quantity_for_stock
+from ....core.enums import PromoCodeRejectionReason
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -124,6 +125,9 @@ MUTATION_CHECKOUT_COMPLETE = """
message,
variants,
code
+ promoCodeDetails {
+ reason
+ }
}
confirmationNeeded
confirmationData
@@ -1094,8 +1098,13 @@ def test_checkout_with_voucher_not_applicable(
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
assert data["errors"][0]["field"] == "voucherCode"
assert data["errors"][0]["code"] == CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.name
+ assert (
+ data["errors"][0]["promoCodeDetails"]["reason"]
+ == PromoCodeRejectionReason.NO_LONGER_AVAILABLE.name
+ )
def test_checkout_with_voucher_inactive_code(
@@ -1138,8 +1147,13 @@ def test_checkout_with_voucher_inactive_code(
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
assert data["errors"][0]["field"] == "voucherCode"
assert data["errors"][0]["code"] == CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.name
+ assert (
+ data["errors"][0]["promoCodeDetails"]["reason"]
+ == PromoCodeRejectionReason.NO_LONGER_AVAILABLE.name
+ )
def test_checkout_with_insufficient_stock(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_promo_code_reason_disclosure.py b/saleor/graphql/checkout/tests/mutations/test_checkout_promo_code_reason_disclosure.py
new file mode 100644
index 0000000000..861db7f62b
--- /dev/null
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_promo_code_reason_disclosure.py
@@ -0,0 +1,242 @@
+"""Guard the information a promo code rejection reason may disclose.
+
+Each test pins a case where reporting a more precise reason would let a caller
+confirm something they are not entitled to know. No reason depends on the
+caller's permissions, so several cases assert that a privileged client gets the
+very same response as an anonymous one.
+"""
+
+import datetime
+
+import pytest
+from django.utils import timezone
+
+from .....checkout.error_codes import CheckoutErrorCode
+from .....discount.models import VoucherCustomer
+from ....core.enums import PromoCodeRejectionReason
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+
+MUTATION_ADD_PROMO_CODE = """
+ mutation($id: ID, $promoCode: String!) {
+ checkoutAddPromoCode(id: $id, promoCode: $promoCode) {
+ errors {
+ field
+ code
+ message
+ promoCodeDetails {
+ reason
+ }
+ }
+ }
+ }
+"""
+
+UNKNOWN_CODE = "NO-SUCH-CODE-AT-ALL"
+
+
+def _add_promo_code(client, checkout, promo_code):
+ variables = {"id": to_global_id_or_none(checkout), "promoCode": promo_code}
+ response = client.post_graphql(MUTATION_ADD_PROMO_CODE, variables)
+ return get_graphql_content(response)["data"]["checkoutAddPromoCode"]
+
+
+def _single_error(data):
+ assert len(data["errors"]) == 1
+ return data["errors"][0]
+
+
+def _yesterday():
+ return datetime.datetime.now(tz=datetime.UTC).date() - datetime.timedelta(days=1)
+
+
+def _set(gift_card, **fields):
+ for name, value in fields.items():
+ setattr(gift_card, name, value)
+ gift_card.save(update_fields=list(fields))
+
+
+# --- an unusable gift card must be indistinguishable from an unknown code ---
+
+
+ ("_case", "setup"),
+ [
+ ("expired", lambda card: _set(card, expiry_date=_yesterday())),
+ ("deactivated", lambda card: _set(card, is_active=False)),
+ ("wrong_currency", lambda card: _set(card, currency="EUR")),
+ ],
+)
+def test_unusable_gift_card_matches_unknown_code(
+ _case, setup, api_client, checkout_with_item, gift_card
+):
+ # given
+ setup(gift_card)
+ baseline = _single_error(
+ _add_promo_code(api_client, checkout_with_item, UNKNOWN_CODE)
+ )
+ assert baseline["promoCodeDetails"] == {
+ "reason": PromoCodeRejectionReason.NOT_FOUND.name
+ }
+
+ # when
+ error = _single_error(
+ _add_promo_code(api_client, checkout_with_item, gift_card.code)
+ )
+
+ # then
+ assert error == baseline
+ assert checkout_with_item.gift_cards.exists() is False
+
+
+def test_gift_card_assigned_to_another_customer_matches_unknown_code(
+ user_api_client, checkout_with_item, gift_card, staff_user
+):
+ # given
+ gift_card.assigned_to = staff_user
+ gift_card.save(update_fields=["assigned_to"])
+ assert gift_card.assigned_to_id != user_api_client.user.pk
+ baseline = _single_error(
+ _add_promo_code(user_api_client, checkout_with_item, UNKNOWN_CODE)
+ )
+
+ # when
+ error = _single_error(
+ _add_promo_code(user_api_client, checkout_with_item, gift_card.code)
+ )
+
+ # then
+ assert error == baseline
+ assert checkout_with_item.gift_cards.exists() is False
+
+
+# --- redemption history is never disclosed ---
+
+
+def _mark_used_by(voucher, email):
+ voucher.apply_once_per_customer = True
+ voucher.save(update_fields=["apply_once_per_customer"])
+ VoucherCustomer.objects.create(
+ voucher_code=voucher.codes.get(), customer_email=email
+ )
+
+
+def test_already_used_reports_generic_reason_to_guest_probing_another_email(
+ api_client, checkout_with_item, voucher, customer_user
+):
+ """A guest may set any email, so the reason must not name the redemption."""
+ # given
+ _mark_used_by(voucher, customer_user.email)
+ checkout_with_item.email = customer_user.email
+ checkout_with_item.save(update_fields=["email"])
+ assert checkout_with_item.user_id is None
+
+ # when
+ error = _single_error(_add_promo_code(api_client, checkout_with_item, voucher.code))
+
+ # then
+ assert error["code"] == CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.name
+ assert error["promoCodeDetails"] == {
+ "reason": PromoCodeRejectionReason.NOT_APPLICABLE.name
+ }
+
+
+def test_already_used_reports_the_same_reason_to_the_owner(
+ user_api_client, checkout_with_item, voucher
+):
+ """The owner learns no more than the guest -- the reason cannot be a probe."""
+ # given
+ customer = user_api_client.user
+ _mark_used_by(voucher, customer.email)
+ checkout_with_item.user = customer
+ checkout_with_item.email = customer.email
+ checkout_with_item.save(update_fields=["user", "email"])
+
+ # when
+ error = _single_error(
+ _add_promo_code(user_api_client, checkout_with_item, voucher.code)
+ )
+
+ # then
+ assert error["code"] == CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.name
+ assert error["promoCodeDetails"] == {
+ "reason": PromoCodeRejectionReason.NOT_APPLICABLE.name
+ }
+
+
+# --- voucher state the caller has no access to stays hidden from everyone ---
+
+
+def _make_not_started(voucher):
+ voucher.start_date = timezone.now() + datetime.timedelta(days=7)
+ voucher.save(update_fields=["start_date"])
+
+
+def _make_out_of_channel(voucher):
+ voucher.channel_listings.all().delete()
+
+
+def _make_out_of_channel_and_expired(voucher):
+ _make_out_of_channel(voucher)
+ voucher.end_date = timezone.now() - datetime.timedelta(days=1)
+ voucher.save(update_fields=["end_date"])
+
+
+def _make_out_of_channel_and_exhausted(voucher):
+ _make_out_of_channel(voucher)
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+ code = voucher.codes.get()
+ code.used = 1
+ code.save(update_fields=["used"])
+
+
+def _make_out_of_channel_with_redeemed_single_use_code(voucher):
+ _make_out_of_channel(voucher)
+ code = voucher.codes.get()
+ code.is_active = False
+ code.save(update_fields=["is_active"])
+
+
+ ("_case", "setup"),
+ [
+ ("unlaunched_campaign", _make_not_started),
+ ("other_channel_campaign", _make_out_of_channel),
+ ("other_channel_campaign_expired", _make_out_of_channel_and_expired),
+ ("other_channel_campaign_exhausted", _make_out_of_channel_and_exhausted),
+ (
+ "other_channel_campaign_redeemed_single_use_code",
+ _make_out_of_channel_with_redeemed_single_use_code,
+ ),
+ ],
+)
+ "client_fixture", ["api_client", "user_api_client", "staff_api_client"]
+)
+def test_inaccessible_voucher_matches_unknown_code(
+ _case,
+ setup,
+ client_fixture,
+ request,
+ checkout_with_item,
+ voucher,
+ permission_manage_discounts,
+):
+ # given
+ setup(voucher)
+ client = request.getfixturevalue(client_fixture)
+ if client.user:
+ client.user.user_permissions.add(permission_manage_discounts)
+ baseline = _single_error(_add_promo_code(client, checkout_with_item, UNKNOWN_CODE))
+
+ # when
+ error = _single_error(_add_promo_code(client, checkout_with_item, voucher.code))
+
+ # then
+ assert error == baseline
+ assert error["promoCodeDetails"] == {
+ "reason": PromoCodeRejectionReason.NOT_FOUND.name
+ }
+ checkout_with_item.refresh_from_db(fields=("voucher_code",))
+ assert checkout_with_item.voucher_code is None
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout_promo_code_details.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout_promo_code_details.py
new file mode 100644
index 0000000000..4e62c80e72
--- /dev/null
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout_promo_code_details.py
@@ -0,0 +1,172 @@
+import datetime
+
+import graphene
+import pytest
+
+from .....checkout.error_codes import OrderCreateFromCheckoutErrorCode
+from .....discount.models import Voucher, VoucherCustomer
+from .....order.models import Order
+from ....core.enums import PromoCodeRejectionReason
+from ....tests.utils import get_graphql_content
+
+MUTATION_ORDER_CREATE_FROM_CHECKOUT = """
+mutation orderCreateFromCheckout($id: ID!) {
+ orderCreateFromCheckout(id: $id) {
+ order {
+ id
+ }
+ errors {
+ field
+ code
+ promoCodeDetails {
+ reason
+ minSpent {
+ amount
+ currency
+ }
+ minCheckoutItemsQuantity
+ }
+ }
+ }
+}
+"""
+
+NO_PARAMS = {"minSpent": None, "minCheckoutItemsQuantity": None}
+
+
+def checkout_ready_for_order(
+ checkout_with_voucher_percentage, address, checkout_delivery
+):
+ checkout = checkout_with_voucher_percentage
+ checkout.email = "[email protected]"
+ checkout.shipping_address = address
+ checkout.billing_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.save()
+ return checkout
+
+
+def _create_order(client, checkout):
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+ response = client.post_graphql(MUTATION_ORDER_CREATE_FROM_CHECKOUT, variables)
+ return get_graphql_content(response)["data"]["orderCreateFromCheckout"]
+
+
+def _assert_rejected(data, expected_reason):
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "voucherCode"
+ assert error["code"] == OrderCreateFromCheckoutErrorCode.VOUCHER_NOT_APPLICABLE.name
+ assert error["promoCodeDetails"] == NO_PARAMS | {"reason": expected_reason.name}
+ assert data["order"] is None
+ assert Order.objects.exists() is False
+
+
+def test_voucher_no_longer_available(
+ app_api_client, permission_handle_checkouts, checkout_ready_for_order
+):
+ """Report the reason from the pre-order checkout validation."""
+ # given
+ app_api_client.app.permissions.add(permission_handle_checkouts)
+ assert checkout_ready_for_order.voucher_code is not None
+ Voucher.objects.all().delete()
+
+ # when
+ data = _create_order(app_api_client, checkout_ready_for_order)
+
+ # then
+ _assert_rejected(data, PromoCodeRejectionReason.NO_LONGER_AVAILABLE)
+
+
+def test_voucher_not_applicable_for_customer(
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_ready_for_order,
+ voucher_percentage,
+):
+ """Report the reason from a `NotApplicable` raised while placing the order."""
+ # given
+ app_api_client.app.permissions.add(permission_handle_checkouts)
+ voucher_percentage.apply_once_per_customer = True
+ voucher_percentage.save(update_fields=["apply_once_per_customer"])
+ VoucherCustomer.objects.create(
+ voucher_code=voucher_percentage.codes.get(),
+ customer_email=checkout_ready_for_order.email,
+ )
+
+ # when
+ data = _create_order(app_api_client, checkout_ready_for_order)
+
+ # then
+ _assert_rejected(data, PromoCodeRejectionReason.NOT_APPLICABLE)
+
+
+def checkout_with_gift_card_ready_for_order(
+ checkout_with_gift_card, address, checkout_delivery
+):
+ checkout = checkout_with_gift_card
+ checkout.email = "[email protected]"
+ checkout.shipping_address = address
+ checkout.billing_address = address
+ checkout.assigned_delivery = checkout_delivery(checkout)
+ checkout.save()
+ return checkout
+
+
+def _expire(gift_card, _staff_user):
+ gift_card.expiry_date = datetime.datetime.now(
+ tz=datetime.UTC
+ ).date() - datetime.timedelta(days=1)
+ gift_card.save(update_fields=["expiry_date"])
+
+
+def _assign_to_another_customer(gift_card, staff_user):
+ gift_card.assigned_to = staff_user
+ gift_card.assigned_to_email = staff_user.email
+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])
+
+
+ ("_case", "setup", "expected_reason"),
+ [
+ ("expired", _expire, PromoCodeRejectionReason.EXPIRED),
+ (
+ "assigned_to_another_customer",
+ _assign_to_another_customer,
+ PromoCodeRejectionReason.NOT_APPLICABLE,
+ ),
+ ],
+)
+def test_gift_card_no_longer_usable(
+ _case,
+ setup,
+ expected_reason,
+ app_api_client,
+ permission_handle_checkouts,
+ checkout_with_gift_card_ready_for_order,
+ gift_card,
+ staff_user,
+):
+ """Report a gift card rejected by the pre-order checkout validation."""
+ # given
+ app_api_client.app.permissions.add(permission_handle_checkouts)
+ checkout = checkout_with_gift_card_ready_for_order
+ assert checkout.gift_cards.get() == gift_card
+ assert checkout.user_id != staff_user.pk
+ setup(gift_card, staff_user)
+
+ # when
+ data = _create_order(app_api_client, checkout)
+
+ # then
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "giftCards"
+ assert (
+ error["code"] == OrderCreateFromCheckoutErrorCode.GIFT_CARD_NOT_APPLICABLE.name
+ )
+ assert error["promoCodeDetails"] == NO_PARAMS | {"reason": expected_reason.name}
+ assert data["order"] is None
+ assert Order.objects.exists() is False
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 112acfaaf9..d16cbe147d 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -18,6 +18,7 @@ from ...core.units import (
WeightUnits,
)
from ...csv import error_codes as csv_error_codes
+from ...discount import PromoCodeRejectionReason as promo_code_rejection_reason
from ...discount import error_codes as discount_error_codes
from ...giftcard import error_codes as giftcard_error_codes
from ...invoice import error_codes as invoice_error_codes
@@ -280,6 +281,73 @@ VoucherCodeBulkDeleteErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(
)
VoucherCodeBulkDeleteErrorCode.doc_category = DOC_CATEGORY_DISCOUNTS
+
+def promo_code_rejection_reason_description(enum):
+ if enum is None:
+ return (
+ "The specific reason why a promo code cannot be applied. "
+ "A code that has not been proven usable yet is only ever reported "
+ "as `NOT_FOUND`, `EXPIRED` or `USAGE_LIMIT_REACHED`, so that a "
+ "rejected code cannot be told apart from one that does not exist. "
+ "The reason never depends on the caller's permissions."
+ )
+ return {
+ promo_code_rejection_reason.NOT_FOUND: (
+ "No promo code matches the given code. Also reported in place of a "
+ "reason that may not be disclosed, so this value does not prove "
+ "that no voucher or gift card exists with that code."
+ ),
+ promo_code_rejection_reason.EXPIRED: (
+ "The voucher's end date, or the gift card's expiry date, is in the past."
+ ),
+ promo_code_rejection_reason.USAGE_LIMIT_REACHED: (
+ "The voucher's total usage limit, summed over all of its codes, is "
+ "exhausted, or a single-use code was already redeemed."
+ ),
+ promo_code_rejection_reason.NOT_APPLICABLE: (
+ "The promo code exists but cannot be used here. Reported when the "
+ "reason is specific to the code's configuration rather than to "
+ "something the customer can change: a voucher limited to staff, to "
+ "other countries, to another channel or to one use per customer, "
+ "or a gift card restricted to another customer."
+ ),
+ promo_code_rejection_reason.MIN_SPENT_NOT_REACHED: (
+ "The order value is below the voucher's minimum. "
+ "Populates the `minSpent` field."
+ ),
+ promo_code_rejection_reason.MIN_QUANTITY_NOT_REACHED: (
+ "The order contains fewer items than the voucher's minimum. "
+ "Populates the `minCheckoutItemsQuantity` field."
+ ),
+ promo_code_rejection_reason.CUSTOMER_EMAIL_REQUIRED: (
+ "The voucher is limited to one use per customer, so a customer email "
+ "must be set on the checkout before it can be applied."
+ ),
+ promo_code_rejection_reason.SHIPPING_NOT_REQUIRED: (
+ "The voucher applies to shipping, but nothing in the order requires "
+ "shipping."
+ ),
+ promo_code_rejection_reason.DELIVERY_METHOD_NOT_SET: (
+ "The voucher applies to shipping, but no delivery method is selected "
+ "yet. Selecting one may make the voucher applicable."
+ ),
+ promo_code_rejection_reason.NO_ELIGIBLE_PRODUCTS: (
+ "The voucher applies to specific products, collections or categories, "
+ "and none of the ordered lines match."
+ ),
+ promo_code_rejection_reason.NO_LONGER_AVAILABLE: (
+ "The promo code was applicable when it was added to the checkout, "
+ "but is no longer available."
+ ),
+ }.get(enum)
+
+
+PromoCodeRejectionReason: Final[graphene.Enum] = graphene.Enum.from_enum(
+ promo_code_rejection_reason,
+ description=promo_code_rejection_reason_description,
+)
+PromoCodeRejectionReason.doc_category = DOC_CATEGORY_DISCOUNTS
+
PluginErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(
plugin_error_codes.PluginErrorCode
)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 001a820849..dae8bfb4bb 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -68,6 +68,7 @@ from ..enums import (
ProductTranslateErrorCode,
ProductVariantBulkErrorCode,
ProductVariantTranslateErrorCode,
+ PromoCodeRejectionReason,
RefundSettingsErrorCode,
ReturnSettingsErrorCode,
SendConfirmationEmailErrorCode,
@@ -97,7 +98,7 @@ from ..enums import (
from ..scalars import Date, PositiveDecimal
from ..tracing import traced_resolver
from .base import BaseObjectType
-from .money import VAT
+from .money import VAT, Money
from .upload import Upload
if TYPE_CHECKING:
@@ -262,6 +263,40 @@ class ChannelError(Error):
doc_category = DOC_CATEGORY_CHANNELS
+PROMO_CODE_DETAILS_DESCRIPTION = (
+ "Details of the promo code that caused the error. Null when the error is "
+ "not a promo code rejection." + ADDED_IN_323
+)
+
+
+class PromoCodeRejectionDetails(BaseObjectType):
+ reason = PromoCodeRejectionReason(
+ description="The specific reason why the promo code cannot be applied.",
+ required=True,
+ )
+ min_spent = graphene.Field(
+ Money,
+ description=(
+ "The minimum order value required by the voucher. "
+ "Set only when `reason` is `MIN_SPENT_NOT_REACHED`."
+ ),
+ required=False,
+ )
+ min_checkout_items_quantity = graphene.Int(
+ description=(
+ "The minimum number of items required by the voucher. "
+ "Set only when `reason` is `MIN_QUANTITY_NOT_REACHED`."
+ ),
+ required=False,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_CHECKOUT
+ description = (
+ "Details explaining why a promo code cannot be applied." + ADDED_IN_323
+ )
+
+
class CheckoutError(Error):
code = CheckoutErrorCode(description="The error code.", required=True)
variants = NonNullList(
@@ -277,6 +312,11 @@ class CheckoutError(Error):
address_type = AddressTypeEnum(
description="A type of address that causes the error.", required=False
)
+ promo_code_details = graphene.Field(
+ PromoCodeRejectionDetails,
+ description=PROMO_CODE_DETAILS_DESCRIPTION,
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_CHECKOUT
@@ -416,6 +456,11 @@ class OrderError(Error):
address_type = AddressTypeEnum(
description="A type of address that causes the error.", required=False
)
+ promo_code_details = graphene.Field(
+ PromoCodeRejectionDetails,
+ description=PROMO_CODE_DETAILS_DESCRIPTION,
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
diff --git a/saleor/graphql/order/mutations/draft_order_cleaner.py b/saleor/graphql/order/mutations/draft_order_cleaner.py
index e052e88db3..b2c80f143b 100644
--- a/saleor/graphql/order/mutations/draft_order_cleaner.py
+++ b/saleor/graphql/order/mutations/draft_order_cleaner.py
@@ -1,6 +1,7 @@
from django.core.exceptions import ValidationError
from ....channel.models import Channel
+from ....core.utils.promo_code import InvalidPromoCode
from ....core.utils.url import validate_storefront_url
from ....discount.models import Voucher, VoucherCode
from ....discount.utils.voucher import (
@@ -43,7 +44,11 @@ def clean_voucher_and_voucher_code(channel: "Channel", cleaned_input: dict):
clean_voucher_code(voucher_code, channel, cleaned_input)
-def clean_voucher(voucher: Voucher | None, channel: Channel, cleaned_input: dict):
+def clean_voucher(
+ voucher: Voucher | None,
+ channel: Channel,
+ cleaned_input: dict,
+):
# We need to clean voucher_code as well
if voucher is None:
cleaned_input["voucher_code"] = None
@@ -64,12 +69,13 @@ def clean_voucher(voucher: Voucher | None, channel: Channel, cleaned_input: dict
validate_usage = channel.include_draft_order_in_voucher_usage
try:
code_instance = get_active_voucher_code(voucher, channel.slug, validate_usage)
- except ValidationError as e:
+ except InvalidPromoCode as e:
raise ValidationError(
{
"voucher": ValidationError(
"Voucher is invalid.",
code=OrderErrorCode.INVALID_VOUCHER.value,
+ params={"promo_code_details": e.rejection},
)
}
) from e
@@ -80,7 +86,11 @@ def clean_voucher(voucher: Voucher | None, channel: Channel, cleaned_input: dict
cleaned_input["voucher_code_instance"] = code_instance
-def clean_voucher_code(voucher_code: str | None, channel: Channel, cleaned_input: dict):
+def clean_voucher_code(
+ voucher_code: str | None,
+ channel: Channel,
+ cleaned_input: dict,
+):
# We need to clean voucher instance as well
if voucher_code is None:
cleaned_input["voucher"] = None
@@ -90,12 +100,13 @@ def clean_voucher_code(voucher_code: str | None, channel: Channel, cleaned_input
code_instance = get_voucher_code_instance(
voucher_code, channel.slug, validate_usage
)
- except ValidationError as e:
+ except InvalidPromoCode as e:
raise ValidationError(
{
"voucher_code": ValidationError(
"Voucher code is invalid.",
code=OrderErrorCode.INVALID_VOUCHER_CODE.value,
+ params={"promo_code_details": e.rejection},
)
}
) from e
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_promo_code_details.py b/saleor/graphql/order/tests/mutations/test_draft_order_promo_code_details.py
new file mode 100644
index 0000000000..5b756480c4
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_promo_code_details.py
@@ -0,0 +1,289 @@
+import datetime
+
+import graphene
+import pytest
+from django.utils import timezone
+
+from .....discount.models import VoucherCustomer
+from .....order import OrderStatus
+from .....order.error_codes import OrderErrorCode
+from ....core.enums import PromoCodeRejectionReason
+from ....tests.utils import get_graphql_content
+
+DRAFT_ORDER_UPDATE_MUTATION = """
+ mutation draftUpdate($id: ID!, $input: DraftOrderInput!) {
+ draftOrderUpdate(id: $id, input: $input) {
+ errors {
+ field
+ code
+ promoCodeDetails {
+ reason
+ minSpent {
+ amount
+ currency
+ }
+ minCheckoutItemsQuantity
+ }
+ }
+ }
+ }
+"""
+
+DRAFT_ORDER_COMPLETE_MUTATION = """
+ mutation draftComplete($id: ID!) {
+ draftOrderComplete(id: $id) {
+ order {
+ id
+ }
+ errors {
+ field
+ code
+ promoCodeDetails {
+ reason
+ minSpent {
+ amount
+ currency
+ }
+ minCheckoutItemsQuantity
+ }
+ }
+ }
+ }
+"""
+
+NO_PARAMS = {"minSpent": None, "minCheckoutItemsQuantity": None}
+
+
+def _expire(voucher):
+ voucher.end_date = timezone.now() - datetime.timedelta(days=1)
+ voucher.save(update_fields=["end_date"])
+
+
+def _deactivate_code(voucher):
+ code = voucher.codes.get()
+ code.is_active = False
+ code.save(update_fields=["is_active"])
+
+
+def _exhaust(voucher):
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+ code = voucher.codes.get()
+ code.used = 1
+ code.save(update_fields=["used"])
+
+
+def _remove_from_channel(voucher):
+ voucher.channel_listings.all().delete()
+
+
+def _remove_from_channel_and_expire(voucher):
+ _remove_from_channel(voucher)
+ _expire(voucher)
+
+
+def _remove_from_channel_and_exhaust(voucher):
+ _remove_from_channel(voucher)
+ _exhaust(voucher)
+
+
+def _remove_from_channel_and_deactivate_code(voucher):
+ _remove_from_channel(voucher)
+ _deactivate_code(voucher)
+
+
+def _delete_all_codes(voucher):
+ voucher.codes.all().delete()
+
+
+HIDDEN_VOUCHER_CASES = [
+ ("other_channel", _remove_from_channel, PromoCodeRejectionReason.NOT_FOUND),
+ (
+ "other_channel_and_expired",
+ _remove_from_channel_and_expire,
+ PromoCodeRejectionReason.NOT_FOUND,
+ ),
+ (
+ "other_channel_and_exhausted",
+ _remove_from_channel_and_exhaust,
+ PromoCodeRejectionReason.NOT_FOUND,
+ ),
+ (
+ "other_channel_and_redeemed_single_use_code",
+ _remove_from_channel_and_deactivate_code,
+ PromoCodeRejectionReason.NOT_FOUND,
+ ),
+]
+
+
+def _assert_single_error(data, expected_code, expected_field, expected_reason):
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == expected_field
+ assert error["code"] == expected_code.name
+ assert error["promoCodeDetails"] == NO_PARAMS | {"reason": expected_reason.name}
+
+
+ ("_case", "setup", "expected_reason"),
+ [
+ ("expired_voucher", _expire, PromoCodeRejectionReason.EXPIRED),
+ (
+ "redeemed_single_use_code",
+ _deactivate_code,
+ PromoCodeRejectionReason.USAGE_LIMIT_REACHED,
+ ),
+ *HIDDEN_VOUCHER_CASES,
+ ],
+)
+def test_draft_order_update_voucher_code(
+ _case,
+ setup,
+ expected_reason,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher,
+):
+ """Report the rejection reason for the `voucherCode` input."""
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ code = voucher.codes.get().code
+ setup(voucher)
+ variables = {
+ "id": graphene.Node.to_global_id("Order", draft_order.pk),
+ "input": {"voucherCode": code},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_UPDATE_MUTATION, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["draftOrderUpdate"]
+ _assert_single_error(
+ data, OrderErrorCode.INVALID_VOUCHER_CODE, "voucherCode", expected_reason
+ )
+ draft_order.refresh_from_db(fields=("voucher_code",))
+ assert draft_order.voucher_code is None
+
+
+def test_draft_order_update_unknown_voucher_code(
+ staff_api_client, permission_group_manage_orders, draft_order
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ variables = {
+ "id": graphene.Node.to_global_id("Order", draft_order.pk),
+ "input": {"voucherCode": "THIS-CODE-DOES-NOT-EXIST"},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_UPDATE_MUTATION, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["draftOrderUpdate"]
+ _assert_single_error(
+ data,
+ OrderErrorCode.INVALID_VOUCHER_CODE,
+ "voucherCode",
+ PromoCodeRejectionReason.NOT_FOUND,
+ )
+
+
+ ("_case", "setup", "expected_reason"),
+ [
+ ("expired_voucher", _expire, PromoCodeRejectionReason.EXPIRED),
+ (
+ "redeemed_single_use_code",
+ _deactivate_code,
+ PromoCodeRejectionReason.USAGE_LIMIT_REACHED,
+ ),
+ ("no_codes_left", _delete_all_codes, PromoCodeRejectionReason.NOT_FOUND),
+ *HIDDEN_VOUCHER_CASES,
+ ],
+)
+def test_draft_order_update_voucher(
+ _case,
+ setup,
+ expected_reason,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher,
+):
+ """Report the rejection reason for the deprecated `voucher` ID input."""
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ setup(voucher)
+ variables = {
+ "id": graphene.Node.to_global_id("Order", draft_order.pk),
+ "input": {"voucher": graphene.Node.to_global_id("Voucher", voucher.pk)},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_UPDATE_MUTATION, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["draftOrderUpdate"]
+ _assert_single_error(
+ data, OrderErrorCode.INVALID_VOUCHER, "voucher", expected_reason
+ )
+ draft_order.refresh_from_db(fields=("voucher_id",))
+ assert draft_order.voucher_id is None
+
+
+def test_draft_order_complete_voucher_not_in_channel(
+ staff_api_client, permission_group_manage_orders, draft_order_with_voucher
+):
+ """Report the rejection reason raised while validating the draft order."""
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order_with_voucher
+ order.voucher.channel_listings.all().delete()
+ variables = {"id": graphene.Node.to_global_id("Order", order.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["draftOrderComplete"]
+ _assert_single_error(
+ data,
+ OrderErrorCode.INVALID_VOUCHER,
+ "voucher",
+ PromoCodeRejectionReason.NOT_APPLICABLE,
+ )
+ assert data["order"] is None
+
+
+def test_draft_order_complete_once_per_customer_voucher_without_email(
+ staff_api_client, permission_group_manage_orders, draft_order_with_voucher
+):
+ """Report the missing email instead of failing while recording the usage."""
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order_with_voucher
+ assert order.channel.include_draft_order_in_voucher_usage is True
+ order.voucher.apply_once_per_customer = True
+ order.voucher.save(update_fields=["apply_once_per_customer"])
+ order.user = None
+ order.user_email = ""
+ order.save(update_fields=["user", "user_email"])
+ variables = {"id": graphene.Node.to_global_id("Order", order.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
+
+ # then
+ data = get_graphql_content(response)["data"]["draftOrderComplete"]
+ _assert_single_error(
+ data,
+ OrderErrorCode.INVALID_VOUCHER,
+ "voucher",
+ PromoCodeRejectionReason.CUSTOMER_EMAIL_REQUIRED,
+ )
+ assert data["order"] is None
+ order.refresh_from_db(fields=("status",))
+ assert order.status == OrderStatus.DRAFT
+ assert VoucherCustomer.objects.exists() is False
diff --git a/saleor/graphql/order/tests/queries/test_order_can_finalize.py b/saleor/graphql/order/tests/queries/test_order_can_finalize.py
index 0c6cee90bf..08ac6a855a 100644
--- a/saleor/graphql/order/tests/queries/test_order_can_finalize.py
+++ b/saleor/graphql/order/tests/queries/test_order_can_finalize.py
@@ -2,9 +2,11 @@ import datetime
import graphene
+from .....discount import NOT_APPLICABLE_MESSAGE
from .....order import OrderStatus
from .....order.error_codes import OrderErrorCode
from .....product.models import ProductVariant
+from ....core.enums import PromoCodeRejectionReason
from ....tests.utils import get_graphql_content
ORDER_CAN_FINALIZE_QUERY = """
@@ -188,3 +190,52 @@ def test_can_finalize_order_invalid_voucher(
assert len(errors) == 1
assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER.name
assert errors[0]["field"] == "voucher"
+
+
+ORDER_ERRORS_PROMO_CODE_DETAILS_QUERY = """
+ query OrderQuery($id: ID!){
+ order(id: $id){
+ canFinalize
+ errors {
+ code
+ field
+ message
+ promoCodeDetails {
+ reason
+ }
+ }
+ }
+ }
+"""
+
+
+def test_errors_report_voucher_rejection_reason(
+ staff_api_client, permission_manage_orders, draft_order_with_voucher
+):
+ # given
+ order = draft_order_with_voucher
+ assert order.channel.include_draft_order_in_voucher_usage is True
+ order.voucher.channel_listings.all().delete()
+
+ variables = {"id": graphene.Node.to_global_id("Order", order.pk)}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_ERRORS_PROMO_CODE_DETAILS_QUERY, variables
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["order"]
+ assert data["canFinalize"] is False
+ assert data["errors"] == [
+ {
+ "code": OrderErrorCode.INVALID_VOUCHER.name,
+ "field": "voucher",
+ "message": NOT_APPLICABLE_MESSAGE,
+ "promoCodeDetails": {
+ "reason": PromoCodeRejectionReason.NOT_APPLICABLE.name
+ },
+ }
+ ]
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index eac5ad42d7..03906a4ecf 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -357,6 +357,7 @@ def _validate_voucher(
ValidationError(
message=e.args[0],
code=OrderErrorCode.INVALID_VOUCHER.value,
+ params={"promo_code_details": e.rejection},
)
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index fdb126f351..8adac8a1b9 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -13374,6 +13374,13 @@ type OrderError @doc(category: "Orders") {
"""A type of address that causes the error."""
addressType: AddressTypeEnum
+
+ """
+ Details of the promo code that caused the error. Null when the error is not a promo code rejection.
+
+ Added in Saleor 3.23.
+ """
+ promoCodeDetails: PromoCodeRejectionDetails
}
enum OrderErrorCode @doc(category: "Orders") {
@@ -13421,6 +13428,86 @@ enum AddressTypeEnum {
SHIPPING
}
+"""
+Details explaining why a promo code cannot be applied.
+
+Added in Saleor 3.23.
+"""
+type PromoCodeRejectionDetails @doc(category: "Checkout") {
+ """The specific reason why the promo code cannot be applied."""
+ reason: PromoCodeRejectionReason!
+
+ """
+ The minimum order value required by the voucher. Set only when `reason` is `MIN_SPENT_NOT_REACHED`.
+ """
+ minSpent: Money
+
+ """
+ The minimum number of items required by the voucher. Set only when `reason` is `MIN_QUANTITY_NOT_REACHED`.
+ """
+ minCheckoutItemsQuantity: Int
+}
+
+"""
+The specific reason why a promo code cannot be applied. A code that has not been proven usable yet is only ever reported as `NOT_FOUND`, `EXPIRED` or `USAGE_LIMIT_REACHED`, so that a rejected code cannot be told apart from one that does not exist. The reason never depends on the caller's permissions.
+"""
+enum PromoCodeRejectionReason @doc(category: "Discounts") {
+ """
+ No promo code matches the given code. Also reported in place of a reason that may not be disclosed, so this value does not prove that no voucher or gift card exists with that code.
+ """
+ NOT_FOUND
+
+ """
+ The voucher's end date, or the gift card's expiry date, is in the past.
+ """
+ EXPIRED
+
+ """
+ The voucher's total usage limit, summed over all of its codes, is exhausted, or a single-use code was already redeemed.
+ """
+ USAGE_LIMIT_REACHED
+
+ """
+ The promo code exists but cannot be used here. Reported when the reason is specific to the code's configuration rather than to something the customer can change: a voucher limited to staff, to other countries, to another channel or to one use per customer, or a gift card restricted to another customer.
+ """
+ NOT_APPLICABLE
+
+ """
+ The order value is below the voucher's minimum. Populates the `minSpent` field.
+ """
+ MIN_SPENT_NOT_REACHED
+
+ """
+ The order contains fewer items than the voucher's minimum. Populates the `minCheckoutItemsQuantity` field.
+ """
+ MIN_QUANTITY_NOT_REACHED
+
+ """
+ The voucher is limited to one use per customer, so a customer email must be set on the checkout before it can be applied.
+ """
+ CUSTOMER_EMAIL_REQUIRED
+
+ """
+ The voucher applies to shipping, but nothing in the order requires shipping.
+ """
+ SHIPPING_NOT_REQUIRED
+
+ """
+ The voucher applies to shipping, but no delivery method is selected yet. Selecting one may make the voucher applicable.
+ """
+ DELIVERY_METHOD_NOT_SET
+
+ """
+ The voucher applies to specific products, collections or categories, and none of the ordered lines match.
+ """
+ NO_ELIGIBLE_PRODUCTS
+
+ """
+ The promo code was applicable when it was added to the checkout, but is no longer available.
+ """
+ NO_LONGER_AVAILABLE
+}
+
"""The details of granted refund."""
type OrderGrantedRefund @doc(category: "Orders") {
id: ID!
@@ -31065,6 +31152,13 @@ type CheckoutError @doc(category: "Checkout") {
"""A type of address that causes the error."""
addressType: AddressTypeEnum
+
+ """
+ Details of the promo code that caused the error. Null when the error is not a promo code rejection.
+
+ Added in Saleor 3.23.
+ """
+ promoCodeDetails: PromoCodeRejectionDetails
}
enum CheckoutErrorCode @doc(category: "Checkout") {
@@ -31652,6 +31746,13 @@ type OrderCreateFromCheckoutError @doc(category: "Orders") {
"""List of line Ids which cause the error."""
lines: [ID!]
+
+ """
+ Details of the promo code that caused the error. Null when the error is not a promo code rejection.
+
+ Added in Saleor 3.23.
+ """
+ promoCodeDetails: PromoCodeRejectionDetails
}
enum OrderCreateFromCheckoutErrorCode @doc(category: "Orders") {