Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Count total voucher usage instead of particular code usage (#16458)
Piotr Zabieglik6cf5cf04fa6f
diff --git a/saleor/discount/models.py b/saleor/discount/models.pyindex ee1ce54583..db25c5dabe 100644--- a/saleor/discount/models.py+++ b/saleor/discount/models.py@@ -56,8 +56,10 @@ class VoucherQueryset(models.QuerySet["Voucher"]):def active(self, date):subquery = (VoucherCode.objects.filter(voucher_id=OuterRef("pk"))+ .order_by()+ .values("voucher_id").annotate(total_used=Sum("used"))- .values("total_used")[:1]+ .values("total_used"))return self.filter(Q(usage_limit__isnull=True) | Q(usage_limit__gt=Subquery(subquery)),@@ -80,8 +82,10 @@ class VoucherQueryset(models.QuerySet["Voucher"]):def expired(self, date):subquery = (VoucherCode.objects.filter(voucher_id=OuterRef("pk"))+ .order_by()+ .values("voucher_id").annotate(total_used=Sum("used"))- .values("total_used")[:1]+ .values("total_used"))return self.filter(Q(usage_limit__lte=Subquery(subquery)) | Q(end_date__lt=date),diff --git a/saleor/graphql/discount/tests/queries/test_vouchers_filtering.py b/saleor/graphql/discount/tests/queries/test_vouchers_filtering.pyindex cd30595c5f..3b182b39d0 100644--- a/saleor/graphql/discount/tests/queries/test_vouchers_filtering.py+++ b/saleor/graphql/discount/tests/queries/test_vouchers_filtering.py@@ -2,6 +2,7 @@ from datetime import timedeltaimport pytestfrom django.utils import timezone+from freezegun import freeze_timefrom .....discount import DiscountValueTypefrom .....discount.models import Voucher, VoucherCode@@ -233,3 +234,96 @@ def test_query_vouchers_with_filter_search(content = get_graphql_content(response)data = content["data"]["vouchers"]["edges"]assert len(data) == count+++@freeze_time("2020-03-18 12:00:00")+ ("start_date", "end_date", "used", "count"),+ [+ (+ timezone.now().replace(year=2018, month=1, day=1),+ timezone.now().replace(year=2019, month=1, day=1),+ 0,+ 2,+ ),+ (+ timezone.now().replace(year=2023, month=1, day=1),+ timezone.now().replace(year=2024, month=1, day=1),+ 0,+ 0,+ ),+ (+ timezone.now().replace(year=2023, month=1, day=1),+ None,+ 0,+ 0,+ ),+ (+ timezone.now().replace(year=2019, month=1, day=1),+ timezone.now().replace(year=2021, month=1, day=1),+ 0,+ 0,+ ),+ (+ timezone.now().replace(year=2019, month=1, day=1),+ timezone.now().replace(year=2021, month=1, day=1),+ 2,+ 1,+ ),+ (+ timezone.now().replace(year=2019, month=1, day=1),+ timezone.now().replace(year=2021, month=1, day=1),+ 110,+ 2,+ ),+ ],+)+def test_query_vouchers_with_filter_status_expired(+ start_date,+ end_date,+ used,+ count,+ staff_api_client,+ permission_manage_discounts,+):+ # given+ vouchers = Voucher.objects.bulk_create(+ [+ Voucher(+ name="Voucher1",+ start_date=timezone.now(),+ ),+ Voucher(+ name="Voucher2",+ start_date=start_date,+ end_date=end_date,+ usage_limit=5,+ ),+ Voucher(+ name="Voucher3",+ start_date=start_date,+ end_date=end_date,+ usage_limit=100,+ ),+ ]+ )+ VoucherCode.objects.bulk_create(+ [+ VoucherCode(code="code-A", voucher=vouchers[0]),+ VoucherCode(code="code-B", voucher=vouchers[0]),+ VoucherCode(code="code-1", voucher=vouchers[1], used=3),+ VoucherCode(code="code-2", voucher=vouchers[1], used=used),+ VoucherCode(code="code-abc", voucher=vouchers[2], used=used),+ ]+ )+ variables = {"filter": {"status": "EXPIRED"}}++ # whne+ response = staff_api_client.post_graphql(+ QUERY_VOUCHERS_WITH_FILTER, variables, permissions=[permission_manage_discounts]+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["vouchers"]["edges"]+ assert len(data) == countdiff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.pyindex 1cbdd08ab2..6b2ce6a92b 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py@@ -11,7 +11,7 @@ from .....checkout import AddressTypefrom .....core.prices import quantize_pricefrom .....core.taxes import TaxError, zero_taxed_moneyfrom .....discount import DiscountType, DiscountValueType, RewardType, RewardValueType-from .....discount.models import VoucherChannelListing, VoucherCustomer+from .....discount.models import VoucherChannelListing, VoucherCode, VoucherCustomerfrom .....order import OrderStatusfrom .....order import events as order_eventsfrom .....order.error_codes import OrderErrorCode@@ -3458,3 +3458,148 @@ def test_draft_order_create_create_no_shipping_method(order = Order.objects.get(id=order_pk)assert order.undiscounted_base_shipping_price_amount == 0assert order.base_shipping_price_amount == 0+++def test_draft_order_create_voucher_exceed_usage_limit(+ staff_api_client,+ permission_group_manage_orders,+ customer_user,+ shipping_method,+ variant,+ voucher_with_many_codes,+ voucher_percentage,+ 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 = True+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher_1 = voucher_with_many_codes+ voucher_1.usage_limit = 6+ voucher_1.save(update_fields=["usage_limit"])++ code_1, code_2, code_3, code_4, code_5 = voucher_1.codes.all()+ code_1.used = 1+ code_2.used = 2+ code_3.used = 3+ code_4.used = 0+ code_5.used = 0+ VoucherCode.objects.bulk_update([code_1, code_2, code_3, code_4, code_5], ["used"])++ voucher_2 = voucher_percentage+ voucher_2.usage_limit = 3+ voucher_2.save(update_fields=["usage_limit"])+ code_6 = voucher_2.codes.get()+ code_6.used = 1+ code_6.save(update_fields=["used"])+ voucher_2.codes.create(code="new code voucher 2", used=1)++ 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)+ redirect_url = "https://www.example.com"+ variables = {+ "input": {+ "user": user_id,+ "lines": variant_list,+ "billingAddress": shipping_address,+ "shippingAddress": shipping_address,+ "shippingMethod": shipping_id,+ "voucherCode": code_2.code,+ "channelId": channel_id,+ "redirectUrl": redirect_url,+ }+ }+ # 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]("used", [0, 1, 2])+def test_draft_order_create_voucher_with_usage_limit(+ used,+ staff_api_client,+ permission_group_manage_orders,+ customer_user,+ shipping_method,+ variant,+ voucher_with_many_codes,+ voucher_percentage,+ 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 = True+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher_1 = voucher_with_many_codes+ voucher_1.usage_limit = 10+ voucher_1.save(update_fields=["usage_limit"])++ code_1, code_2, code_3, code_4, code_5 = voucher_1.codes.all()+ code_1.used = used+ code_2.used = 1+ code_3.used = 2+ code_4.used = 3+ code_5.used = 0+ VoucherCode.objects.bulk_update([code_1, code_2, code_3, code_4, code_5], ["used"])++ voucher_2 = voucher_percentage+ voucher_2.usage_limit = 3+ voucher_2.save(update_fields=["usage_limit"])+ code_6 = voucher_2.codes.get()+ code_6.used = 1+ code_6.save(update_fields=["used"])+ voucher_2.codes.create(code="new code voucher 2", used=1)++ 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)+ redirect_url = "https://www.example.com"+ variables = {+ "input": {+ "user": user_id,+ "lines": variant_list,+ "billingAddress": shipping_address,+ "shippingAddress": shipping_address,+ "shippingMethod": shipping_id,+ "voucherCode": code_1.code,+ "channelId": channel_id,+ "redirectUrl": redirect_url,+ }+ }+ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["draftOrderCreate"]["errors"]+ data = content["data"]["draftOrderCreate"]["order"]+ assert data["voucherCode"] == code_1.code