Skip to content

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

Improve voucher validations in draft orders (#18728)

Iga Karbowiaka047cef2564d
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 94f51b3c23..3440406c24 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -50,7 +50,7 @@ class NotApplicable(ValueError):
class VoucherQueryset(models.QuerySet["Voucher"]):
- def active(self, date):
+ def active(self, date, validate_usage_limit=True):
subquery = (
VoucherCode.objects.filter(voucher_id=OuterRef("pk"))
.order_by()
@@ -58,13 +58,16 @@ class VoucherQueryset(models.QuerySet["Voucher"]):
.annotate(total_used=Sum("used"))
.values("total_used")
)
- return self.filter(
- Q(usage_limit__isnull=True) | Q(usage_limit__gt=Subquery(subquery)),
- Q(end_date__isnull=True) | Q(end_date__gte=date),
- start_date__lte=date,
+ lookup = (Q(end_date__isnull=True) | Q(end_date__gte=date)) & Q(
+ start_date__lte=date
)
+ if validate_usage_limit:
+ lookup &= Q(usage_limit__isnull=True) | Q(
+ usage_limit__gt=Subquery(subquery)
+ )
+ return self.filter(lookup)
- def active_in_channel(self, date, channel_slug: str):
+ def active_in_channel(self, date, channel_slug: str, validate_usage_limit=True):
channels = Channel.objects.filter(
slug=str(channel_slug), is_active=True
).values("id")
@@ -72,7 +75,7 @@ class VoucherQueryset(models.QuerySet["Voucher"]):
Exists(channels.filter(pk=OuterRef("channel_id"))),
).values("id")
- return self.active(date).filter(
+ return self.active(date, validate_usage_limit).filter(
Exists(channel_listings.filter(voucher_id=OuterRef("pk")))
)
diff --git a/saleor/discount/utils/voucher.py b/saleor/discount/utils/voucher.py
index 9f4d906249..d1ca06703f 100644
--- a/saleor/discount/utils/voucher.py
+++ b/saleor/discount/utils/voucher.py
@@ -148,11 +148,14 @@ def release_voucher_code_usage(
def get_voucher_code_instance(
voucher_code: str,
channel_slug: str,
+ validate_usage_limit=True,
):
"""Return a voucher code instance if it's valid or raise an error."""
if (
Voucher.objects.active_in_channel(
- date=timezone.now(), channel_slug=channel_slug
+ date=timezone.now(),
+ channel_slug=channel_slug,
+ validate_usage_limit=validate_usage_limit,
)
.filter(
Exists(
@@ -171,13 +174,15 @@ def get_voucher_code_instance(
return code_instance
-def get_active_voucher_code(voucher, channel_slug):
+def get_active_voucher_code(voucher, channel_slug, validate_usage_limit=True):
"""Return an active VoucherCode instance.
This method along with `Voucher.code` should be removed in Saleor 4.0.
"""
- voucher_queryset = Voucher.objects.active_in_channel(timezone.now(), channel_slug)
+ voucher_queryset = Voucher.objects.active_in_channel(
+ timezone.now(), channel_slug, validate_usage_limit
+ )
if not voucher_queryset.filter(pk=voucher.pk).exists():
raise InvalidPromoCode()
voucher_code = VoucherCode.objects.filter(voucher=voucher, is_active=True).first()
diff --git a/saleor/graphql/order/mutations/draft_order_cleaner.py b/saleor/graphql/order/mutations/draft_order_cleaner.py
index 08fe397318..e052e88db3 100644
--- a/saleor/graphql/order/mutations/draft_order_cleaner.py
+++ b/saleor/graphql/order/mutations/draft_order_cleaner.py
@@ -61,21 +61,18 @@ def clean_voucher(voucher: Voucher | None, channel: Channel, cleaned_input: dict
)
code_instance = None
- if channel.include_draft_order_in_voucher_usage:
- # Validate voucher when it's included in voucher usage calculation
- try:
- code_instance = get_active_voucher_code(voucher, channel.slug)
- except ValidationError as e:
- raise ValidationError(
- {
- "voucher": ValidationError(
- "Voucher is invalid.",
- code=OrderErrorCode.INVALID_VOUCHER.value,
- )
- }
- ) from e
- else:
- clean_voucher_listing(voucher, channel, "voucher")
+ 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:
+ raise ValidationError(
+ {
+ "voucher": ValidationError(
+ "Voucher is invalid.",
+ code=OrderErrorCode.INVALID_VOUCHER.value,
+ )
+ }
+ ) from e
if not code_instance:
code_instance = voucher.codes.first()
if code_instance:
@@ -88,33 +85,21 @@ def clean_voucher_code(voucher_code: str | None, channel: Channel, cleaned_input
if voucher_code is None:
cleaned_input["voucher"] = None
return
- if channel.include_draft_order_in_voucher_usage:
- # Validate voucher when it's included in voucher usage calculation
- try:
- code_instance = get_voucher_code_instance(voucher_code, channel.slug)
- except ValidationError as e:
- raise ValidationError(
- {
- "voucher_code": ValidationError(
- "Voucher code is invalid.",
- code=OrderErrorCode.INVALID_VOUCHER_CODE.value,
- )
- }
- ) from e
- voucher = code_instance.voucher
- else:
- code_instance = VoucherCode.objects.filter(code=voucher_code).first()
- if not code_instance:
- raise ValidationError(
- {
- "voucher": ValidationError(
- "Invalid voucher code.",
- code=OrderErrorCode.INVALID_VOUCHER_CODE.value,
- )
- }
- )
- voucher = code_instance.voucher
- clean_voucher_listing(voucher, channel, "voucher_code")
+ validate_usage = channel.include_draft_order_in_voucher_usage
+ try:
+ code_instance = get_voucher_code_instance(
+ voucher_code, channel.slug, validate_usage
+ )
+ except ValidationError as e:
+ raise ValidationError(
+ {
+ "voucher_code": ValidationError(
+ "Voucher code is invalid.",
+ code=OrderErrorCode.INVALID_VOUCHER_CODE.value,
+ )
+ }
+ ) from e
+ voucher = code_instance.voucher
cleaned_input["voucher"] = voucher
cleaned_input["voucher_code"] = voucher_code
cleaned_input["voucher_code_instance"] = code_instance
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index 8529997ffd..7dd8e2ba40 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -1608,7 +1608,6 @@ def test_draft_order_create_with_inactive_channel(
product_without_shipping,
shipping_method,
variant,
- voucher,
channel_USD,
graphql_address_data,
):
@@ -1636,7 +1635,6 @@ def test_draft_order_create_with_inactive_channel(
]
shipping_address = graphql_address_data
shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
- voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
variables = {
"input": {
@@ -1644,7 +1642,6 @@ def test_draft_order_create_with_inactive_channel(
"lines": variant_list,
"shippingAddress": shipping_address,
"shippingMethod": shipping_id,
- "voucher": voucher_id,
"customerNote": customer_note,
"channelId": channel_id,
}
@@ -1654,7 +1651,6 @@ def test_draft_order_create_with_inactive_channel(
assert not content["data"]["draftOrderCreate"]["errors"]
data = content["data"]["draftOrderCreate"]["order"]
assert data["status"] == OrderStatus.DRAFT.upper()
- assert data["voucher"]["code"] == voucher.code
assert data["customerNote"] == customer_note
order = Order.objects.first()
@@ -1939,7 +1935,7 @@ def test_draft_order_create_with_voucher_not_assigned_to_order_channel(
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
error = content["data"]["draftOrderCreate"]["errors"][0]
- assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
+ assert error["code"] == OrderErrorCode.INVALID_VOUCHER.name
assert error["field"] == "voucher"
@@ -4153,3 +4149,245 @@ def test_draft_order_create_sets_product_type_id_for_order_line(
order_line = OrderLine.objects.first()
assert order_line.product_type_id == expected_product_type_id
+
+
[email protected]("include_draft_order_in_voucher_usage", [True, False])
+def test_draft_order_create_with_expired_voucher(
+ include_draft_order_in_voucher_usage,
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ variant,
+ voucher,
+ channel_USD,
+ graphql_address_data,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ channel_USD.include_draft_order_in_voucher_usage = (
+ include_draft_order_in_voucher_usage
+ )
+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ # Set voucher end date to the past
+ voucher.end_date = timezone.now() - timedelta(days=1)
+ voucher.save(update_fields=["end_date"])
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variant_qty = 2
+
+ variant_list = [
+ {"variantId": variant_id, "quantity": variant_qty},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "channelId": channel_id,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["draftOrderCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER.name
+ assert errors[0]["field"] == "voucher"
+
+
[email protected]("include_draft_order_in_voucher_usage", [True, False])
+def test_draft_order_create_with_expired_voucher_code(
+ include_draft_order_in_voucher_usage,
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ variant,
+ voucher,
+ channel_USD,
+ graphql_address_data,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ channel_USD.include_draft_order_in_voucher_usage = (
+ include_draft_order_in_voucher_usage
+ )
+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ # Set voucher end date to the past
+ voucher.end_date = timezone.now() - timedelta(days=1)
+ voucher.save(update_fields=["end_date"])
+
+ code = voucher.codes.first()
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variant_qty = 2
+
+ variant_list = [
+ {"variantId": variant_id, "quantity": variant_qty},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucherCode": code.code,
+ "channelId": channel_id,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["draftOrderCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER_CODE.name
+ assert errors[0]["field"] == "voucherCode"
+
+
[email protected]("include_draft_order_in_voucher_usage", [True, False])
+def test_draft_order_create_with_inactive_voucher(
+ include_draft_order_in_voucher_usage,
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ variant,
+ voucher,
+ channel_USD,
+ graphql_address_data,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ channel_USD.include_draft_order_in_voucher_usage = (
+ include_draft_order_in_voucher_usage
+ )
+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ # Set voucher code to inactive
+ code = voucher.codes.first()
+ code.is_active = False
+ code.save(update_fields=["is_active"])
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variant_qty = 2
+
+ variant_list = [
+ {"variantId": variant_id, "quantity": variant_qty},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "channelId": channel_id,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["draftOrderCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER.name
+ assert errors[0]["field"] == "voucher"
+
+
[email protected]("include_draft_order_in_voucher_usage", [True, False])
+def test_draft_order_create_with_inactive_voucher_code(
+ include_draft_order_in_voucher_usage,
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ variant,
+ voucher,
+ channel_USD,
+ graphql_address_data,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ channel_USD.include_draft_order_in_voucher_usage = (
+ include_draft_order_in_voucher_usage
+ )
+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ # Set voucher code to inactive
+ code = voucher.codes.first()
+ code.is_active = False
+ code.save(update_fields=["is_active"])
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variant_qty = 2
+
+ variant_list = [
+ {"variantId": variant_id, "quantity": variant_qty},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucherCode": code.code,
+ "channelId": channel_id,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["draftOrderCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER_CODE.name
+ assert errors[0]["field"] == "voucherCode"
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
index 02776312e3..f1cf0daf23 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -1,9 +1,11 @@
+from datetime import timedelta
from decimal import Decimal
from unittest.mock import ANY, patch
import graphene
import pytest
from django.test import override_settings
+from django.utils import timezone
from prices import TaxedMoney
from .....core.models import EventDelivery
@@ -223,7 +225,7 @@ def test_draft_order_update_voucher_not_available(
content = get_graphql_content(response)
error = content["data"]["draftOrderUpdate"]["errors"][0]
- assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
+ assert error["code"] == OrderErrorCode.INVALID_VOUCHER.name
assert error["field"] == "voucher"
@@ -3822,3 +3824,173 @@ def test_draft_order_update_metadata_key_deleted_in_meantime(
draft_order.refresh_from_db()
assert draft_order.metadata == {key_1: new_value}
assert draft_order.private_metadata == {key_2: new_value}
+
+
[email protected]("include_draft_order_in_voucher_usage", [True, False])
+def test_draft_order_update_with_expired_voucher(
+ include_draft_order_in_voucher_usage,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = include_draft_order_in_voucher_usage
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ # Set voucher end date to the past
+ voucher.end_date = timezone.now() - timedelta(days=1)
+ voucher.save(update_fields=["end_date"])
+
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucher": voucher_id,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["draftOrderUpdate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER.name
+ assert errors[0]["field"] == "voucher"
+
+
[email protected]("include_draft_order_in_voucher_usage", [True, False])
+def test_draft_order_update_with_expired_voucher_code(
+ include_draft_order_in_voucher_usage,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = include_draft_order_in_voucher_usage
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ # Set voucher end date to the past
+ voucher.end_date = timezone.now() - timedelta(days=1)
+ voucher.save(update_fields=["end_date"])
+
+ code = voucher.codes.first()
+
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucherCode": code.code,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["draftOrderUpdate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER_CODE.name
+ assert errors[0]["field"] == "voucherCode"
+
+
[email protected]("include_draft_order_in_voucher_usage", [True, False])
+def test_draft_order_update_with_inactive_voucher(
+ include_draft_order_in_voucher_usage,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = include_draft_order_in_voucher_usage
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ # Set voucher code to inactive
+ code = voucher.codes.first()
+ code.is_active = False
+ code.save(update_fields=["is_active"])
+
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucher": voucher_id,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["draftOrderUpdate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER.name
+ assert errors[0]["field"] == "voucher"
+
+
[email protected]("include_draft_order_in_voucher_usage", [True, False])
+def test_draft_order_update_with_inactive_voucher_code(
+ include_draft_order_in_voucher_usage,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = include_draft_order_in_voucher_usage
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ # Set voucher code to inactive
+ code = voucher.codes.first()
+ code.is_active = False
+ code.save(update_fields=["is_active"])
+
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucherCode": code.code,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["draftOrderUpdate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER_CODE.name
+ assert errors[0]["field"] == "voucherCode"