Skip to content

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

Fix voucher usage update for draft orders deletion (#18438)

Iga Karbowiak3c50ec999a47
diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.py
index b9779b41e9..61f4800a85 100644
--- a/saleor/discount/tasks.py
+++ b/saleor/discount/tasks.py
@@ -1,5 +1,5 @@
import datetime
-from collections import defaultdict
+from collections import Counter, defaultdict
from typing import TYPE_CHECKING
import graphene
@@ -29,7 +29,9 @@ from .models import (
OrderLineDiscount,
Promotion,
PromotionRule,
+ Voucher,
VoucherCode,
+ VoucherCustomer,
)
from .utils.promotion import mark_catalogue_promotion_rules_as_dirty
@@ -214,6 +216,39 @@ def clear_promotion_rule_variants_task():
clear_promotion_rule_variants_task.delay()
+@allow_writer()
+def release_voucher_code_usage_of_draft_orders(
+ voucher_codes_with_emails: list[tuple[str, str]],
+):
+ voucher_codes = [code for code, _ in voucher_codes_with_emails]
+ if not voucher_codes:
+ return
+ codes = VoucherCode.objects.filter(code__in=voucher_codes)
+
+ # activate single use vouchers
+ single_use_vouchers = Voucher.objects.filter(single_use=True)
+ codes.filter(voucher__in=single_use_vouchers).update(is_active=True)
+
+ # decrease usage for vouchers with usage limit
+ voucher_with_usage_limit = Voucher.objects.filter(usage_limit__isnull=False)
+ codes_to_release = codes.filter(voucher__in=voucher_with_usage_limit)
+ code_counter = Counter(voucher_codes)
+ for voucher_code in codes_to_release:
+ usage_decrease = code_counter[voucher_code.code]
+ if voucher_code.used < usage_decrease:
+ voucher_code.used = 0
+ else:
+ voucher_code.used = F("used") - usage_decrease
+ VoucherCode.objects.bulk_update(codes_to_release, ["used"])
+
+ # drop customer usage
+ lookup = Q()
+ for code, email in voucher_codes_with_emails:
+ lookup |= Q(voucher_code__code=code, customer_email=email)
+ VoucherCustomer.objects.filter(lookup).delete()
+
+
def decrease_voucher_code_usage_of_draft_orders(channel_id: int):
codes = (
Order.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.py
index 07adeac641..ec2b90d7d9 100644
--- a/saleor/discount/tests/test_discounts.py
+++ b/saleor/discount/tests/test_discounts.py
@@ -233,6 +233,29 @@ def test_decrease_voucher_usage(channel_USD):
assert code_instance.used == 9
+def test_decrease_voucher_usage_used_0(channel_USD):
+ # given
+ code = "unique"
+ voucher = Voucher.objects.create(
+ type=VoucherType.ENTIRE_ORDER,
+ discount_value_type=DiscountValueType.FIXED,
+ usage_limit=100,
+ )
+ code_instance = VoucherCode.objects.create(code=code, voucher=voucher, used=0)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(10, channel_USD.currency_code),
+ )
+
+ # when
+ decrease_voucher_code_usage_value(code_instance)
+
+ # then
+ code_instance.refresh_from_db(fields=["used"])
+ assert code_instance.used == 0
+
+
def test_deactivate_voucher_code(voucher):
# given
code_instance = voucher.codes.first()
diff --git a/saleor/discount/tests/test_tasks.py b/saleor/discount/tests/test_tasks.py
index ec1b9d4ee4..9ea0e92c96 100644
--- a/saleor/discount/tests/test_tasks.py
+++ b/saleor/discount/tests/test_tasks.py
@@ -11,7 +11,14 @@ from freezegun import freeze_time
from ...order.models import Order
from ...product.models import ProductChannelListing, ProductVariant
from .. import DiscountType, RewardValueType
-from ..models import OrderDiscount, OrderLineDiscount, Promotion, PromotionRule
+from ..models import (
+ OrderDiscount,
+ OrderLineDiscount,
+ Promotion,
+ PromotionRule,
+ VoucherCode,
+ VoucherCustomer,
+)
from ..tasks import (
clear_promotion_rule_variants_task,
decrease_voucher_code_usage_of_draft_orders,
@@ -19,6 +26,7 @@ from ..tasks import (
disconnect_voucher_codes_from_draft_orders_task,
fetch_promotion_variants_and_product_ids,
handle_promotion_toggle,
+ release_voucher_code_usage_of_draft_orders,
set_promotion_rule_variants_task,
)
from ..utils.promotion import mark_catalogue_promotion_rules_as_dirty
@@ -368,3 +376,101 @@ def test_disconnect_voucher_codes_from_draft_orders(
line_discount.refresh_from_db()
with pytest.raises(order_discount._meta.model.DoesNotExist):
order_discount.refresh_from_db()
+
+
+def test_release_voucher_code_usage_of_draft_orders_single_use(voucher_single_use):
+ # given
+ single_use_code_1 = voucher_single_use.codes.first()
+ single_use_code_2 = voucher_single_use.codes.last()
+ single_use_code_1.is_active = False
+ single_use_code_2.is_active = False
+ VoucherCode.objects.bulk_update(
+ [single_use_code_1, single_use_code_2], ["is_active"]
+ )
+
+ voucher_codes_with_emails = [
+ (single_use_code_1.code, "[email protected]"),
+ (single_use_code_2.code, "[email protected]"),
+ ]
+
+ # when
+ release_voucher_code_usage_of_draft_orders(voucher_codes_with_emails)
+
+ # then
+ single_use_code_2.refresh_from_db()
+ assert single_use_code_2.is_active is True
+ single_use_code_1.refresh_from_db()
+ assert single_use_code_1.is_active is True
+
+
[email protected]("used", [1, 2, 3, 4])
+def test_release_voucher_code_usage_of_draft_orders_multiple_use(
+ used, voucher_multiple_use
+):
+ # given
+ multiple_use_code = voucher_multiple_use.codes.first()
+ multiple_use_code.used = used
+ multiple_use_code.save(update_fields=["used"])
+
+ voucher_codes_with_emails = [
+ (multiple_use_code.code, "[email protected]"),
+ (multiple_use_code.code, "[email protected]"),
+ (multiple_use_code.code, "[email protected]"),
+ ]
+
+ # when
+ release_voucher_code_usage_of_draft_orders(voucher_codes_with_emails)
+
+ # then
+ multiple_use_code.refresh_from_db()
+ assert multiple_use_code.used == max(used - len(voucher_codes_with_emails), 0)
+
+
+def test_release_voucher_code_usage_of_draft_orders_clears_voucher_customers(
+ voucher_single_use,
+):
+ # given
+ single_use_code_1 = voucher_single_use.codes.first()
+ single_use_code_2 = voucher_single_use.codes.last()
+ email_1 = "[email protected]"
+ email_2 = "[email protected]"
+ email_3 = "[email protected]"
+ VoucherCustomer.objects.bulk_create(
+ [
+ VoucherCustomer(voucher_code=single_use_code_1, customer_email=email_1),
+ VoucherCustomer(voucher_code=single_use_code_1, customer_email=email_2),
+ VoucherCustomer(voucher_code=single_use_code_2, customer_email=email_3),
+ ]
+ )
+ voucher_codes_with_emails = [
+ (single_use_code_1.code, email_1),
+ (single_use_code_2.code, email_3),
+ (single_use_code_2.code, email_2),
+ ]
+
+ # when
+ release_voucher_code_usage_of_draft_orders(voucher_codes_with_emails)
+
+ # then
+ assert not VoucherCustomer.objects.filter(
+ voucher_code=single_use_code_1, customer_email=email_1
+ ).exists()
+ assert not VoucherCustomer.objects.filter(
+ voucher_code=single_use_code_2, customer_email=email_3
+ ).exists()
+ assert VoucherCustomer.objects.filter(
+ voucher_code=single_use_code_1, customer_email=email_2
+ ).exists()
+
+
+def test_release_voucher_code_usage_of_draft_orders_no_codes():
+ # given
+ voucher_codes_with_emails = []
+
+ # when
+ # Should not raise or do anything
+ release_voucher_code_usage_of_draft_orders(voucher_codes_with_emails)
+
+ # then
+ assert VoucherCode.objects.count() == 0
+ assert VoucherCustomer.objects.count() == 0
diff --git a/saleor/discount/utils/voucher.py b/saleor/discount/utils/voucher.py
index fe4d2b9f04..9f4d906249 100644
--- a/saleor/discount/utils/voucher.py
+++ b/saleor/discount/utils/voucher.py
@@ -4,7 +4,7 @@ from decimal import Decimal
from typing import TYPE_CHECKING, Optional, Union, cast
from uuid import UUID
-from django.db.models import Exists, F, OuterRef
+from django.db.models import Case, Exists, F, IntegerField, OuterRef, Value, When
from django.utils import timezone
from prices import Money
@@ -88,8 +88,13 @@ def increase_voucher_code_usage_value(code: "VoucherCode") -> None:
def decrease_voucher_code_usage_value(code: "VoucherCode") -> None:
"""Decrease voucher code uses by 1."""
- code.used = F("used") - 1
- code.save(update_fields=["used"])
+ VoucherCode.objects.filter(pk=code.pk).update(
+ used=Case(
+ When(used__gt=0, then=F("used") - 1),
+ default=Value(0),
+ output_field=IntegerField(),
+ )
+ )
def deactivate_voucher_code(code: "VoucherCode") -> None:
diff --git a/saleor/graphql/order/bulk_mutations/draft_orders.py b/saleor/graphql/order/bulk_mutations/draft_orders.py
index 8b329de582..0a4f24ad73 100644
--- a/saleor/graphql/order/bulk_mutations/draft_orders.py
+++ b/saleor/graphql/order/bulk_mutations/draft_orders.py
@@ -5,6 +5,8 @@ import graphene
from django.core.exceptions import ValidationError
from ....channel import models as channel_models
+from ....discount.tasks import release_voucher_code_usage_of_draft_orders
+from ....discount.utils.voucher import get_customer_email_for_voucher_usage
from ....order import OrderStatus, models
from ....order.error_codes import OrderErrorCode
from ....payment.models import Payment, TransactionItem
@@ -81,6 +83,7 @@ class DraftOrderBulkDelete(
instances_ids = [instance.id for instance in instances]
related_objects = cls.get_ids_with_related_objects(instances_ids)
+ voucher_codes_with_emails = []
for instance, node_id in zip(instances, ids, strict=False):
instance_errors = []
@@ -100,13 +103,49 @@ class DraftOrderBulkDelete(
ValidationError({node_id: instance_errors_msg}).update_error_dict(
errors_dict
)
- return clean_instance_ids, errors_dict
+
+ if instance.channel.include_draft_order_in_voucher_usage and (
+ code := instance.voucher_code
+ ):
+ voucher_codes_with_emails.append(
+ (code, get_customer_email_for_voucher_usage(instance))
+ )
+ return clean_instance_ids, errors_dict, voucher_codes_with_emails
@classmethod
def get_channel_ids(cls, instances) -> Iterable[UUID | int]:
"""Get the instances channel ids for channel permission accessible check."""
return [order.channel_id for order in instances]
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, *, ids, **data
+ ) -> tuple[int, ValidationError | None]:
+ """Perform a mutation that deletes a list of model instances."""
+ if not ids:
+ return 0, None
+ try:
+ instances = cls.get_nodes_or_error(ids, "id", Order, schema=info.schema)
+ except ValidationError as error:
+ return 0, error
+
+ channel_ids = cls.get_channel_ids(instances)
+ cls.check_channel_permissions(info, channel_ids)
+
+ clean_instance_ids, errors_dict, voucher_codes_with_emails = cls.clean_input(
+ info, instances, ids
+ )
+ if errors_dict:
+ errors = ValidationError(errors_dict)
+ else:
+ errors = None
+ count = len(clean_instance_ids)
+ if count:
+ qs = models.Order.objects.filter(pk__in=clean_instance_ids)
+ cls.bulk_action(info, qs, **data)
+ release_voucher_code_usage_of_draft_orders.delay(voucher_codes_with_emails)
+ return count, errors
+
class DraftOrderLinesBulkDelete(
ModelBulkDeleteMutation, BaseBulkWithRestrictedChannelAccessMutation
diff --git a/saleor/graphql/order/mutations/draft_order_delete.py b/saleor/graphql/order/mutations/draft_order_delete.py
index 03bd29b5ea..b3067c427d 100644
--- a/saleor/graphql/order/mutations/draft_order_delete.py
+++ b/saleor/graphql/order/mutations/draft_order_delete.py
@@ -3,7 +3,10 @@ from django.core.exceptions import ValidationError
from ....core.tracing import traced_atomic_transaction
from ....discount.models import VoucherCode
-from ....discount.utils.voucher import release_voucher_code_usage
+from ....discount.utils.voucher import (
+ get_customer_email_for_voucher_usage,
+ release_voucher_code_usage,
+)
from ....order import OrderStatus, models
from ....order.actions import call_order_event
from ....order.error_codes import OrderErrorCode
@@ -83,9 +86,13 @@ class DraftOrderDelete(
@classmethod
def post_save_action(cls, info, instance, _):
if code := instance.voucher_code:
- if voucher_code := VoucherCode.objects.filter(code=code).first():
+ channel = instance.channel
+ if channel.include_draft_order_in_voucher_usage and (
+ voucher_code := VoucherCode.objects.filter(code=code).first()
+ ):
+ user_email = get_customer_email_for_voucher_usage(instance)
voucher = voucher_code.voucher
- release_voucher_code_usage(voucher_code, voucher, None)
+ release_voucher_code_usage(voucher_code, voucher, user_email)
@classmethod
def success_response(cls, order):
diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.py
index 1b0feb5d17..284da0db15 100644
--- a/saleor/graphql/order/mutations/draft_order_update.py
+++ b/saleor/graphql/order/mutations/draft_order_update.py
@@ -314,13 +314,13 @@ class DraftOrderUpdate(
# create or update voucher discount object
create_or_update_voucher_discount_objects_for_order(instance)
- # handle voucher usage
- user_email = get_customer_email_for_voucher_usage(instance)
-
channel = instance.channel
if not channel.include_draft_order_in_voucher_usage:
return
+ # handle voucher usage
+ user_email = get_customer_email_for_voucher_usage(instance)
+
if voucher:
code_instance = cleaned_input.pop("voucher_code_instance", None)
increase_voucher_usage(
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_bulk_delete.py b/saleor/graphql/order/tests/mutations/test_draft_order_bulk_delete.py
index 08a968fd28..5a61cd6e81 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_bulk_delete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_bulk_delete.py
@@ -1,5 +1,6 @@
import graphene
+from .....discount.models import VoucherCode
from .....order import OrderStatus
from .....order import models as order_models
from .....order.error_codes import OrderErrorCode
@@ -64,7 +65,10 @@ def test_delete_draft_orders_by_user_no_channel_access(
query = DRAFT_ORDER_BULK_DELETE
variables = {
- "ids": [graphene.Node.to_global_id("Order", order.id) for order in order_list]
+ "ids": [
+ graphene.Node.to_global_id("Order", order.id)
+ for order in [order_1, order_2]
+ ]
}
# when
@@ -146,6 +150,96 @@ def test_delete_draft_orders_orders_with_transaction_item(
).count() == len(order_list)
+def test_draft_order_bulk_delete_with_voucher_and_include_draft_order_in_voucher_usage_false(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+ voucher,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ voucher_code = voucher.codes.first()
+
+ for order in order_list:
+ order.voucher_code = voucher_code.code
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status", "voucher_code"])
+
+ order_ids = [order.id for order in order_list]
+
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = False
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+ assert voucher_code.used == 0
+
+ query = DRAFT_ORDER_BULK_DELETE
+ variables = {
+ "ids": [graphene.Node.to_global_id("Order", order.id) for order in order_list]
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["draftOrderBulkDelete"]["count"] == len(order_list)
+ assert not order_models.Order.objects.filter(id__in=order_ids).exists()
+
+ voucher_code.refresh_from_db()
+ assert voucher_code.used == 0
+
+
+def test_draft_order_bulk_delete_with_voucher_and_include_draft_order_in_voucher_usage_true(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_list,
+ voucher_with_many_codes,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ voucher_codes = []
+ voucher = voucher_with_many_codes
+
+ for order, voucher_code in zip(order_list, voucher.codes.all(), strict=False):
+ order.voucher_code = voucher_code.code
+ order.status = OrderStatus.DRAFT
+
+ voucher_codes.append(voucher_code)
+ voucher_code.used = 1
+
+ order_models.Order.objects.bulk_update(order_list, ["voucher_code", "status"])
+ VoucherCode.objects.bulk_update(voucher_codes, ["used"])
+
+ order_ids = [order.id for order in order_list]
+
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = True
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+
+ query = DRAFT_ORDER_BULK_DELETE
+ variables = {
+ "ids": [graphene.Node.to_global_id("Order", order.id) for order in order_list]
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["draftOrderBulkDelete"]["count"] == len(order_list)
+ assert not order_models.Order.objects.filter(id__in=order_ids).exists()
+
+ for code in voucher_codes:
+ code.refresh_from_db()
+ assert code.used == 0
+
+
MUTATION_DELETE_ORDER_LINES = """
mutation draftOrderLinesBulkDelete($ids: [ID!]!) {
draftOrderLinesBulkDelete(ids: $ids) {
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py b/saleor/graphql/order/tests/mutations/test_draft_order_delete.py
index 0b2a91d2c0..d1ff1ca1e1 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_delete.py
@@ -255,6 +255,11 @@ def test_draft_order_delete_release_voucher_codes_multiple_use(
query = DRAFT_ORDER_DELETE_MUTATION
permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order_list_with_multiple_use_voucher[0]
+
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = True
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
voucher_code = VoucherCode.objects.get(code=order.voucher_code)
assert voucher_code.used == 1
@@ -278,6 +283,11 @@ def test_draft_order_delete_release_voucher_codes_single_use(
query = DRAFT_ORDER_DELETE_MUTATION
permission_group_manage_orders.user_set.add(staff_api_client.user)
order = draft_order_list_with_single_use_voucher[0]
+
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = True
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
voucher_code = VoucherCode.objects.get(code=order.voucher_code)
assert voucher_code.is_active is False
@@ -347,3 +357,79 @@ def test_draft_order_delete_do_not_trigger_sync_webhooks(
)
assert not mocked_send_webhook_request_sync.called
assert wrapped_call_order_event.called
+
+
+def test_draft_order_delete_with_voucher_and_include_draft_order_in_voucher_usage_false(
+ 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
+ voucher_code = voucher.codes.first()
+ order.voucher_code = voucher_code.code
+ order.save(update_fields=["voucher_code"])
+
+ # Ensure the channel flag is False
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = False
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+ assert voucher_code.used == 0
+
+ query = DRAFT_ORDER_DELETE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ staff_api_client.post_graphql(query, variables)
+
+ # then
+ with pytest.raises(order._meta.model.DoesNotExist):
+ order.refresh_from_db()
+
+ voucher_code.refresh_from_db()
+ assert voucher_code.used == 0
+
+
+def test_draft_order_delete_with_voucher_and_include_draft_order_in_voucher_usage_true(
+ 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
+ voucher_code = voucher.codes.first()
+ order.voucher_code = voucher_code.code
+ order.save(update_fields=["voucher_code", "channel"])
+
+ # Ensure the channel flag is False
+ channel = order.channel
+ channel.include_draft_order_in_voucher_usage = True
+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])
+
+ voucher.usage_limit = 1
+ voucher.save(update_fields=["usage_limit"])
+
+ voucher_code.used = 1
+ voucher_code.save(update_fields=["used"])
+
+ query = DRAFT_ORDER_DELETE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ staff_api_client.post_graphql(query, variables)
+
+ # then
+ with pytest.raises(order._meta.model.DoesNotExist):
+ order.refresh_from_db()
+ voucher_code.refresh_from_db()
+ # Voucher usage should be decremented
+ assert voucher_code.used == 0