Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Include draft orders in voucher usage (#14288)
Iga Karbowiaka1f6cf30564b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a571bc36e..7a188bd406 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,14 @@All notable, unreleased changes to this project will be documented in this file. For the released changes, please visit the [Releases](https://github.com/saleor/saleor/releases) page.# 3.18.0 [Unreleased]++### Highlights+- Allow including draft orders in voucher usage. New `includeDraftOrderInVoucherUsage` flag allows defining if vouchers used in draft orders should be counted into voucher usage. - #14288 by @zedzior, @IKarbowiak, @michal-macioszczyk++ - Add `includeDraftOrderInVoucherUsage` to `OrderSettings`+ - Add `includeDraftOrderInVoucherUsage` to `OrderSettingsInput`++### Breaking changes- Optimize number of queries in bulk mutations when calling webhooks. This change affects only users of open-source Saleor, who have their own custom plugin implementations. To adjust to this change, the `webhooks` parameter should be added to any of the affected method. Affected methods:- `attribute_updated`diff --git a/saleor/channel/migrations/0017_channel_include_draft_order_in_voucher_usage.py b/saleor/channel/migrations/0017_channel_include_draft_order_in_voucher_usage.pynew file mode 100644index 0000000000..ea55686cad--- /dev/null+++ b/saleor/channel/migrations/0017_channel_include_draft_order_in_voucher_usage.py@@ -0,0 +1,25 @@+# Generated by Django 3.2.22 on 2023-10-13 09:46++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("channel", "0016_auto_20230816_1209"),+ ]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="include_draft_order_in_voucher_usage",+ field=models.BooleanField(default=False),+ ),+ migrations.RunSQL(+ """+ ALTER TABLE channel_channel+ ALTER COLUMN include_draft_order_in_voucher_usage+ SET DEFAULT false;+ """,+ migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/channel/models.py b/saleor/channel/models.pyindex a9feab0638..2353e23543 100644--- a/saleor/channel/models.py+++ b/saleor/channel/models.py@@ -44,6 +44,8 @@ class Channel(ModelWithMetadata):default=timedelta(days=60),)+ include_draft_order_in_voucher_usage = models.BooleanField(default=False)+use_legacy_error_flow_for_checkout = models.BooleanField(default=True)class Meta(ModelWithMetadata.Meta):diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 61981667e5..37890c949e 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -33,10 +33,8 @@ from ..core.utils.url import validate_storefront_urlfrom ..discount import DiscountType, DiscountValueTypefrom ..discount.models import NotApplicable, OrderLineDiscountfrom ..discount.utils import (- add_voucher_usage_by_customer,- deactivate_voucher_code,get_sale_id,- increase_voucher_code_usage,+ increase_voucher_usage,prepare_promotion_discount_reason,release_voucher_code_usage,)@@ -118,13 +116,9 @@ def _process_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:if not voucher_code or not voucher:return {}- if voucher.usage_limit:- increase_voucher_code_usage(voucher_code)- if voucher.apply_once_per_customer:- customer_email = cast(str, checkout_info.get_customer_email())- add_voucher_usage_by_customer(voucher_code, customer_email)- if voucher.single_use:- deactivate_voucher_code(voucher_code)+ customer_email = cast(str, checkout_info.get_customer_email())+ increase_voucher_usage(voucher, voucher_code, customer_email)+return {"voucher": voucher,"voucher_code": voucher_code.code,@@ -977,21 +971,14 @@ def _is_refund_ongoing(payment):)-def _increase_voucher_code_usage(checkout_info: "CheckoutInfo"):+def _increase_voucher_code_usage_value(checkout_info: "CheckoutInfo"):"""Increase a voucher usage applied to the checkout."""voucher, code = get_voucher_for_checkout_info(checkout_info, with_lock=True)if not voucher or not code:return None- if voucher.apply_once_per_customer:- customer_email = cast(str, checkout_info.get_customer_email())- add_voucher_usage_by_customer(code, customer_email)-- if voucher.usage_limit:- increase_voucher_code_usage(code)-- if voucher.single_use:- deactivate_voucher_code(code)+ customer_email = cast(str, checkout_info.get_customer_email())+ increase_voucher_usage(voucher, code, customer_email)return code@@ -1303,7 +1290,7 @@ def create_order_from_checkout(if voucher := checkout_info.voucher:with transaction.atomic():- code = _increase_voucher_code_usage(checkout_info=checkout_info)+ code = _increase_voucher_code_usage_value(checkout_info=checkout_info)with transaction.atomic():checkout_pk = checkout_info.checkout.pkdiff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.pyindex e890e27721..fc02d54dff 100644--- a/saleor/checkout/tests/test_order_from_checkout.py+++ b/saleor/checkout/tests/test_order_from_checkout.py@@ -744,7 +744,7 @@ def test_note_in_created_order_checkout_line_deleted_in_the_meantime(# whenwith before_after.after(- "saleor.checkout.complete_checkout._increase_voucher_code_usage",+ "saleor.checkout.complete_checkout._increase_voucher_code_usage_value",delete_checkout_line,):order = create_order_from_checkout(@@ -779,7 +779,7 @@ def test_note_in_created_order_checkout_deleted_in_the_meantime(# whenwith before_after.after(- "saleor.checkout.complete_checkout._increase_voucher_code_usage",+ "saleor.checkout.complete_checkout._increase_voucher_code_usage_value",delete_checkout,):order = create_order_from_checkout(diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 3a2ad72eaf..8af0a461d2 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, Optional, Union, castimport graphenefrom django.core.exceptions import ValidationError-from django.db.models import Exists, OuterRef, prefetch_related_objects+from django.db.models import prefetch_related_objectsfrom django.utils import timezonefrom prices import Money@@ -24,6 +24,7 @@ from ..discount.models import NotApplicable, Voucher, VoucherCodefrom ..discount.utils import (create_or_update_discount_objects_from_promotion_for_checkout,get_products_voucher_discount,+ get_voucher_code_instance,validate_voucher_for_checkout,)from ..giftcard.utils import (@@ -684,25 +685,7 @@ def add_voucher_code_to_checkout(Raise InvalidPromoCode() if voucher of given type cannot be applied."""-- if (- Voucher.objects.active_in_channel(- date=timezone.now(), channel_slug=checkout_info.channel.slug- )- .filter(- Exists(- VoucherCode.objects.filter(- code=voucher_code,- voucher_id=OuterRef("id"),- is_active=True,- )- )- )- .exists()- ):- code_instance = VoucherCode.objects.get(code=voucher_code)- else:- raise InvalidPromoCode()+ code_instance = get_voucher_code_instance(voucher_code, checkout_info.channel.slug)try:add_voucher_to_checkout(manager, checkout_info, lines, code_instance.voucher, code_instancediff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.pyindex c46a9abe37..352b3d21df 100644--- a/saleor/discount/tasks.py+++ b/saleor/discount/tasks.py@@ -9,10 +9,19 @@ from django.db.models import Exists, F, OuterRef, Q, QuerySetfrom ..celeryconf import appfrom ..graphql.discount.utils import get_variants_for_predicate+from ..order import OrderStatus+from ..order.models import Order, OrderLinefrom ..plugins.manager import get_plugins_managerfrom ..product.models import Product, ProductVariantfrom ..product.tasks import update_products_discounted_prices_for_promotion_task-from .models import Promotion, PromotionRule+from . import DiscountType+from .models import (+ OrderDiscount,+ OrderLineDiscount,+ Promotion,+ PromotionRule,+ VoucherCode,+)if TYPE_CHECKING:from uuid import UUID@@ -146,3 +155,62 @@ def fetch_promotion_variants_and_product_ids(promotions: "QuerySet[Promotion]"):Exists(variants.filter(product_id=OuterRef("id"))))return promotion_id_to_variants, list(products.values_list("id", flat=True))+++def decrease_voucher_code_usage_of_draft_orders(channel_id: int):+ codes = Order.objects.filter(+ channel_id=channel_id, status=OrderStatus.DRAFT, voucher_code__isnull=False+ ).values_list("voucher_code", flat=True)+ voucher_code_ids = VoucherCode.objects.filter(code__in=codes).values_list(+ "pk", flat=True+ )+ decrease_voucher_codes_usage_task.delay(list(voucher_code_ids))+++def decrease_voucher_codes_usage_task(voucher_code_ids):+ # Batch of size 1000 takes ~1sec and consumes ~20mb at peak+ BATCH_SIZE = 1000+ ids = voucher_code_ids[:BATCH_SIZE]+ if (+ voucher_codes := VoucherCode.objects.filter(pk__in=ids)+ .select_related("voucher")+ .only("voucher", "used", "is_active")+ ):+ for voucher_code in voucher_codes:+ if voucher_code.voucher.usage_limit and voucher_code.used > 0:+ voucher_code.used = F("used") - 1+ if voucher_code.voucher.single_use:+ voucher_code.is_active = True+ VoucherCode.objects.bulk_update(voucher_codes, ["used", "is_active"])+ if remaining_ids := list(set(voucher_code_ids) - set(ids)):+ decrease_voucher_codes_usage_task.delay(remaining_ids)+++def disconnect_voucher_codes_from_draft_orders(channel_id: int):+ order_ids = Order.objects.filter(+ channel_id=channel_id, status=OrderStatus.DRAFT, voucher_code__isnull=False+ ).values_list("pk", flat=True)+ disconnect_voucher_codes_from_draft_orders_task.delay(list(order_ids))+++def disconnect_voucher_codes_from_draft_orders_task(order_ids):+ # Batch of size 1000 takes ~1sec and consumes ~20mb at peak+ BATCH_SIZE = 1000+ ids = order_ids[:BATCH_SIZE]+ if orders := Order.objects.filter(pk__in=ids).only(+ "voucher_code", "should_refresh_prices"+ ):+ for order in orders:+ order.voucher_code = None+ order.should_refresh_prices = True+ Order.objects.bulk_update(orders, ["voucher_code", "should_refresh_prices"])+ OrderDiscount.objects.filter(order_id__in=ids).filter(+ type=DiscountType.VOUCHER+ ).delete()+ OrderLineDiscount.objects.filter(+ Exists(OrderLine.objects.filter(order_id__in=order_ids))+ ).filter(type=DiscountType.VOUCHER).delete()+ if remaining_ids := list(set(order_ids) - set(ids)):+ disconnect_voucher_codes_from_draft_orders_task.delay(remaining_ids)diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.pyindex ed2ecc09e4..09974ec90f 100644--- a/saleor/discount/tests/test_discounts.py+++ b/saleor/discount/tests/test_discounts.py@@ -19,10 +19,10 @@ from ..utils import (activate_voucher_code,add_voucher_usage_by_customer,deactivate_voucher_code,- decrease_voucher_code_usage,+ decrease_voucher_code_usage_value,get_discount_name,get_discount_translated_name,- increase_voucher_code_usage,+ increase_voucher_code_usage_value,remove_voucher_usage_by_customer,validate_voucher,)@@ -202,7 +202,7 @@ def test_increase_voucher_usage(channel_USD):channel=channel_USD,discount=Money(10, channel_USD.currency_code),)- increase_voucher_code_usage(code_instance)+ increase_voucher_code_usage_value(code_instance)code_instance.refresh_from_db(fields=["used"])assert code_instance.used == 1@@ -220,7 +220,7 @@ def test_decrease_voucher_usage(channel_USD):channel=channel_USD,discount=Money(10, channel_USD.currency_code),)- decrease_voucher_code_usage(code_instance)+ decrease_voucher_code_usage_value(code_instance)code_instance.refresh_from_db(fields=["used"])assert code_instance.used == 9diff --git a/saleor/discount/tests/test_tasks.py b/saleor/discount/tests/test_tasks.pyindex 0c2245fbde..321a6c4fc2 100644--- a/saleor/discount/tests/test_tasks.py+++ b/saleor/discount/tests/test_tasks.py@@ -3,12 +3,19 @@ from decimal import Decimalfrom unittest.mock import ANY, patchimport graphene+import pytestfrom django.utils import timezonefrom freezegun import freeze_time-from .. import RewardValueType-from ..models import Promotion, PromotionRule-from ..tasks import fetch_promotion_variants_and_product_ids, handle_promotion_toggle+from ...order.models import Order+from .. import DiscountType, RewardValueType+from ..models import OrderDiscount, OrderLineDiscount, Promotion, PromotionRule+from ..tasks import (+ decrease_voucher_codes_usage_task,+ disconnect_voucher_codes_from_draft_orders_task,+ fetch_promotion_variants_and_product_ids,+ handle_promotion_toggle,+)def test_fetch_promotion_variants_and_product_ids(@@ -177,3 +184,76 @@ def test_handle_promotion_toggle(product_list[0].id,product_list[2].id,}+++def test_decrease_voucher_code_usage_task_multiple_use(+ draft_order_list_with_multiple_use_voucher, voucher_multiple_use+):+ # given+ order_list = draft_order_list_with_multiple_use_voucher+ voucher = voucher_multiple_use+ voucher_codes = voucher.codes.all()[: len(order_list)]+ assert all([voucher_code.used == 1 for voucher_code in voucher_codes])+ voucher_code_ids = [voucher_code.pk for voucher_code in voucher_codes]++ # when+ decrease_voucher_codes_usage_task(voucher_code_ids)++ # then+ voucher_codes = voucher.codes.all()[: len(order_list)]+ assert all([voucher_code.used == 0 for voucher_code in voucher_codes])+++def test_decrease_voucher_code_usage_task_single_use(+ draft_order_list_with_single_use_voucher, voucher_single_use+):+ # given+ order_list = draft_order_list_with_single_use_voucher+ voucher = voucher_single_use+ voucher_codes = voucher.codes.all()[: len(order_list)]+ assert all([voucher_code.is_active is False for voucher_code in voucher_codes])+ voucher_code_ids = [voucher_code.pk for voucher_code in voucher_codes]++ # when+ decrease_voucher_codes_usage_task(voucher_code_ids)++ # then+ voucher_codes = voucher.codes.all()[: len(order_list)]+ assert all([voucher_code.is_active is True for voucher_code in voucher_codes])+++def test_disconnect_voucher_codes_from_draft_orders(+ draft_order_list_with_multiple_use_voucher, order_line+):+ # given+ order_list = draft_order_list_with_multiple_use_voucher+ order = order_list[0]+ order.lines.add(order_line)++ order_list_ids = [order.id for order in order_list]+ assert all([order.voucher_code for order in order_list])+ for order in order_list:+ order.should_refresh_prices = False+ Order.objects.bulk_update(order_list, ["should_refresh_prices"])+ assert all([order.should_refresh_prices is False for order in order_list])++ voucher_code = order.voucher_code+ order_discount = OrderDiscount.objects.create(+ order=order, voucher_code=voucher_code, type=DiscountType.VOUCHER+ )+ line_discount = OrderLineDiscount.objects.create(+ line=order_line, type=DiscountType.VOUCHER+ )++ # when+ disconnect_voucher_codes_from_draft_orders_task(order_list_ids)++ # then+ order_list = Order.objects.filter(id__in=order_list_ids).all()+ assert all([order.voucher_code is None for order in order_list])+ assert all([order.should_refresh_prices is True for order in order_list])++ with pytest.raises(line_discount._meta.model.DoesNotExist):+ line_discount.refresh_from_db()+ with pytest.raises(order_discount._meta.model.DoesNotExist):+ order_discount.refresh_from_db()diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 80e8d661e8..fa087668b5 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -14,10 +14,12 @@ from uuid import UUIDimport graphenefrom django.db.models import Exists, F, OuterRef, QuerySet+from django.utils import timezonefrom prices import Money, TaxedMoney, fixed_discount, percentage_discountfrom ..channel.models import Channelfrom ..core.taxes import zero_money+from ..core.utils.promo_code import InvalidPromoCodefrom ..discount.models import VoucherCustomerfrom . import DiscountType, PromotionRuleInfofrom .models import (@@ -26,6 +28,8 @@ from .models import (NotApplicable,Promotion,PromotionRule,+ Voucher,+ VoucherCode,)if TYPE_CHECKING:@@ -39,19 +43,32 @@ if TYPE_CHECKING:ProductVariantChannelListing,VariantChannelListingPromotionRule,)- from .models import Voucher, VoucherCodeCatalogueInfo = defaultdict[str, set[Union[int, str]]]CATALOGUE_FIELDS = ["categories", "collections", "products", "variants"]-def increase_voucher_code_usage(code: "VoucherCode") -> None:+def increase_voucher_usage(+ voucher: "Voucher",+ code: "VoucherCode",+ customer_email: str,+ increase_voucher_customer_usage: bool = True,+) -> None:+ if voucher.usage_limit:+ increase_voucher_code_usage_value(code)+ if voucher.apply_once_per_customer and increase_voucher_customer_usage:+ add_voucher_usage_by_customer(code, customer_email)+ if voucher.single_use:+ deactivate_voucher_code(code)+++def increase_voucher_code_usage_value(code: "VoucherCode") -> None:"""Increase voucher code uses by 1."""code.used = F("used") + 1code.save(update_fields=["used"])-def decrease_voucher_code_usage(code: "VoucherCode") -> None:+def decrease_voucher_code_usage_value(code: "VoucherCode") -> None:"""Decrease voucher code uses by 1."""code.used = F("used") - 1code.save(update_fields=["used"])@@ -93,7 +110,7 @@ def release_voucher_code_usage(if not code:returnif voucher and voucher.usage_limit:- decrease_voucher_code_usage(code)+ decrease_voucher_code_usage_value(code)if voucher and voucher.single_use:activate_voucher_code(code)if user_email:@@ -112,6 +129,32 @@ def get_sale_id(promotion: "Promotion"):)+def get_voucher_code_instance(+ voucher_code: str,+ channel_slug: str,+):+ """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+ )+ .filter(+ Exists(+ VoucherCode.objects.filter(+ code=voucher_code,+ voucher_id=OuterRef("id"),+ is_active=True,+ )+ )+ )+ .exists()+ ):+ code_instance = VoucherCode.objects.get(code=voucher_code)+ else:+ raise InvalidPromoCode()+ return code_instance++def calculate_discounted_price_for_rules(*, price: Money, rules: Iterable["PromotionRule"], currency: str):@@ -233,16 +276,16 @@ def validate_voucher_for_checkout(def validate_voucher_in_order(order: "Order"):- subtotal = order.get_subtotal()- quantity = order.get_total_quantity()- customer_email = order.get_customer_email()if not order.voucher:return+ subtotal = order.get_subtotal()+ quantity = order.get_total_quantity()+ customer_email = order.get_customer_email()tax_configuration = order.channel.tax_configurationprices_entered_with_tax = tax_configuration.prices_entered_with_tax-value = subtotal.gross if prices_entered_with_tax else subtotal.net+validate_voucher(order.voucher, value, quantity, customer_email, order.channel, order.user)diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.pyindex babfc2fddd..d1bddf9e2a 100644--- a/saleor/graphql/channel/mutations/channel_create.py+++ b/saleor/graphql/channel/mutations/channel_create.py@@ -17,6 +17,7 @@ from ...core.descriptions import (ADDED_IN_314,ADDED_IN_315,ADDED_IN_316,+ ADDED_IN_318,DEPRECATED_IN_3X_INPUT,DEPRECATED_PREVIEW_IN_316_INPUT,PREVIEW_FEATURE,@@ -139,6 +140,17 @@ class OrderSettingsInput(BaseInputObjectType):"`checkoutComplete` mutation." + ADDED_IN_315 + PREVIEW_FEATURE),)+ include_draft_order_in_voucher_usage = graphene.Boolean(+ required=False,+ description=(+ "Specify whether a coupon applied to draft orders will count toward "+ "voucher usage."+ "\n\nWarning: when switching this setting from `false` to `true`, "+ "the vouchers will be disconnected from all draft orders."+ + ADDED_IN_318+ + PREVIEW_FEATURE+ ),+ )class Meta:doc_category = DOC_CATEGORY_ORDERS@@ -262,7 +274,7 @@ class ChannelCreate(ModelMutation):if stock_settings := cleaned_input.get("stock_settings"):cleaned_input["allocation_strategy"] = stock_settings["allocation_strategy"]if order_settings := cleaned_input.get("order_settings"):- clean_input_order_settings(order_settings, cleaned_input)+ clean_input_order_settings(order_settings, cleaned_input, instance)if checkout_settings := cleaned_input.get("checkout_settings"):clean_input_checkout_settings(checkout_settings, cleaned_input)diff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.pyindex 674341e0c5..a65b5bbb9d 100644--- a/saleor/graphql/channel/mutations/channel_update.py+++ b/saleor/graphql/channel/mutations/channel_update.py@@ -5,6 +5,10 @@ from django.utils.text import slugifyfrom ....channel import modelsfrom ....channel.error_codes import ChannelErrorCodefrom ....core.tracing import traced_atomic_transaction+from ....discount.tasks import (+ decrease_voucher_code_usage_of_draft_orders,+ disconnect_voucher_codes_from_draft_orders,+)from ....permission.enums import (ChannelPermissions,CheckoutPermissions,@@ -125,7 +129,7 @@ class ChannelUpdate(ModelMutation):if stock_settings := cleaned_input.get("stock_settings"):cleaned_input["allocation_strategy"] = stock_settings["allocation_strategy"]if order_settings := cleaned_input.get("order_settings"):- clean_input_order_settings(order_settings, cleaned_input)+ clean_input_order_settings(order_settings, cleaned_input, instance)if checkout_settings := cleaned_input.get("checkout_settings"):clean_input_checkout_settings(checkout_settings, cleaned_input)@@ -218,9 +222,26 @@ class ChannelUpdate(ModelMutation):if remove_warehouses:instance.warehouses.remove(*remove_warehouses)+ @classmethod+ def _update_voucher_usage(cls, cleaned_input, instance):+ """Update voucher code usage.++ When the 'include_draft_order_in_voucher_usage' flag is changed:+ - True -> False: decrease voucher usage of all vouchers associated with+ draft orders.+ - False -> True: disconnect vouchers from all draft orders.+ """+ current_flag = cleaned_input.get("include_draft_order_in_voucher_usage")+ previous_flag = cleaned_input.get("prev_include_draft_order_in_voucher_usage")+ if current_flag is False and previous_flag is True:+ decrease_voucher_code_usage_of_draft_orders(instance.id)+ elif current_flag is True and previous_flag is False:+ disconnect_voucher_codes_from_draft_orders(instance.id)+@classmethoddef post_save_action(cls, info: ResolveInfo, instance, cleaned_input):manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.channel_updated, instance)if cleaned_input.get("metadata"):cls.call_event(manager.channel_metadata_updated, instance)+ cls._update_voucher_usage(cleaned_input, instance)diff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.pyindex 1cf607c34f..ef13c778d6 100644--- a/saleor/graphql/channel/mutations/utils.py+++ b/saleor/graphql/channel/mutations/utils.py@@ -3,7 +3,8 @@ from typing import Optionalfrom django.core.exceptions import ValidationError-from saleor.graphql.core.enums import ChannelErrorCode+from ....channel.models import Channel+from ...core.enums import ChannelErrorCodeDELETE_EXPIRED_ORDERS_MAX_DAYS = 120@@ -40,23 +41,24 @@ def clean_delete_expired_orders_after(delete_expired_orders_after: int) -> timedreturn timedelta(days=delete_expired_orders_after)-def clean_input_order_settings(order_settings: dict, cleaned_input: dict):- automatically_confirm_all_new_orders = order_settings.get(- "automatically_confirm_all_new_orders"- )- if automatically_confirm_all_new_orders is not None:- cleaned_input[- "automatically_confirm_all_new_orders"- ] = automatically_confirm_all_new_orders+def clean_input_order_settings(+ order_settings: dict, cleaned_input: dict, instance: Channel+):+ channel_settings = [+ "automatically_confirm_all_new_orders",+ "automatically_fulfill_non_shippable_gift_card",+ "default_transaction_flow_strategy",+ "allow_unpaid_orders",+ "include_draft_order_in_voucher_usage",+ ]- automatically_fulfill_non_shippable_gift_card = order_settings.get(- "automatically_fulfill_non_shippable_gift_card"- )- if automatically_fulfill_non_shippable_gift_card is not None:- cleaned_input[- "automatically_fulfill_non_shippable_gift_card"- ] = automatically_fulfill_non_shippable_gift_card- if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):+ for field in channel_settings:+ if (value := order_settings.get(field)) is not None:+ cleaned_input[field] = value++ if (+ mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy")+ ) is not None:cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategyif "expire_orders_after" in order_settings:@@ -71,16 +73,9 @@ def clean_input_order_settings(order_settings: dict, cleaned_input: dict):"delete_expired_orders_after"] = clean_delete_expired_orders_after(delete_expired_orders_after)- if default_transaction_strategy := order_settings.get(- "default_transaction_flow_strategy"- ):- cleaned_input[- "default_transaction_flow_strategy"- ] = default_transaction_strategy-- allow_unpaid_orders = order_settings.get("allow_unpaid_orders")- if allow_unpaid_orders is not None:- cleaned_input["allow_unpaid_orders"] = allow_unpaid_orders+ cleaned_input[+ "prev_include_draft_order_in_voucher_usage"+ ] = instance.include_draft_order_in_voucher_usagedef clean_input_checkout_settings(checkout_settings: dict, cleaned_input: dict):diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.pyindex 7328c0ab68..af4e7b58d3 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py@@ -47,6 +47,7 @@ CHANNEL_CREATE_MUTATION = """defaultTransactionFlowStrategydeleteExpiredOrdersAfterallowUnpaidOrders+ includeDraftOrderInVoucherUsage}checkoutSettings {useLegacyErrorFlow@@ -86,6 +87,7 @@ def test_channel_create_mutation_as_staff_user("automaticallyConfirmAllNewOrders": False,"automaticallyFulfillNonShippableGiftCard": False,"expireOrdersAfter": 10,+ "includeDraftOrderInVoucherUsage": True,},"checkoutSettings": {"useLegacyErrorFlow": False},}@@ -119,6 +121,7 @@ def test_channel_create_mutation_as_staff_user(is False)assert channel_data["orderSettings"]["expireOrdersAfter"] == 10+ assert channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"] is Trueassert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False@@ -172,6 +175,7 @@ def test_channel_create_mutation_as_app(is True)assert channel_data["orderSettings"]["expireOrdersAfter"] is None+ assert channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"] is Falseassert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is Falsediff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.pyindex 3f1fe8efa2..0739ce62b6 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py@@ -45,6 +45,7 @@ CHANNEL_UPDATE_MUTATION = """defaultTransactionFlowStrategydeleteExpiredOrdersAfterallowUnpaidOrders+ includeDraftOrderInVoucherUsage}}errors{@@ -60,7 +61,9 @@ CHANNEL_UPDATE_MUTATION = """def test_channel_update_mutation_as_staff_user(- permission_manage_channels, staff_api_client, channel_USD+ permission_manage_channels,+ staff_api_client,+ channel_USD,):# givenchannel_id = graphene.Node.to_global_id("Channel", channel_USD.id)@@ -80,6 +83,7 @@ def test_channel_update_mutation_as_staff_user("automaticallyFulfillNonShippableGiftCard": False,"expireOrdersAfter": 10,"allowUnpaidOrders": True,+ "includeDraftOrderInVoucherUsage": True,},},}@@ -112,6 +116,7 @@ def test_channel_update_mutation_as_staff_user(is False)assert channel_data["orderSettings"]["expireOrdersAfter"] == 10+ assert channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"] is Trueassert channel_data["orderSettings"]["allowUnpaidOrders"] is True@@ -1139,6 +1144,80 @@ def test_channel_update_set_incorrect_delete_expired_orders_after(assert error["code"] == ChannelErrorCode.INVALID.name+@patch("saleor.discount.tasks.decrease_voucher_codes_usage_task.delay")+def test_channel_update_order_settings_voucher_usage_disable(+ decrease_voucher_codes_usage_task_mock,+ permission_manage_orders,+ staff_api_client,+ channel_USD,+ draft_order_list_with_multiple_use_voucher,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ channel_USD.include_draft_order_in_voucher_usage = True+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])++ variables = {+ "id": channel_id,+ "input": {+ "orderSettings": {+ "includeDraftOrderInVoucherUsage": False,+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_orders,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ assert data["channel"]["orderSettings"]["includeDraftOrderInVoucherUsage"] is False+ decrease_voucher_codes_usage_task_mock.assert_called_once()+++@patch("saleor.discount.tasks.disconnect_voucher_codes_from_draft_orders_task.delay")+def test_channel_update_order_settings_voucher_usage_enable(+ disconnect_voucher_codes_from_draft_orders_task_mock,+ permission_manage_orders,+ staff_api_client,+ channel_USD,+ draft_order_list_with_multiple_use_voucher,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ channel_USD.include_draft_order_in_voucher_usage = False+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])++ variables = {+ "id": channel_id,+ "input": {+ "orderSettings": {+ "includeDraftOrderInVoucherUsage": True,+ },+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_orders,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ assert data["channel"]["orderSettings"]["includeDraftOrderInVoucherUsage"] is True+ disconnect_voucher_codes_from_draft_orders_task_mock.assert_called_once()++CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """mutation UpdateChannel($id: ID!,$input: ChannelUpdateInput!){channelUpdate(id: $id, input: $input){diff --git a/saleor/graphql/channel/tests/queries/test_channel.py b/saleor/graphql/channel/tests/queries/test_channel.pyindex e19cc7bda0..c0ade8ad7c 100644--- a/saleor/graphql/channel/tests/queries/test_channel.py+++ b/saleor/graphql/channel/tests/queries/test_channel.py@@ -294,6 +294,7 @@ QUERY_CHANNEL_ORDER_SETTINGS = """defaultTransactionFlowStrategydeleteExpiredOrdersAfterallowUnpaidOrders+ includeDraftOrderInVoucherUsage}}}@@ -350,6 +351,10 @@ def test_query_channel_order_settings_as_staff_user(channel_data["orderSettings"]["allowUnpaidOrders"]== channel_USD.allow_unpaid_orders)+ assert (+ channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"]+ == channel_USD.include_draft_order_in_voucher_usage+ )def test_query_channel_order_settings_as_app(@@ -396,6 +401,10 @@ def test_query_channel_order_settings_as_app(channel_data["orderSettings"]["defaultTransactionFlowStrategy"]== channel_USD.default_transaction_flow_strategy.upper())+ assert (+ channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"]+ == channel_USD.include_draft_order_in_voucher_usage+ )def test_query_channel_order_settings_as_staff_user_no_permission(diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex 1d5cadadc9..914d4f246d 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -30,6 +30,7 @@ from ..core.descriptions import (ADDED_IN_314,ADDED_IN_315,ADDED_IN_316,+ ADDED_IN_318,DEPRECATED_IN_3X_FIELD,DEPRECATED_PREVIEW_IN_316_FIELD,PREVIEW_FEATURE,@@ -272,6 +273,13 @@ class OrderSettings(ObjectType):"`checkoutComplete` mutation." + ADDED_IN_315 + PREVIEW_FEATURE),)+ include_draft_order_in_voucher_usage = graphene.Boolean(+ required=True,+ description=(+ "Determine if voucher applied on draft order should be count toward "+ "voucher usage." + ADDED_IN_318 + PREVIEW_FEATURE+ ),+ )class Meta:description = "Represents the channel-specific order settings."@@ -557,6 +565,9 @@ class Channel(ModelObjectType):mark_as_paid_strategy=root.order_mark_as_paid_strategy,default_transaction_flow_strategy=root.default_transaction_flow_strategy,delete_expired_orders_after=root.delete_expired_orders_after.days,+ include_draft_order_in_voucher_usage=(+ root.include_draft_order_in_voucher_usage+ ),allow_unpaid_orders=(root.allow_unpaid_orders),)diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex e804df1ec7..0decd13da8 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -9,6 +9,8 @@ from ....core.exceptions import InsufficientStockfrom ....core.postgres import FlatConcatSearchVectorfrom ....core.taxes import zero_taxed_moneyfrom ....core.tracing import traced_atomic_transaction+from ....discount.models import VoucherCode+from ....discount.utils import add_voucher_usage_by_customerfrom ....order import OrderStatus, modelsfrom ....order.actions import order_createdfrom ....order.calculations import fetch_order_prices_if_expired@@ -70,6 +72,18 @@ class DraftOrderComplete(BaseMutation):)return order+ @classmethod+ def setup_voucher_customer(cls, order, channel):+ if (+ order.voucher+ and order.voucher_code+ and order.voucher.apply_once_per_customer+ and channel.include_draft_order_in_voucher_usage+ ):+ code = VoucherCode.objects.filter(code=order.voucher_code).first()+ if code:+ add_voucher_usage_by_customer(code, order.get_customer_email())+@classmethoddef perform_mutation( # type: ignore[override]cls, _root, info: ResolveInfo, /, *, id: str@@ -108,6 +122,7 @@ class DraftOrderComplete(BaseMutation):order.save()channel = order.channel+ cls.setup_voucher_customer(order, channel)order_lines_info = []for line in order.lines.all():if not line.variant:diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex 31a419ed7f..6dfe4c639b 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -1,8 +1,8 @@from collections import defaultdict+from typing import Optionalimport graphenefrom django.core.exceptions import ValidationError-from django.db.models import Exists, OuterReffrom ....account.models import Userfrom ....checkout import AddressType@@ -10,6 +10,7 @@ from ....core.taxes import TaxErrorfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils.url import validate_storefront_urlfrom ....discount.models import Voucher, VoucherCode+from ....discount.utils import get_voucher_code_instance, increase_voucher_usagefrom ....order import OrderOrigin, OrderStatus, events, modelsfrom ....order.error_codes import OrderErrorCodefrom ....order.search import update_order_search_vector@@ -209,9 +210,9 @@ class DraftOrderCreate(voucher = cleaned_input.get("voucher", None)voucher_code = cleaned_input.get("voucher_code", None)cls.clean_voucher_and_voucher_code(voucher, voucher_code)- if voucher:+ if "voucher" in cleaned_input:cls.clean_voucher(voucher, channel, cleaned_input)- if voucher_code:+ elif "voucher_code" in cleaned_input:cls.clean_voucher_code(voucher_code, channel, cleaned_input)if channel:@@ -253,61 +254,92 @@ class DraftOrderCreate(return instance.channel if hasattr(instance, "channel") else None@classmethod- def clean_voucher(cls, voucher, channel, cleaned_input):- if not voucher.channel_listings.filter(channel=channel).exists():+ def clean_voucher_and_voucher_code(cls, voucher, voucher_code):+ if voucher and voucher_code:raise ValidationError({"voucher": ValidationError(- "Voucher not available for this order.",- code=OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value,+ "You cannot use both a voucher and a voucher code for the same "+ "order. Please choose one.",+ code=OrderErrorCode.INVALID.value,)})- first_code = voucher.codes.first()- if first_code:- cleaned_input["voucher_code"] = first_code.code++ @classmethod+ def clean_voucher(cls, voucher, channel, cleaned_input):+ # We need to clean voucher_code as well+ if voucher is None:+ cleaned_input["voucher_code"] = None+ return+ 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_voucher_code_instance(voucher.code, channel.slug)+ except ValidationError:+ raise ValidationError(+ {+ "voucher": ValidationError(+ "Voucher is invalid.",+ code=OrderErrorCode.INVALID_VOUCHER.value,+ )+ }+ )+ else:+ cls.clean_voucher_listing(voucher, channel, "voucher")+ if not code_instance:+ code_instance = voucher.codes.first()+ if code_instance:+ cleaned_input["voucher_code"] = code_instance.code+ cleaned_input["voucher_code_instance"] = code_instance@classmethoddef clean_voucher_code(- cls, voucher_code: str, channel: Channel, cleaned_input: dict+ cls, voucher_code: Optional[str], channel: Channel, cleaned_input: dict):- voucher = Voucher.objects.filter(- Exists(- VoucherCode.objects.filter(code=voucher_code, voucher_id=OuterRef("pk"))- )- ).first()-- if not voucher:- raise ValidationError(- {- "voucher": ValidationError(- "Invalid voucher code.",- code=OrderErrorCode.INVALID_VOUCHER_CODE.value,- )- }- )+ # We need to clean voucher instance as well+ 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:+ raise ValidationError(+ {+ "voucher_code": ValidationError(+ "Voucher code is invalid.",+ code=OrderErrorCode.INVALID_VOUCHER_CODE.value,+ )+ }+ )+ voucher = code_instance.voucherelse:- if not voucher.channel_listings.filter(channel=channel).exists():+ code_instance = VoucherCode.objects.filter(code=voucher_code).first()+ if not code_instance:raise ValidationError({"voucher": ValidationError(- "Voucher not available for this order.",- code=OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value,+ "Invalid voucher code.",+ code=OrderErrorCode.INVALID_VOUCHER_CODE.value,)})- cleaned_input["voucher"] = voucher- cleaned_input["voucher_code"] = voucher_code+ voucher = code_instance.voucher+ cls.clean_voucher_listing(voucher, channel, "voucher_code")+ cleaned_input["voucher"] = voucher+ cleaned_input["voucher_code_instance"] = code_instance@classmethod- def clean_voucher_and_voucher_code(cls, voucher, voucher_code):- if voucher and voucher_code:+ def clean_voucher_listing(cls, voucher: "Voucher", channel: "Channel", field: str):+ if not voucher.channel_listings.filter(channel=channel).exists():raise ValidationError({- "voucher": ValidationError(- "You cannot use both a voucher and a voucher code for the same "- "order. Please choose one.",- code=OrderErrorCode.INVALID.value,+ field: ValidationError(+ "Voucher not available for this order.",+ code=OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value,)})@@ -513,6 +545,9 @@ class DraftOrderCreate(# Save any changes create/update the draftcls._commit_changes(info, instance, cleaned_input, is_new_instance, app)+ if voucher := cleaned_input.get("voucher"):+ cls.handle_order_voucher(cleaned_input, instance, voucher)+update_order_display_gross_prices(instance)if is_new_instance:@@ -537,3 +572,15 @@ class DraftOrderCreate(update_order_search_vector(instance, save=False)instance.save(update_fields=updated_fields)++ @classmethod+ def handle_order_voucher(cls, cleaned_input, instance, voucher):+ code_instance = cleaned_input.pop("voucher_code_instance", None)+ channel = instance.channel+ if channel.include_draft_order_in_voucher_usage:+ increase_voucher_usage(+ voucher,+ code_instance,+ instance.user_email or instance.user.email,+ increase_voucher_customer_usage=False,+ )diff --git a/saleor/graphql/order/mutations/draft_order_delete.py b/saleor/graphql/order/mutations/draft_order_delete.pyindex 969a76963c..a89522372a 100644--- a/saleor/graphql/order/mutations/draft_order_delete.py+++ b/saleor/graphql/order/mutations/draft_order_delete.py@@ -2,6 +2,8 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom ....core.tracing import traced_atomic_transaction+from ....discount.models import VoucherCode+from ....discount.utils import release_voucher_code_usagefrom ....order import OrderStatus, modelsfrom ....order.error_codes import OrderErrorCodefrom ....permission.enums import OrderPermissions@@ -58,3 +60,10 @@ class DraftOrderDelete(@classmethoddef get_instance_channel_id(cls, instance):return instance.channel_id++ @classmethod+ def post_save_action(cls, info, instance, _):+ if code := instance.voucher_code:+ if voucher_code := VoucherCode.objects.filter(code=code).first():+ voucher = voucher_code.voucher+ release_voucher_code_usage(voucher_code, voucher, None)diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex 1ff2c7b3fb..d8e6e2ced4 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -6,6 +6,7 @@ import pytzfrom django.db.models import Sumfrom .....core.taxes import zero_taxed_money+from .....discount.models import VoucherCustomerfrom .....order import OrderOrigin, OrderStatusfrom .....order import events as order_eventsfrom .....order.error_codes import OrderErrorCode@@ -30,6 +31,20 @@ DRAFT_ORDER_COMPLETE_MUTATION = """statusoriginpaymentStatus+ voucher {+ code+ }+ voucherCode+ total {+ net {+ amount+ }+ }+ undiscountedTotal {+ net {+ amount+ }+ }}}}@@ -44,6 +59,7 @@ def test_draft_order_complete(staff_user,draft_order,):+ # givenorder = draft_orderpermission_group_manage_orders.user_set.add(staff_api_client.user)@@ -55,7 +71,11 @@ def test_draft_order_complete(order_id = graphene.Node.to_global_id("Order", order.id)variables = {"id": order_id}++ # whenresponse = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["draftOrderComplete"]["order"]order.refresh_from_db()@@ -137,6 +157,135 @@ def test_draft_order_complete_by_app(assert order.search_vector+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")+def test_draft_order_complete_with_voucher(+ product_variant_out_of_stock_webhook_mock,+ staff_api_client,+ permission_group_manage_orders,+ staff_user,+ draft_order,+ voucher,+):+ # given+ order = draft_order+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ # Ensure no events were created+ assert not OrderEvent.objects.exists()++ # Ensure no allocation were created+ assert not Allocation.objects.filter(order_line__order=order).exists()++ order.voucher = voucher+ code_instance = voucher.codes.first()+ order.voucher_code = code_instance.code+ order.should_refresh_prices = True+ order.save(update_fields=["voucher", "voucher_code", "should_refresh_prices"])++ voucher_listing = voucher.channel_listings.get(channel=order.channel)+ order_total = order.total_net_amount++ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}++ # when+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["draftOrderComplete"]["order"]+ order.refresh_from_db()+ assert data["status"] == order.status.upper()+ assert data["origin"] == OrderOrigin.DRAFT.upper()+ assert data["voucherCode"] == code_instance.code+ assert data["voucher"]["code"] == voucher.code+ assert data["undiscountedTotal"]["net"]["amount"] == order_total+ assert (+ data["total"]["net"]["amount"] == order_total - voucher_listing.discount_value+ )+ assert order.search_vector++ for line in order.lines.all():+ allocation = line.allocations.get()+ assert allocation.quantity_allocated == line.quantity_unfulfilled++ # ensure there are only 2 events with correct types+ event_params = {+ "user": staff_user,+ "type__in": [+ order_events.OrderEvents.PLACED_FROM_DRAFT,+ order_events.OrderEvents.CONFIRMED,+ ],+ "parameters": {},+ }+ matching_events = OrderEvent.objects.filter(**event_params)+ assert matching_events.count() == 2+ assert matching_events[0].type != matching_events[1].type+ assert not OrderEvent.objects.exclude(**event_params).exists()+ product_variant_out_of_stock_webhook_mock.assert_called_once_with(+ Stock.objects.last()+ )+ assert not VoucherCustomer.objects.filter(+ voucher_code=code_instance, customer_email=order.get_customer_email()+ ).exists()+++def test_draft_order_complete_with_invalid_voucher(+ staff_api_client,+ permission_group_manage_orders,+ staff_user,+ draft_order_with_voucher,+):+ # given+ order = draft_order_with_voucher+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order.voucher.channel_listings.all().delete()+ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}++ # when+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["draftOrderComplete"]+ assert not data["order"]+ assert data["errors"][0]["code"] == OrderErrorCode.INVALID_VOUCHER.name+ assert data["errors"][0]["field"] == "voucher"+++def test_draft_order_complete_with_voucher_once_per_customer(+ staff_api_client,+ permission_group_manage_orders,+ staff_user,+ draft_order_with_voucher,+):+ # given+ order = draft_order_with_voucher+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ order.voucher.apply_once_per_customer = True+ order.voucher.save(update_fields=["apply_once_per_customer"])++ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}+ code_instance = order.voucher.codes.first()+ assert not VoucherCustomer.objects.filter(+ voucher_code=code_instance, customer_email=order.get_customer_email()+ ).exists()+ # when+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["draftOrderComplete"]["order"]+ assert data["voucherCode"] == code_instance.code+ assert data["voucher"]["code"] == order.voucher.code+ assert VoucherCustomer.objects.filter(+ voucher_code=code_instance, customer_email=order.get_customer_email()+ ).exists()++@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_draft_order_complete_0_total(product_variant_out_of_stock_webhook_mock,@@ -145,6 +294,7 @@ def test_draft_order_complete_0_total(staff_user,draft_order,):+ # given"""Ensure the payment status is FULLY_CHARGED when the total order price is 0."""permission_group_manage_orders.user_set.add(staff_api_client.user)order = draft_order@@ -168,7 +318,11 @@ def test_draft_order_complete_0_total(order_id = graphene.Node.to_global_id("Order", order.id)variables = {"id": order_id}++ # whenresponse = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["draftOrderComplete"]["order"]order.refresh_from_db()@@ -208,6 +362,7 @@ def test_draft_order_complete_without_sku(staff_user,draft_order,):+ # givenpermission_group_manage_orders.user_set.add(staff_api_client.user)ProductVariant.objects.update(sku=None)draft_order.lines.update(product_sku=None)@@ -222,7 +377,11 @@ def test_draft_order_complete_without_sku(order_id = graphene.Node.to_global_id("Order", order.id)variables = {"id": order_id}++ # whenresponse = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["draftOrderComplete"]["order"]order.refresh_from_db()@@ -258,6 +417,7 @@ def test_draft_order_complete_with_out_of_stock_webhook(permission_group_manage_orders,draft_order,):+ # givenpermission_group_manage_orders.user_set.add(staff_api_client.user)order = draft_orderfirst_line = order.lines.first()@@ -268,8 +428,11 @@ def test_draft_order_complete_with_out_of_stock_webhook(assert not Allocation.objects.filter(order_line__order=order).exists()order_id = graphene.Node.to_global_id("Order", order.id)variables = {"id": order_id}++ # whenstaff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)+ # thentotal_stock = Stock.objects.aggregate(Sum("quantity"))["quantity__sum"]total_allocation = Allocation.objects.filter(order_line__order=order).aggregate(Sum("quantity_allocated")@@ -285,6 +448,7 @@ def test_draft_order_from_reissue_complete(staff_user,draft_order,):+ # givenpermission_group_manage_orders.user_set.add(staff_api_client.user)order = draft_orderorder.origin = OrderOrigin.REISSUE@@ -298,7 +462,11 @@ def test_draft_order_from_reissue_complete(order_id = graphene.Node.to_global_id("Order", order.id)variables = {"id": order_id}++ # whenresponse = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["draftOrderComplete"]["order"]order.refresh_from_db()@@ -330,6 +498,7 @@ def test_draft_order_complete_with_inactive_channel(staff_user,draft_order,):+ # givenpermission_group_manage_orders.user_set.add(staff_api_client.user)order = draft_orderchannel = order.channel@@ -338,7 +507,11 @@ def test_draft_order_complete_with_inactive_channel(order_id = graphene.Node.to_global_id("Order", order.id)variables = {"id": order_id}++ # whenresponse = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["draftOrderComplete"]assert data["errors"][0]["code"] == OrderErrorCode.CHANNEL_INACTIVE.name@@ -351,6 +524,7 @@ def test_draft_order_complete_with_unavailable_variant(staff_user,draft_order,):+ # givenpermission_group_manage_orders.user_set.add(staff_api_client.user)order = draft_ordervariant = order.lines.first().variant@@ -360,7 +534,11 @@ def test_draft_order_complete_with_unavailable_variant(variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)variables = {"id": order_id}++ # whenresponse = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["draftOrderComplete"]assert data["errors"][0]["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name@@ -374,6 +552,7 @@ def test_draft_order_complete_channel_without_shipping_zones(staff_user,draft_order,):+ # givenpermission_group_manage_orders.user_set.add(staff_api_client.user)order = draft_orderorder.channel.shipping_zones.clear()@@ -386,7 +565,11 @@ def test_draft_order_complete_channel_without_shipping_zones(order_id = graphene.Node.to_global_id("Order", order.id)variables = {"id": order_id}++ # whenresponse = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["draftOrderComplete"]diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.pyindex cae148c243..4e9ff7f779 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py@@ -10,7 +10,7 @@ from prices import Moneyfrom .....checkout import AddressTypefrom .....core.taxes import TaxError, zero_taxed_moneyfrom .....discount import DiscountType, DiscountValueType-from .....discount.models import VoucherChannelListing+from .....discount.models import VoucherChannelListing, VoucherCustomerfrom .....order import OrderStatusfrom .....order import events as order_eventsfrom .....order.error_codes import OrderErrorCode@@ -129,6 +129,7 @@ def test_draft_order_create_with_voucher(channel_USD,graphql_address_data,):+ # givenvariant_0 = variantquery = DRAFT_ORDER_CREATE_MUTATIONpermission_group_manage_orders.user_set.add(staff_api_client.user)@@ -273,6 +274,7 @@ def test_draft_order_create_with_voucher_and_voucher_code(channel_USD,graphql_address_data,):+ # givenvariant_0 = variantquery = DRAFT_ORDER_CREATE_MUTATIONpermission_group_manage_orders.user_set.add(staff_api_client.user)@@ -282,15 +284,18 @@ def test_draft_order_create_with_voucher_and_voucher_code(user_id = graphene.Node.to_global_id("User", customer_user.id)variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)+ variant_0_qty = 2variant_1 = product_without_shipping.variants.first()- variant_1.quantity = 2+ variant_1_qty = 1+ variant_1.quantity = variant_1_qtyvariant_1.save()+variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)discount = "10"customer_note = "Test note"variant_list = [- {"variantId": variant_0_id, "quantity": 2},- {"variantId": variant_1_id, "quantity": 1},+ {"variantId": variant_0_id, "quantity": variant_0_qty},+ {"variantId": variant_1_id, "quantity": variant_1_qty},]shipping_address = graphql_address_datashipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)@@ -315,7 +320,11 @@ def test_draft_order_create_with_voucher_and_voucher_code("externalReference": external_reference,}}++ # whenresponse = staff_api_client.post_graphql(query, variables)++ # thencontent = get_graphql_content(response)error = content["data"]["draftOrderCreate"]["errors"][0]assert error["field"] == "voucher"@@ -339,6 +348,7 @@ def test_draft_order_create_with_voucher_code(channel_USD,graphql_address_data,):+ # givenvariant_0 = variantquery = DRAFT_ORDER_CREATE_MUTATIONvoucher_code = voucher.codes.first()@@ -387,14 +397,17 @@ def test_draft_order_create_with_voucher_code("externalReference": external_reference,}}+ # whenresponse = staff_api_client.post_graphql(query, variables)content = get_graphql_content(response)+ # thenassert not content["data"]["draftOrderCreate"]["errors"]stored_metadata = {"public": "public_value"}data = content["data"]["draftOrderCreate"]["order"]assert data["status"] == OrderStatus.DRAFT.upper()- assert data["voucherCode"] == voucher_code.code+ assert data["voucher"]["code"] == voucher.code+ assert data["voucherCode"] == voucher.codeassert data["customerNote"] == customer_noteassert data["redirectUrl"] == redirect_urlassert data["externalReference"] == external_reference@@ -416,7 +429,6 @@ def test_draft_order_create_with_voucher_code(+ channel_listing_1.discounted_price_amount * variant_1_qty+ shipping_total.amount)-assert data["undiscountedTotal"]["gross"]["amount"] == order_totalassert (data["total"]["gross"]["amount"] == order_total - voucher_listing.discount_value@@ -433,9 +445,6 @@ def test_draft_order_create_with_voucher_code(assert order.shipping_address.metadata == stored_metadataassert order.search_vectorassert order.external_reference == external_reference- shipping_total = shipping_method.channel_listings.get(- channel_id=order.channel_id- ).get_total()assert order.base_shipping_price == shipping_total# Ensure the correct event was created@@ -472,6 +481,119 @@ def test_draft_order_create_with_voucher_code(assert order_discount.amount_value == voucher_listing.discount_value+def test_draft_order_create_percentage_voucher(+ staff_api_client,+ permission_group_manage_orders,+ staff_user,+ customer_user,+ shipping_method,+ variant,+ voucher_percentage,+ channel_USD,+ graphql_address_data,+):+ # given+ query = DRAFT_ORDER_CREATE_MUTATION+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ # Ensure no events were created yet+ assert not OrderEvent.objects.exists()++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ channel_listing = variant.channel_listings.get(channel=channel_USD)+ 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_listing = voucher_percentage.channel_listings.get(channel=channel_USD)+ voucher_id = graphene.Node.to_global_id("Voucher", voucher_percentage.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,+ "voucher": voucher_id,+ "channelId": channel_id,+ "redirectUrl": redirect_url,+ }+ }+ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ assert not content["data"]["draftOrderCreate"]["errors"]+ data = content["data"]["draftOrderCreate"]["order"]+ assert data["status"] == OrderStatus.DRAFT.upper()+ assert data["voucher"]["code"] == voucher_percentage.code+ assert data["redirectUrl"] == redirect_url+ assert (+ data["billingAddress"]["streetAddress1"]+ == graphql_address_data["streetAddress1"]+ )+ assert (+ data["shippingAddress"]["streetAddress1"]+ == graphql_address_data["streetAddress1"]+ )+ assert data["billingAddress"]["metadata"] == graphql_address_data["metadata"]+ assert data["shippingAddress"]["metadata"] == graphql_address_data["metadata"]+ shipping_total = shipping_method.channel_listings.get(+ channel=channel_USD+ ).get_total()+ subtotal = channel_listing.discounted_price_amount * variant_qty+ assert (+ data["undiscountedTotal"]["gross"]["amount"] == subtotal + shipping_total.amount+ )+ discount_amount = subtotal * voucher_listing.discount_value / 100+ assert (+ data["total"]["gross"]["amount"]+ == subtotal - discount_amount + shipping_total.amount+ )++ order = Order.objects.first()+ assert order.user == customer_user+ assert order.shipping_method == shipping_method+ assert order.shipping_method_name == shipping_method.name+ assert order.base_shipping_price == shipping_total++ # Ensure the correct event was created+ created_draft_event = OrderEvent.objects.get(+ type=order_events.OrderEvents.DRAFT_CREATED+ )+ assert created_draft_event.user == staff_user+ assert created_draft_event.parameters == {}++ # Ensure the order_added_products_event was created properly+ added_products_event = OrderEvent.objects.get(+ type=order_events.OrderEvents.ADDED_PRODUCTS+ )+ event_parameters = added_products_event.parameters+ assert event_parameters+ assert len(event_parameters["lines"]) == 1++ order_line = order.lines.first()+ assert event_parameters["lines"][0]["item"] == str(order_line)+ assert event_parameters["lines"][0]["line_pk"] == str(order_line.pk)+ assert event_parameters["lines"][0]["quantity"] == variant_qty++ # Ensure order discount object was properly created+ assert order.discounts.count() == 1+ order_discount = order.discounts.first()+ assert order_discount.voucher == voucher_percentage+ assert order_discount.type == DiscountType.VOUCHER+ assert order_discount.value_type == DiscountValueType.PERCENTAGE+ assert order_discount.value == voucher_listing.discount_value+ assert order_discount.amount_value == discount_amount++def test_draft_order_create_by_user_no_channel_access(staff_api_client,permission_group_all_perms_channel_USD_only,@@ -573,6 +695,366 @@ def test_draft_order_create_by_app(assert data["status"] == OrderStatus.DRAFT.upper()+def test_draft_order_create_with_voucher_including_drafts_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 = True+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher.apply_once_per_customer = True+ voucher.usage_limit = 10+ voucher.save(update_fields=["apply_once_per_customer", "usage_limit"])++ # Ensure no events were created yet+ assert not OrderEvent.objects.exists()++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ channel_listing = variant.channel_listings.get(channel=channel_USD)+ 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_listing = voucher.channel_listings.get(channel=channel_USD)+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.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,+ "voucher": voucher_id,+ "channelId": channel_id,+ "redirectUrl": redirect_url,+ }+ }+ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ assert not content["data"]["draftOrderCreate"]["errors"]+ data = content["data"]["draftOrderCreate"]["order"]+ assert data["status"] == OrderStatus.DRAFT.upper()+ assert data["voucher"]["code"] == voucher.code+ shipping_total = shipping_method.channel_listings.get(+ channel=channel_USD+ ).get_total()+ order_total = (+ channel_listing.discounted_price_amount * variant_qty + shipping_total.amount+ )+ assert data["undiscountedTotal"]["gross"]["amount"] == order_total+ assert (+ data["total"]["gross"]["amount"] == order_total - voucher_listing.discount_value+ )++ order = Order.objects.first()++ # Ensure order discount object was properly created+ assert order.discounts.count() == 1+ order_discount = order.discounts.first()+ assert order_discount.voucher == voucher+ assert order_discount.type == DiscountType.VOUCHER+ assert order_discount.value_type == DiscountValueType.FIXED+ assert order_discount.value == voucher_listing.discount_value+ assert order_discount.amount_value == voucher_listing.discount_value++ code = voucher.codes.first()+ assert code.used == 1++ assert not VoucherCustomer.objects.filter(voucher_code=code).exists()+++def test_draft_order_create_with_voucher_including_drafts_in_voucher_usage_invalid_code(+ 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 = True+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher.single_use = True+ voucher.save(update_fields=["single_use"])++ code = voucher.codes.first()+ code.is_active = False+ code.save(update_fields=["is_active"])++ # Ensure no events were created yet+ assert not OrderEvent.objects.exists()++ 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)+ redirect_url = "https://www.example.com"+ variables = {+ "input": {+ "user": user_id,+ "lines": variant_list,+ "billingAddress": shipping_address,+ "shippingAddress": shipping_address,+ "shippingMethod": shipping_id,+ "voucher": voucher_id,+ "channelId": channel_id,+ "redirectUrl": redirect_url,+ }+ }+ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ content = get_graphql_content(response)+ error = content["data"]["draftOrderCreate"]["errors"][0]+ assert error["code"] == OrderErrorCode.INVALID_VOUCHER.name+ assert error["field"] == "voucher"+++def test_draft_order_create_with_voucher_code_including_drafts_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 = True+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher.apply_once_per_customer = True+ voucher.usage_limit = 10+ voucher.save(update_fields=["apply_once_per_customer", "usage_limit"])++ code_instance = voucher.codes.first()++ # Ensure no events were created yet+ assert not OrderEvent.objects.exists()++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ channel_listing = variant.channel_listings.get(channel=channel_USD)+ 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_listing = voucher.channel_listings.get(channel=channel_USD)+ 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_instance.code,+ "channelId": channel_id,+ "redirectUrl": redirect_url,+ }+ }+ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ assert not content["data"]["draftOrderCreate"]["errors"]+ data = content["data"]["draftOrderCreate"]["order"]+ assert data["status"] == OrderStatus.DRAFT.upper()+ assert data["voucher"]["code"] == voucher.code+ shipping_total = shipping_method.channel_listings.get(+ channel=channel_USD+ ).get_total()+ order_total = (+ channel_listing.discounted_price_amount * variant_qty + shipping_total.amount+ )+ assert data["undiscountedTotal"]["gross"]["amount"] == order_total+ assert (+ data["total"]["gross"]["amount"] == order_total - voucher_listing.discount_value+ )++ order = Order.objects.first()++ # Ensure order discount object was properly created+ assert order.discounts.count() == 1+ order_discount = order.discounts.first()+ assert order_discount.voucher == voucher+ assert order_discount.type == DiscountType.VOUCHER+ assert order_discount.value_type == DiscountValueType.FIXED+ assert order_discount.value == voucher_listing.discount_value+ assert order_discount.amount_value == voucher_listing.discount_value++ code = voucher.codes.first()+ assert code.used == 1++ assert not VoucherCustomer.objects.filter(voucher_code=code).exists()+++def test_draft_order_create_voucher_code_including_drafts_in_voucher_usage_invalid_code(+ 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 = True+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher.single_use = True+ voucher.save(update_fields=["single_use"])++ code = voucher.codes.first()+ code.is_active = False+ code.save(update_fields=["is_active"])++ # Ensure no events were created yet+ assert not OrderEvent.objects.exists()++ 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.code,+ "channelId": channel_id,+ "redirectUrl": redirect_url,+ }+ }+ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ content = get_graphql_content(response)+ error = content["data"]["draftOrderCreate"]["errors"][0]+ assert error["code"] == OrderErrorCode.INVALID_VOUCHER_CODE.name+ assert error["field"] == "voucherCode"+++def test_draft_order_create_voucher_including_drafts_in_voucher_usage_invalid_code(+ 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 = True+ channel_USD.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher.single_use = True+ voucher.save(update_fields=["single_use"])+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)++ code = voucher.codes.first()+ code.is_active = False+ code.save(update_fields=["is_active"])++ # Ensure no events were created yet+ assert not OrderEvent.objects.exists()++ 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,+ "voucher": voucher_id,+ "channelId": channel_id,+ "redirectUrl": redirect_url,+ }+ }+ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ content = get_graphql_content(response)+ error = content["data"]["draftOrderCreate"]["errors"][0]+ assert error["code"] == OrderErrorCode.INVALID_VOUCHER.name+ assert error["field"] == "voucher"++def test_draft_order_create_with_same_variant_and_force_new_line(staff_api_client,permission_group_manage_orders,diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py b/saleor/graphql/order/tests/mutations/test_draft_order_delete.pyindex fc62c5ff77..491e217b0c 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_delete.py@@ -1,6 +1,7 @@import grapheneimport pytest+from .....discount.models import VoucherCodefrom .....order import OrderStatusfrom .....order.error_codes import OrderErrorCodefrom ....tests.utils import assert_no_permission, get_graphql_content@@ -209,3 +210,49 @@ def test_draft_order_delete_by_external_reference_not_existing(# thenerrors = content["data"]["draftOrderDelete"]["errors"]assert errors[0]["message"] == f"Couldn't resolve to a node: {ext_ref}"+++def test_draft_order_delete_release_voucher_codes_multiple_use(+ staff_api_client,+ permission_group_manage_orders,+ draft_order_list_with_multiple_use_voucher,+):+ # given+ 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]+ voucher_code = VoucherCode.objects.get(code=order.voucher_code)+ assert voucher_code.used == 1++ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}++ # when+ staff_api_client.post_graphql(query, variables)++ # then+ voucher_code.refresh_from_db()+ assert voucher_code.used == 0+++def test_draft_order_delete_release_voucher_codes_single_use(+ staff_api_client,+ permission_group_manage_orders,+ draft_order_list_with_single_use_voucher,+):+ # given+ 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]+ voucher_code = VoucherCode.objects.get(code=order.voucher_code)+ assert voucher_code.is_active is False++ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}++ # when+ staff_api_client.post_graphql(query, variables)++ # then+ voucher_code.refresh_from_db()+ assert voucher_code.is_active is Truediff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.pyindex a475bddf74..55a6f645ea 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py@@ -61,6 +61,16 @@ DRAFT_ORDER_UPDATE_MUTATION = """value}}+ total {+ gross {+ amount+ }+ }+ undiscountedTotal {+ gross {+ amount+ }+ }}}}@@ -119,7 +129,7 @@ def test_draft_order_update_voucher_not_available(assert error["field"] == "voucher"-def test_draft_order_update_with_voucher_code(+def test_draft_order_update_with_voucher(staff_api_client,permission_group_manage_orders,draft_order,@@ -133,14 +143,17 @@ def test_draft_order_update_with_voucher_code(assert not order.customer_notepermission_group_manage_orders.user_set.add(staff_api_client.user)query = DRAFT_ORDER_UPDATE_MUTATION- voucher = voucher.codes.first()order_id = graphene.Node.to_global_id("Order", order.id)+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)+ voucher_listing = voucher.channel_listings.get(channel=order.channel)customer_note = "Test customer note"external_reference = "test-ext-ref"+ order_total = order.total_net_amount+variables = {"id": order_id,"input": {- "voucherCode": voucher.code,+ "voucher": voucher_id,"customerNote": customer_note,"externalReference": external_reference,"shippingAddress": graphql_address_data,@@ -148,9 +161,13 @@ def test_draft_order_update_with_voucher_code(},}+ # whenresponse = staff_api_client.post_graphql(query, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["draftOrderUpdate"]+ assert data["order"]["voucher"]["code"] == voucher.codeassert data["order"]["voucherCode"] == voucher.codestored_metadata = {"public": "public_value"}@@ -160,6 +177,11 @@ def test_draft_order_update_with_voucher_code(assert (data["order"]["shippingAddress"]["metadata"] == graphql_address_data["metadata"])+ assert data["order"]["undiscountedTotal"]["net"]["amount"] == order_total+ assert (+ data["order"]["total"]["net"]["amount"]+ == order_total - voucher_listing.discount_value+ )assert not data["errors"]order.refresh_from_db()@@ -174,35 +196,48 @@ def test_draft_order_update_with_voucher_code(== order.external_reference)+ # Ensure order discount object was properly created+ assert order.discounts.count() == 1+ order_discount = order.discounts.first()+ assert order_discount.voucher == voucher+ assert order_discount.type == DiscountType.VOUCHER+ assert order_discount.value_type == DiscountValueType.FIXED+ assert order_discount.value == voucher_listing.discount_value+ assert order_discount.amount_value == voucher_listing.discount_value+-def test_draft_order_update_with_voucher(+def test_draft_order_update_clear_voucher(staff_api_client,permission_group_manage_orders,draft_order,voucher,- graphql_address_data,):+ # givenorder = draft_order- assert not order.voucher- assert not order.voucher_code- assert not order.customer_note+ order.voucher = voucher+ order.save(update_fields=["voucher"])++ voucher_listing = voucher.channel_listings.get(channel=order.channel)+ discount_amount = voucher_listing.discount_value+ order.discounts.create(+ voucher=voucher,+ value=discount_amount,+ type=DiscountType.VOUCHER,+ )++ order.total_gross_amount -= discount_amount+ order.total_net_amount -= discount_amount+ order.save(update_fields=["total_net_amount", "total_gross_amount"])+permission_group_manage_orders.user_set.add(staff_api_client.user)query = DRAFT_ORDER_UPDATE_MUTATIONorder_id = graphene.Node.to_global_id("Order", order.id)- voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)- voucher_listing = voucher.channel_listings.get(channel=order.channel)- customer_note = "Test customer note"- external_reference = "test-ext-ref"- order_total = order.total_net_amount+ order_total = order.undiscounted_total_net_amountvariables = {"id": order_id,"input": {- "voucher": voucher_id,- "customerNote": customer_note,- "externalReference": external_reference,- "shippingAddress": graphql_address_data,- "billingAddress": graphql_address_data,+ "voucher": None,},}@@ -212,51 +247,23 @@ def test_draft_order_update_with_voucher(# thencontent = get_graphql_content(response)data = content["data"]["draftOrderUpdate"]- assert data["order"]["voucher"]["code"] == voucher.code- assert data["order"]["voucherCode"] == voucher.code- stored_metadata = {"public": "public_value"}- assert (- data["order"]["billingAddress"]["metadata"] == graphql_address_data["metadata"]- )- assert (- data["order"]["shippingAddress"]["metadata"] == graphql_address_data["metadata"]- )assert data["order"]["undiscountedTotal"]["net"]["amount"] == order_total- assert (- data["order"]["total"]["net"]["amount"]- == order_total - voucher_listing.discount_value- )+ assert data["order"]["total"]["net"]["amount"] == order_totalassert not data["errors"]order.refresh_from_db()- assert order.billing_address.metadata == stored_metadata- assert order.shipping_address.metadata == stored_metadata- assert order.voucher_code == voucher.code- assert order.customer_note == customer_note+ assert not order.voucherassert order.search_vector- assert (- data["order"]["externalReference"]- == external_reference- == order.external_reference- )- # Ensure order discount object was properly created- assert order.discounts.count() == 1- order_discount = order.discounts.first()- assert order_discount.voucher == voucher- assert order_discount.type == DiscountType.VOUCHER- assert order_discount.value_type == DiscountValueType.FIXED- assert order_discount.value == voucher_listing.discount_value- assert order_discount.amount_value == voucher_listing.discount_value+ assert not order.discounts.count()-def test_draft_order_update_clear_voucher(+def test_draft_order_update_clear_voucher_code(staff_api_client,permission_group_manage_orders,draft_order,voucher,- graphql_address_data,):# givenorder = draft_order@@ -283,7 +290,7 @@ def test_draft_order_update_clear_voucher(variables = {"id": order_id,"input": {- "voucher": None,+ "voucherCode": None,},}@@ -346,6 +353,178 @@ def test_draft_order_update_with_voucher_and_voucher_code()+def test_draft_order_update_with_voucher_including_drafts_in_voucher_usage(+ staff_api_client,+ permission_group_manage_orders,+ draft_order,+ voucher,+):+ # given+ order = draft_order+ assert not order.voucher+ assert not order.voucher_code+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ 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)+ voucher_listing = voucher.channel_listings.get(channel=order.channel)+ order_total = order.total_net_amount++ channel = order.channel+ channel.include_draft_order_in_voucher_usage = True+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher.single_use = True+ voucher.save(update_fields=["single_use"])++ variables = {+ "id": order_id,+ "input": {+ "voucher": voucher_id,+ },+ }++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["draftOrderUpdate"]+ assert data["order"]["voucher"]["code"] == voucher.code+ assert data["order"]["voucherCode"] == voucher.code+ assert data["order"]["undiscountedTotal"]["net"]["amount"] == order_total+ assert (+ data["order"]["total"]["net"]["amount"]+ == order_total - voucher_listing.discount_value+ )++ assert not data["errors"]+ order.refresh_from_db()+ assert order.voucher_code == voucher.code+ assert order.search_vector++ # Ensure order discount object was properly created+ assert order.discounts.count() == 1+ order_discount = order.discounts.first()+ assert order_discount.voucher == voucher+ assert order_discount.type == DiscountType.VOUCHER+ assert order_discount.value_type == DiscountValueType.FIXED+ assert order_discount.value == voucher_listing.discount_value+ assert order_discount.amount_value == voucher_listing.discount_value++ code_instance = voucher.codes.first()+ assert code_instance.is_active is False+++def test_draft_order_update_with_voucher_code_including_drafts_in_voucher_usage(+ staff_api_client,+ permission_group_manage_orders,+ draft_order,+ voucher,+):+ # given+ order = draft_order+ assert not order.voucher+ assert not order.voucher_code+ assert not order.customer_note+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ query = DRAFT_ORDER_UPDATE_MUTATION+ order_id = graphene.Node.to_global_id("Order", order.id)+ voucher_listing = voucher.channel_listings.get(channel=order.channel)+ order_total = order.total_net_amount++ channel = order.channel+ channel.include_draft_order_in_voucher_usage = True+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher.single_use = True+ voucher.save(update_fields=["single_use"])++ code_instance = voucher.codes.first()++ variables = {+ "id": order_id,+ "input": {+ "voucherCode": code_instance.code,+ },+ }++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["draftOrderUpdate"]+ assert data["order"]["voucher"]["code"] == voucher.code+ assert data["order"]["voucherCode"] == voucher.code+ assert data["order"]["undiscountedTotal"]["net"]["amount"] == order_total+ assert (+ data["order"]["total"]["net"]["amount"]+ == order_total - voucher_listing.discount_value+ )++ assert not data["errors"]+ order.refresh_from_db()+ assert order.voucher_code == voucher.code+ assert order.search_vector++ # Ensure order discount object was properly created+ assert order.discounts.count() == 1+ order_discount = order.discounts.first()+ assert order_discount.voucher == voucher+ assert order_discount.type == DiscountType.VOUCHER+ assert order_discount.value_type == DiscountValueType.FIXED+ assert order_discount.value == voucher_listing.discount_value+ assert order_discount.amount_value == voucher_listing.discount_value++ code_instance.refresh_from_db()+ assert code_instance.is_active is False+++def test_draft_order_update_voucher_including_drafts_in_voucher_usage_invalid_code(+ staff_api_client, permission_group_manage_orders, order_with_lines, voucher+):+ # given+ order = order_with_lines+ order.status = OrderStatus.DRAFT+ order.save()+ assert order.voucher is None+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ channel = order.channel+ channel.include_draft_order_in_voucher_usage = True+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])++ voucher.single_use = True+ voucher.save(update_fields=["single_use"])++ 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)+ error = content["data"]["draftOrderUpdate"]["errors"][0]++ assert error["code"] == OrderErrorCode.INVALID_VOUCHER.name+ assert error["field"] == "voucher"++def test_draft_order_update_with_non_draft_order(staff_api_client, permission_group_manage_orders, order_with_lines, voucher):diff --git a/saleor/graphql/order/tests/queries/test_order_can_finalize.py b/saleor/graphql/order/tests/queries/test_order_can_finalize.pyindex 56bd702780..98e4c245a0 100644--- a/saleor/graphql/order/tests/queries/test_order_can_finalize.py+++ b/saleor/graphql/order/tests/queries/test_order_can_finalize.py@@ -166,3 +166,25 @@ def test_can_finalize_order_product_available_for_purchase_from_tomorrow(assert errors[0]["code"] == OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.nameassert errors[0]["field"] == "lines"assert errors[0]["orderLines"] == [graphene.Node.to_global_id("OrderLine", line.pk)]+++def test_can_finalize_order_invalid_voucher(+ staff_api_client, permission_manage_orders, draft_order_with_voucher+):+ # given+ order = draft_order_with_voucher+ order.voucher.channel_listings.all().delete()+ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}+ staff_api_client.user.user_permissions.add(permission_manage_orders)++ # when+ response = staff_api_client.post_graphql(ORDER_CAN_FINALIZE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["order"]["canFinalize"] is False+ errors = content["data"]["order"]["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == OrderErrorCode.INVALID_VOUCHER.name+ assert errors[0]["field"] == "voucher"diff --git a/saleor/graphql/order/tests/test_draft_order_validate.py b/saleor/graphql/order/tests/test_draft_order_validate.pyindex 7e662fbd7c..b1d76d2b3c 100644--- a/saleor/graphql/order/tests/test_draft_order_validate.py+++ b/saleor/graphql/order/tests/test_draft_order_validate.py@@ -178,3 +178,16 @@ def test_validate_draft_order_no_shipping_address_no_method_shipping_not_requireorder.is_shipping_required = required_mockassert validate_draft_order(order, "US", get_plugins_manager()) is None+++def test_validate_draft_order_voucher(draft_order_with_voucher):+ # given+ order = draft_order_with_voucher+ order.voucher.channel_listings.all().delete()++ # when & then+ with pytest.raises(ValidationError) as e:+ validate_draft_order(order, "US", get_plugins_manager())++ error = e.value.error_dict["voucher"][0]+ assert error.code == OrderErrorCode.INVALID_VOUCHER.valuediff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.pyindex 0e8095f468..91cb2a9bf2 100644--- a/saleor/graphql/order/utils.py+++ b/saleor/graphql/order/utils.py@@ -8,6 +8,8 @@ from django.core.exceptions import ValidationErrorfrom ...core.exceptions import InsufficientStockfrom ...discount.interface import VariantPromotionRuleInfo+from ...discount.models import NotApplicable+from ...discount.utils import validate_voucher_in_orderfrom ...order.error_codes import OrderErrorCodefrom ...order.utils import get_valid_shipping_methods_for_orderfrom ...plugins.manager import PluginsManager@@ -269,6 +271,19 @@ def validate_channel_is_active(channel: "Channel", errors: T_ERRORS):)+def _validate_voucher(order: "Order", errors: T_ERRORS):+ if order.channel.include_draft_order_in_voucher_usage:+ try:+ validate_voucher_in_order(order)+ except NotApplicable as e:+ errors["voucher"].append(+ ValidationError(+ message=e.args[0],+ code=OrderErrorCode.INVALID_VOUCHER.value,+ )+ )++def validate_draft_order(order: "Order", country: str, manager: "PluginsManager"):"""Check if the given order contains the proper data.@@ -277,6 +292,7 @@ def validate_draft_order(order: "Order", country: str, manager: "PluginsManager"- Product variants for order lines still exists in database.- Product variants are available in requested quantity.- Product variants are published.+ - Voucher is properly applied.Returns a list of errors if any were found."""@@ -291,6 +307,8 @@ def validate_draft_order(order: "Order", country: str, manager: "PluginsManager"validate_product_is_published(order, errors)validate_product_is_available_for_purchase(order, errors)validate_variants_is_available(order, errors)+ _validate_voucher(order, errors)+if errors:raise ValidationError(errors)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 00f542eaa1..2586c65ffc 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -5598,6 +5598,15 @@ type OrderSettings {Note: this API is currently in Feature Preview and can be subject to changes at later point."""allowUnpaidOrders: Boolean!++ """+ Determine if voucher applied on draft order should be count toward voucher usage.++ Added in Saleor 3.18.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ includeDraftOrderInVoucherUsage: Boolean!}"""@@ -29147,6 +29156,17 @@ input OrderSettingsInput @doc(category: "Orders") {Note: this API is currently in Feature Preview and can be subject to changes at later point."""allowUnpaidOrders: Boolean++ """+ Specify whether a coupon applied to draft orders will count toward voucher usage.++ Warning: when switching this setting from `false` to `true`, the vouchers will be disconnected from all draft orders.++ Added in Saleor 3.18.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ includeDraftOrderInVoucherUsage: Boolean}input CheckoutSettingsInput @doc(category: "Checkout") {diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 76efcd7a16..8bf8ed35dc 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -774,7 +774,11 @@ def get_order_discounts(order: Order) -> list[OrderDiscount]:def create_order_discount_for_order(- order: Order, reason: str, value_type: str, value: Decimal+ order: Order,+ reason: str,+ value_type: str,+ value: Decimal,+ type: Optional[str] = None,):"""Add new order discount and update the prices."""@@ -786,12 +790,14 @@ def create_order_discount_for_order()new_amount = quantize_price((current_total - gross_total).gross, currency)+ kwargs = {} if not type else {"type": type}order_discount = order.discounts.create(value_type=value_type,value=value,reason=reason,amount=new_amount, # type: ignore+ **kwargs,)return order_discountdiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 8b75a2b1b0..e2163faf81 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -4005,6 +4005,49 @@ def voucher_customer(voucher, customer_user):return VoucherCustomer.objects.create(voucher_code=code, customer_email=email)+def voucher_multiple_use(voucher_with_many_codes):+ voucher = voucher_with_many_codes+ voucher.usage_limit = 3+ voucher.save(update_fields=["usage_limit"])+ codes = voucher.codes.all()+ for code in codes:+ code.used = 1+ VoucherCode.objects.bulk_update(codes, ["used"])+ voucher.refresh_from_db()+ return voucher+++def voucher_single_use(voucher_with_many_codes):+ voucher = voucher_with_many_codes+ voucher.single_use = True+ voucher.save(update_fields=["single_use"])+ return voucher+++def draft_order_list_with_multiple_use_voucher(draft_order_list, voucher_multiple_use):+ codes = voucher_multiple_use.codes.values_list("code", flat=True)+ for idx, order in enumerate(draft_order_list):+ order.voucher_code = codes[idx]+ Order.objects.bulk_update(draft_order_list, ["voucher_code"])+ return draft_order_list+++def draft_order_list_with_single_use_voucher(draft_order_list, voucher_single_use):+ voucher_codes = voucher_single_use.codes.all()+ codes = voucher_codes.values_list("code", flat=True)+ for idx, order in enumerate(draft_order_list):+ order.voucher_code = codes[idx]+ for voucher_code in voucher_codes:+ voucher_code.is_active = False+ Order.objects.bulk_update(draft_order_list, ["voucher_code"])+ VoucherCode.objects.bulk_update(voucher_codes, ["is_active"])+ return draft_order_list++@pytest.fixturedef order_line(order, variant):product = variant.product@@ -4672,8 +4715,6 @@ def order_with_lines(order.shipping_price = TaxedMoney(net=net, gross=gross)order.base_shipping_price = netorder.shipping_tax_rate = calculate_tax_rate(order.shipping_price)- order.total += order.shipping_price- order.undiscounted_total += order.shipping_priceorder.save()recalculate_order(order)@@ -5220,6 +5261,29 @@ def draft_order_with_fixed_discount_order(draft_order):return draft_order+def draft_order_with_voucher(+ draft_order_with_fixed_discount_order, voucher_multiple_use+):+ order = draft_order_with_fixed_discount_order+ voucher_code = voucher_multiple_use.codes.first()+ discount = order.discounts.first()+ discount.type = DiscountType.VOUCHER+ discount.voucher = voucher_multiple_use+ discount.voucher_code = voucher_code.code+ discount.save(update_fields=["type", "voucher", "voucher_code"])++ order.voucher = voucher_multiple_use+ order.voucher_code = voucher_code.code+ order.save(update_fields=["voucher", "voucher_code"])++ channel = order.channel+ channel.include_draft_order_in_voucher_usage = True+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])++ return order++@pytest.fixturedef draft_order_without_inventory_tracking(order_with_line_without_inventory_tracking):order_with_line_without_inventory_tracking.status = OrderStatus.DRAFT