Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor `discount/utils.py` (#16239)
Iga Karbowiaka4621623f618
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.pyindex 34e2c2c39a..36cf051979 100644--- a/saleor/checkout/base_calculations.py+++ b/saleor/checkout/base_calculations.py@@ -48,7 +48,7 @@ def calculate_base_line_total_price(The price does not include order promotions and the entire order vouchers.When the line is gift reward, the price is zero."""- from ..discount.utils import calculate_line_discount_amount_from_voucher+ from ..discount.utils.voucher import calculate_line_discount_amount_from_vouchervariant = line_info.variantvariant_price = variant.get_base_price(@@ -212,7 +212,7 @@ def checkout_total(It should be used as a based value when no flat rate/tax plugin/tax app is active."""- from ..discount.utils import is_order_level_voucher+ from ..discount.utils.voucher import is_order_level_vouchercurrency = checkout_info.checkout.currencysubtotal = base_checkout_subtotal(lines, checkout_info.channel, currency)diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex f541aa78cd..6079810082 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -11,7 +11,7 @@ from ..checkout import base_calculationsfrom ..core.db.connection import allow_writerfrom ..core.prices import quantize_pricefrom ..core.taxes import TaxData, TaxEmptyData, zero_money, zero_taxed_money-from ..discount.utils import (+from ..discount.utils.checkout import (create_or_update_discount_objects_from_promotion_for_checkout,)from ..payment.models import TransactionItemdiff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex c97a82df54..756e961762 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -27,8 +27,8 @@ from ..core.transactions import transaction_with_commit_on_errorsfrom ..core.utils.url import validate_storefront_urlfrom ..discount import DiscountType, DiscountValueTypefrom ..discount.models import CheckoutDiscount, NotApplicable, OrderLineDiscount-from ..discount.utils import (- get_sale_id,+from ..discount.utils.promotion import get_sale_id+from ..discount.utils.voucher import (increase_voucher_usage,release_voucher_code_usage,)diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex b40453a8b5..1bfce4f52a 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -295,7 +295,7 @@ def fetch_checkout_lines(database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,) -> tuple[Iterable[CheckoutLineInfo], Iterable[int]]:"""Fetch checkout lines as CheckoutLineInfo objects."""- from ..discount.utils import apply_voucher_to_line+ from ..discount.utils.voucher import apply_voucher_to_linefrom .utils import get_voucher_for_checkoutselect_related_fields = ["variant__product__product_type__tax_class"]diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex b3236ce7a5..17aa4f983a 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -643,7 +643,7 @@ def test_get_discount_for_checkout_value_specific_product_voucher(assert discount == Money(expected_value, "USD")-@patch("saleor.discount.utils.validate_voucher")+@patch("saleor.discount.utils.voucher.validate_voucher")def test_get_voucher_discount_for_checkout_voucher_validation(mock_validate_voucher, voucher, checkout_with_voucher):diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 0b35eecc1c..4e3720fa2d 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -32,10 +32,14 @@ from ..discount.models import (Voucher,VoucherCode,)-from ..discount.utils import (+from ..discount.utils.checkout import (create_checkout_discount_objects_for_order_promotions,create_checkout_line_discount_objects_for_catalogue_promotions,+)+from ..discount.utils.promotion import (delete_gift_line,+)+from ..discount.utils.voucher import (get_discounted_lines,get_products_voucher_discount,get_voucher_code_instance,diff --git a/saleor/core/pricing/interface.py b/saleor/core/pricing/interface.pyindex d4e6925f46..3718e01d38 100644--- a/saleor/core/pricing/interface.py+++ b/saleor/core/pricing/interface.py@@ -13,6 +13,7 @@ if TYPE_CHECKING:from ...product.models import (Collection,Product,+ ProductType,ProductVariant,ProductVariantChannelListing,)@@ -23,6 +24,7 @@ class LineInfo:line: Union["OrderLine", "CheckoutLine"]variant: Optional["ProductVariant"]product: Optional["Product"]+ product_type: Optional["ProductType"]collections: list["Collection"]channel_listing: "ProductVariantChannelListing"channel: "Channel"diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.pyindex 9aa2771ce0..41cef0b09a 100644--- a/saleor/discount/tasks.py+++ b/saleor/discount/tasks.py@@ -31,7 +31,7 @@ from .models import (PromotionRule,VoucherCode,)-from .utils import mark_catalogue_promotion_rules_as_dirty+from .utils.promotion import mark_catalogue_promotion_rules_as_dirtyif TYPE_CHECKING:from uuid import UUIDdiff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.pyindex 38c9f88c2f..969196b50c 100644--- a/saleor/discount/tests/test_discounts.py+++ b/saleor/discount/tests/test_discounts.py@@ -16,14 +16,16 @@ from ..models import (VoucherCode,VoucherCustomer,)-from ..utils import (+from ..utils.promotion import (+ get_discount_name,+ get_discount_translated_name,+)+from ..utils.voucher import (_get_the_cheapest_line,activate_voucher_code,add_voucher_usage_by_customer,deactivate_voucher_code,decrease_voucher_code_usage_value,- get_discount_name,- get_discount_translated_name,increase_voucher_code_usage_value,is_order_level_voucher,remove_voucher_usage_by_customer,diff --git a/saleor/discount/tests/test_rounding_issue.py b/saleor/discount/tests/test_rounding_issue.pyindex 247cbd3d2b..8908a29a74 100644--- a/saleor/discount/tests/test_rounding_issue.py+++ b/saleor/discount/tests/test_rounding_issue.py@@ -12,7 +12,9 @@ from ...product.utils.variant_prices import update_discounted_prices_for_promotifrom ...product.utils.variants import fetch_variants_for_promotion_rulesfrom .. import DiscountValueType, RewardValueTypefrom ..models import Promotion-from ..utils import create_or_update_discount_objects_from_promotion_for_checkout+from ..utils.checkout import (+ create_or_update_discount_objects_from_promotion_for_checkout,+)@pytest.fixturediff --git a/saleor/discount/tests/test_tasks.py b/saleor/discount/tests/test_tasks.pyindex 5232c95cef..9173e1beb5 100644--- a/saleor/discount/tests/test_tasks.py+++ b/saleor/discount/tests/test_tasks.py@@ -20,7 +20,7 @@ from ..tasks import (handle_promotion_toggle,set_promotion_rule_variants_task,)-from ..utils import mark_catalogue_promotion_rules_as_dirty+from ..utils.promotion import mark_catalogue_promotion_rules_as_dirtydef test_fetch_promotion_variants_and_product_ids(diff --git a/saleor/discount/tests/test_utils/test_calculate_discounted_price_for_promotions.py b/saleor/discount/tests/test_utils/test_calculate_discounted_price_for_promotions.pyindex 8213a4be53..6e4f01621a 100644--- a/saleor/discount/tests/test_utils/test_calculate_discounted_price_for_promotions.py+++ b/saleor/discount/tests/test_utils/test_calculate_discounted_price_for_promotions.py@@ -4,7 +4,7 @@ import graphenefrom ... import PromotionRuleInfo, RewardValueTypefrom ...models import Promotion, PromotionRule-from ...utils import calculate_discounted_price_for_promotions+from ...utils.promotion import calculate_discounted_price_for_promotionsdef test_variant_discounts_multiple_promotions(product, channel_USD):diff --git a/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py b/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.pyindex f014bc4ff8..3e44daf08b 100644--- a/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py+++ b/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py@@ -5,7 +5,7 @@ import graphenefrom ....order.fetch import fetch_draft_order_lines_infofrom ... import DiscountType, DiscountValueTypefrom ...models import PromotionRule-from ...utils import _copy_unit_discount_data_to_order_line+from ...utils.order import _copy_unit_discount_data_to_order_linedef test_copy_unit_discount_data_to_order_line_multiple_discounts(diff --git a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.pyindex 2e5b940ab3..61f03c271c 100644--- a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py+++ b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py@@ -20,12 +20,14 @@ from ....product.models import ()from ... import DiscountType, RewardType, RewardValueTypefrom ...models import CheckoutDiscount, CheckoutLineDiscount, PromotionRule-from ...utils import (- _get_best_gift_reward,+from ...utils.checkout import (create_checkout_discount_objects_for_order_promotions,create_checkout_line_discount_objects_for_catalogue_promotions,create_or_update_discount_objects_from_promotion_for_checkout,)+from ...utils.promotion import (+ _get_best_gift_reward,+)def test_create_or_update_discount_objects_from_promotion_for_checkout_no_discount(@@ -1301,8 +1303,8 @@ def test_create_or_update_discount_objects_from_promotion_for_checkout_voucher_sassert not checkout_info.checkout.discounts.all()-@patch("saleor.discount.utils.base_checkout_delivery_price")-@patch("saleor.discount.utils.base_checkout_subtotal")+@patch("saleor.discount.utils.checkout.base_checkout_delivery_price")+@patch("saleor.discount.utils.checkout.base_checkout_subtotal")def test_create_or_update_discount_objects_from_promotion_no_applicable_rules(base_checkout_subtotal_mock,base_checkout_delivery_price_mock,@@ -1399,8 +1401,8 @@ def test_create_or_update_discount_objects_from_promotion(assert checkout_info.discounts[0].promotion_rule == rules[1]-@patch("saleor.discount.utils.base_checkout_delivery_price")-@patch("saleor.discount.utils.base_checkout_subtotal")+@patch("saleor.discount.utils.checkout.base_checkout_delivery_price")+@patch("saleor.discount.utils.checkout.base_checkout_subtotal")def test_create_or_update_discount_objects_from_promotion_best_rule_applies(subtotal_mock,delivery_price_mock,@@ -1505,8 +1507,8 @@ def test_create_or_update_discount_objects_from_promotion_best_rule_applies(assert discount.reason == f"Promotion: {promotion_id}"-@patch("saleor.discount.utils.base_checkout_delivery_price")-@patch("saleor.discount.utils.base_checkout_subtotal")+@patch("saleor.discount.utils.checkout.base_checkout_delivery_price")+@patch("saleor.discount.utils.checkout.base_checkout_subtotal")def test_create_or_update_discount_objects_from_promotion_subtotal_price_discount(subtotal_mock,delivery_price_mock,@@ -1667,8 +1669,8 @@ def test_update_gift_discount(assert lines_info[-1].discounts == [discount]-@patch("saleor.discount.utils.base_checkout_delivery_price")-@patch("saleor.discount.utils.base_checkout_subtotal")+@patch("saleor.discount.utils.checkout.base_checkout_delivery_price")+@patch("saleor.discount.utils.checkout.base_checkout_subtotal")def test_create_or_update_discount_objects_from_promotion_gift_rule_applies(subtotal_mock,delivery_price_mock,@@ -1775,8 +1777,8 @@ def test_create_or_update_discount_objects_from_promotion_gift_rule_applies(assert discount.reason == f"Promotion: {promotion_id}"-@patch("saleor.discount.utils.base_checkout_delivery_price")-@patch("saleor.discount.utils.base_checkout_subtotal")+@patch("saleor.discount.utils.checkout.base_checkout_delivery_price")+@patch("saleor.discount.utils.checkout.base_checkout_subtotal")def test_create_or_update_discount_objects_from_promotion_gift_line_removed(subtotal_mock,delivery_price_mock,@@ -2110,7 +2112,7 @@ def test_create_discount_objects_for_order_promotions_race_condition()with before_after.before(- "saleor.discount.utils.create_checkout_discount_objects_for_order_promotions",+ "saleor.discount.utils.checkout.create_checkout_discount_objects_for_order_promotions",call_before_creating_discount_object,):create_checkout_discount_objects_for_order_promotions(@@ -2155,7 +2157,7 @@ def test_create_or_update_order_discount_race_condition()with before_after.before(- "saleor.discount.utils._set_checkout_base_prices", call_update+ "saleor.discount.utils.checkout._set_checkout_base_prices", call_update):call_update()@@ -2180,7 +2182,7 @@ def test_create_or_update_order_discount_gift_reward_race_condition()with before_after.before(- "saleor.discount.utils._set_checkout_base_prices", call_update+ "saleor.discount.utils.checkout._set_checkout_base_prices", call_update):call_update()@@ -2301,7 +2303,7 @@ def test_create_checkout_line_discount_objects_for_catalogue_promotions_race_concreate_checkout_line_discount_objects_for_catalogue_promotions(lines_info)with before_after.before(- "saleor.discount.utils.prepare_line_discount_objects_for_catalogue_promotions",+ "saleor.discount.utils.promotion.prepare_line_discount_objects_for_catalogue_promotions",call_before_creating_catalogue_line_discount,):lines_info, _ = fetch_checkout_lines(checkout)diff --git a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.pyindex 6523652ac3..bd0938c6db 100644--- a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py+++ b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py@@ -10,7 +10,7 @@ from ....product.models import (from ....warehouse.models import Stockfrom ... import DiscountType, RewardType, RewardValueTypefrom ...models import OrderDiscount, OrderLineDiscount-from ...utils import create_or_update_discount_objects_from_promotion_for_order+from ...utils.order import create_or_update_discount_objects_from_promotion_for_orderdef test_create_catalogue_discount_fixed(diff --git a/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.pyindex 0dbcfaf3e7..83fd9bd1b1 100644--- a/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py+++ b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py@@ -2,7 +2,7 @@ from decimal import Decimalfrom ... import RewardType, RewardValueTypefrom ...models import PromotionRule-from ...utils import fetch_promotion_rules_for_checkout_or_order+from ...utils.promotion import fetch_promotion_rules_for_checkout_or_orderdef test_fetch_promotion_rules_for_checkout(diff --git a/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_order.py b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_order.pyindex 9d65cced02..bc709522cf 100644--- a/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_order.py+++ b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_order.py@@ -2,7 +2,7 @@ from decimal import Decimalfrom ... import RewardType, RewardValueTypefrom ...models import PromotionRule-from ...utils import fetch_promotion_rules_for_checkout_or_order+from ...utils.promotion import fetch_promotion_rules_for_checkout_or_orderdef test_fetch_promotion_rules_for_order(order, order_line_JPY, order_promotion_rule):diff --git a/saleor/discount/tests/test_utils/test_get_variants_to_promotions_map.py b/saleor/discount/tests/test_utils/test_get_variants_to_promotions_map.pyindex 1a2394374d..330853ea95 100644--- a/saleor/discount/tests/test_utils/test_get_variants_to_promotions_map.py+++ b/saleor/discount/tests/test_utils/test_get_variants_to_promotions_map.py@@ -6,7 +6,7 @@ from ....product.models import ProductVariantfrom ....product.utils.variants import fetch_variants_for_promotion_rulesfrom ... import PromotionRuleInfo, RewardValueTypefrom ...models import Promotion, PromotionRule-from ...utils import get_variants_to_promotion_rules_map+from ...utils.promotion import get_variants_to_promotion_rules_mapdef test_get_variants_to_promotions_map(diff --git a/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py b/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.pyindex 8c4a6a445d..6bd69eed4f 100644--- a/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py+++ b/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py@@ -7,10 +7,10 @@ import pytzfrom ... import RewardValueTypefrom ...models import Promotion, PromotionRule-from ...utils import mark_active_catalogue_promotion_rules_as_dirty+from ...utils.promotion import mark_active_catalogue_promotion_rules_as_dirty-@patch("saleor.discount.utils.PromotionRule.channels.through.objects.filter")+@patch("saleor.discount.utils.promotion.PromotionRule.channels.through.objects.filter")def test_mark_active_catalogue_promotion_rules_as_dirty_with_empty_channel_list(mocked_promotion_channel_filter,):diff --git a/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py b/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.pyindex ef581fbb5a..3ba1e386b0 100644--- a/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py+++ b/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py@@ -7,10 +7,10 @@ import pytzfrom ... import RewardValueTypefrom ...models import Promotion, PromotionRule-from ...utils import mark_catalogue_promotion_rules_as_dirty+from ...utils.promotion import mark_catalogue_promotion_rules_as_dirty-@patch("saleor.discount.utils.PromotionRule.objects.filter")+@patch("saleor.discount.utils.promotion.PromotionRule.objects.filter")def test_mark_catalogue_promotion_rules_as_dirty_with_empty_list_as_input(mocked_promotion_rule_filter,):diff --git a/saleor/discount/tests/test_utils/test_update_rule_variant_relation.py b/saleor/discount/tests/test_utils/test_update_rule_variant_relation.pyindex e672d876fe..3d41f38581 100644--- a/saleor/discount/tests/test_utils/test_update_rule_variant_relation.py+++ b/saleor/discount/tests/test_utils/test_update_rule_variant_relation.py@@ -4,7 +4,7 @@ import graphenefrom ... import RewardValueTypefrom ...models import PromotionRule-from ...utils import update_rule_variant_relation+from ...utils.promotion import update_rule_variant_relationdef test_update_rule_variant_relation(diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pydeleted file mode 100644index 66d9081f3b..0000000000--- a/saleor/discount/utils.py+++ /dev/null@@ -1,1969 +0,0 @@-import datetime-from collections import defaultdict, namedtuple-from collections.abc import Iterable, Iterator-from decimal import ROUND_HALF_UP, Decimal-from functools import partial-from typing import TYPE_CHECKING, Callable, Optional, Union, cast, overload-from uuid import UUID--import graphene-import pytz-from django.conf import settings-from django.db import transaction-from django.db.models import Exists, F, OuterRef, QuerySet-from django.utils import timezone-from prices import Money, TaxedMoney, fixed_discount, percentage_discount--from ..channel.models import Channel-from ..checkout.base_calculations import (- base_checkout_delivery_price,- base_checkout_subtotal,-)-from ..checkout.models import Checkout, CheckoutLine-from ..core.db.connection import allow_writer-from ..core.exceptions import InsufficientStock-from ..core.taxes import zero_money-from ..core.utils.promo_code import InvalidPromoCode-from ..order.models import Order, OrderLine-from ..product.models import (- Product,- ProductChannelListing,- ProductVariant,- ProductVariantChannelListing,-)-from . import (- DiscountType,- PromotionRuleInfo,- PromotionType,- RewardType,- RewardValueType,- VoucherType,-)-from .interface import VariantPromotionRuleInfo, get_rule_translations-from .models import (- CheckoutDiscount,- CheckoutLineDiscount,- DiscountValueType,- NotApplicable,- OrderDiscount,- OrderLineDiscount,- Promotion,- PromotionRule,- Voucher,- VoucherCode,- VoucherCustomer,-)--if TYPE_CHECKING:- from ..account.models import User- from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo- from ..core.pricing.interface import LineInfo- from ..discount.models import Voucher- from ..order.fetch import EditableOrderLineInfo- from ..order.models import OrderLine- from ..plugins.manager import PluginsManager- from ..product.managers import ProductVariantQueryset- from .interface import VoucherInfo--CatalogueInfo = defaultdict[str, set[Union[int, str]]]-CATALOGUE_FIELDS = ["categories", "collections", "products", "variants"]---def is_order_level_voucher(voucher: Optional[Voucher]):- return bool(- voucher- and voucher.type == VoucherType.ENTIRE_ORDER- and not voucher.apply_once_per_order- )---def increase_voucher_usage(- voucher: "Voucher",- code: "VoucherCode",- customer_email: Optional[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") + 1- code.save(update_fields=["used"])---def decrease_voucher_code_usage_value(code: "VoucherCode") -> None:- """Decrease voucher code uses by 1."""- code.used = F("used") - 1- code.save(update_fields=["used"])---def deactivate_voucher_code(code: "VoucherCode") -> None:- """Mark voucher code as used."""- code.is_active = False- code.save(update_fields=["is_active"])---def activate_voucher_code(code: "VoucherCode") -> None:- """Mark voucher code as unused."""- code.is_active = True- code.save(update_fields=["is_active"])---def add_voucher_usage_by_customer(- code: "VoucherCode", customer_email: Optional[str]-) -> None:- if not customer_email:- raise NotApplicable("Unable to apply voucher as customer details are missing.")-- _, created = VoucherCustomer.objects.get_or_create(- voucher_code=code, customer_email=customer_email- )- if not created:- raise NotApplicable("This offer is only valid once per customer.")---def remove_voucher_usage_by_customer(code: "VoucherCode", customer_email: str) -> None:- voucher_customer = VoucherCustomer.objects.filter(- voucher_code=code, customer_email=customer_email- )- if voucher_customer:- voucher_customer.delete()---def release_voucher_code_usage(- code: Optional["VoucherCode"],- voucher: Optional["Voucher"],- user_email: Optional[str],-):- if not code:- return- if voucher and voucher.usage_limit:- decrease_voucher_code_usage_value(code)- if voucher and voucher.single_use:- activate_voucher_code(code)- if user_email:- remove_voucher_usage_by_customer(code, user_email)---def prepare_promotion_discount_reason(promotion: "Promotion", sale_id: str):- return f"{'Sale' if promotion.old_sale_id else 'Promotion'}: {sale_id}"---def get_sale_id(promotion: "Promotion"):- return (- graphene.Node.to_global_id("Sale", promotion.old_sale_id)- if promotion.old_sale_id- else graphene.Node.to_global_id("Promotion", promotion.id)- )---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 get_active_voucher_code(voucher, channel_slug):- """Return an active VoucherCode instance.-- This method along with `Voucher.code` should be removed in Saleor 4.0.- """-- voucher_queryset = Voucher.objects.active_in_channel(timezone.now(), channel_slug)- if not voucher_queryset.filter(pk=voucher.pk).exists():- raise InvalidPromoCode()- voucher_code = VoucherCode.objects.filter(voucher=voucher, is_active=True).first()- if not voucher_code:- raise InvalidPromoCode()- return voucher_code---def apply_voucher_to_line(- voucher_info: "VoucherInfo",- lines_info: Iterable["LineInfo"],-):- """Attach voucher to valid checkout or order lines info.-- Apply a voucher to checkout/order line info when the voucher has the type- SPECIFIC_PRODUCTS or is applied only to the cheapest item.- """- voucher = voucher_info.voucher- discounted_lines_by_voucher: list[LineInfo] = []- lines_included_in_discount = lines_info- if voucher.type == VoucherType.SPECIFIC_PRODUCT:- discounted_lines_by_voucher.extend(- get_discounted_lines(lines_info, voucher_info)- )- lines_included_in_discount = discounted_lines_by_voucher- if voucher.apply_once_per_order:- if cheapest_line := _get_the_cheapest_line(lines_included_in_discount):- discounted_lines_by_voucher = [cheapest_line]- for line_info in lines_info:- if line_info in discounted_lines_by_voucher:- line_info.voucher = voucher- line_info.voucher_code = voucher_info.voucher_code---def get_discounted_lines(- lines: Iterable["LineInfo"], voucher_info: "VoucherInfo"-) -> Iterable["LineInfo"]:- discounted_lines = []- if (- voucher_info.product_pks- or voucher_info.collection_pks- or voucher_info.category_pks- or voucher_info.variant_pks- ):- for line_info in lines:- if line_info.line.is_gift:- continue- line_variant = line_info.variant- line_product = line_info.product- if not line_variant or not line_product:- continue- line_category = line_product.category- line_collections = set(- [collection.pk for collection in line_info.collections]- )- if line_info.variant and (- line_variant.pk in voucher_info.variant_pks- or line_product.pk in voucher_info.product_pks- or line_category- and line_category.pk in voucher_info.category_pks- or line_collections.intersection(voucher_info.collection_pks)- ):- discounted_lines.append(line_info)- else:- # If there's no discounted products, collections or categories,- # it means that all products are discounted- discounted_lines.extend(lines)- return discounted_lines---def _get_the_cheapest_line(- lines_info: Optional[Iterable["LineInfo"]],-) -> Optional["LineInfo"]:- if not lines_info:- return None- return min(- lines_info, key=lambda line_info: line_info.channel_listing.discounted_price- )---def calculate_discounted_price_for_rules(- *, price: Money, rules: Iterable["PromotionRule"], currency: str-):- """Calculate the discounted price for provided rules.-- The discounts from rules summed up and applied to the price.- """- total_discount = zero_money(currency)- for rule in rules:- discount = rule.get_discount(currency)- total_discount += price - discount(price)-- return max(price - total_discount, zero_money(currency))---def calculate_discounted_price_for_promotions(- *,- price: Money,- rules_info_per_variant: dict[int, list[PromotionRuleInfo]],- channel: "Channel",- variant_id: int,-) -> Optional[tuple[UUID, Money]]:- """Return minimum product's price of all prices with promotions applied."""- applied_discount = None- rules_info_for_variant = rules_info_per_variant.get(variant_id)- if rules_info_for_variant:- applied_discount = get_best_promotion_discount(- price, rules_info_for_variant, channel- )- return applied_discount---def get_best_promotion_discount(- price: Money,- rules_info_for_variant: list[PromotionRuleInfo],- channel: "Channel",-) -> Optional[tuple[UUID, Money]]:- """Return the rule with the discount amount for the best promotion.-- The data for the promotion that gives the best saving are returned in the following- shape:- (rule_id_1, discount_amount_1)- """- available_discounts = []- for rule_id, discount in get_product_promotion_discounts(- rules_info=rules_info_for_variant,- channel=channel,- ):- available_discounts.append((rule_id, discount))-- applied_discount = None- if available_discounts:- applied_discount = max(- [- (rule_id, price - discount(price))- for rule_id, discount in available_discounts- ],- key=lambda x: x[1].amount, # sort over a max discount- )-- return applied_discount---def get_product_promotion_discounts(- *,- rules_info: list[PromotionRuleInfo],- channel: "Channel",-) -> Iterator[tuple[UUID, Callable]]:- """Return rule id, discount value for all rules applicable for given channel."""- for rule_info in rules_info:- try:- yield get_product_discount_on_promotion(rule_info, channel)- except NotApplicable:- pass---def get_product_discount_on_promotion(- rule_info: PromotionRuleInfo,- channel: "Channel",-) -> tuple[UUID, Callable]:- """Return rule id, discount value if rule applied or raise NotApplicable."""- if channel.id in rule_info.channel_ids:- return rule_info.rule.id, rule_info.rule.get_discount(channel.currency_code)- raise NotApplicable("Promotion rule not applicable for this product")---def validate_voucher_for_checkout(- manager: "PluginsManager",- voucher: "Voucher",- checkout_info: "CheckoutInfo",- lines: Iterable["CheckoutLineInfo"],-):- from ..checkout import base_calculations- from ..checkout.utils import calculate_checkout_quantity-- quantity = calculate_checkout_quantity(lines)- subtotal = base_calculations.base_checkout_subtotal(- lines,- checkout_info.channel,- checkout_info.checkout.currency,- )-- customer_email = cast(str, checkout_info.get_customer_email())- validate_voucher(- voucher,- subtotal,- quantity,- customer_email,- checkout_info.channel,- checkout_info.user,- )---def validate_voucher_in_order(- order: "Order", lines: Iterable["OrderLine"], channel: "Channel"-):- if not order.voucher:- return-- from ..order.utils import get_total_quantity-- subtotal = order.subtotal- quantity = get_total_quantity(lines)- customer_email = order.get_customer_email()- tax_configuration = channel.tax_configuration- prices_entered_with_tax = tax_configuration.prices_entered_with_tax- value = subtotal.gross if prices_entered_with_tax else subtotal.net-- validate_voucher(- order.voucher, value, quantity, customer_email, channel, order.user- )---def validate_voucher(- voucher: "Voucher",- total_price: Money,- quantity: int,- customer_email: str,- channel: Channel,- customer: Optional["User"],-) -> None:- voucher.validate_min_spent(total_price, channel)- voucher.validate_min_checkout_items_quantity(quantity)- if voucher.apply_once_per_customer:- voucher.validate_once_per_customer(customer_email)- if voucher.only_for_staff:- voucher.validate_only_for_staff(customer)---def get_products_voucher_discount(- voucher: "Voucher", prices: Iterable[Money], channel: Channel-) -> Money:- """Calculate discount value for a voucher of product or category type."""- if voucher.apply_once_per_order:- return voucher.get_discount_amount_for(min(prices), channel)- discounts = (voucher.get_discount_amount_for(price, channel) for price in prices)- total_amount = sum(discounts, zero_money(channel.currency_code))- return total_amount---def apply_discount_to_value(- value: Decimal,- value_type: Optional[str],- currency: str,- price_to_discount: Union[Money, TaxedMoney],-):- """Calculate the price based on the provided values."""- if value_type == DiscountValueType.PERCENTAGE:- discount_method = percentage_discount- discount_kwargs = {"percentage": value, "rounding": ROUND_HALF_UP}- else:- discount_method = fixed_discount- discount_kwargs = {"discount": Money(value, currency)}- discount = partial(- discount_method,- **discount_kwargs,- )- return discount(price_to_discount)---def create_or_update_discount_objects_from_promotion_for_checkout(- checkout_info: "CheckoutInfo",- lines_info: Iterable["CheckoutLineInfo"],- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- create_checkout_line_discount_objects_for_catalogue_promotions(lines_info)- create_checkout_discount_objects_for_order_promotions(- checkout_info, lines_info, database_connection_name=database_connection_name- )---def create_checkout_line_discount_objects_for_catalogue_promotions(- lines_info: Iterable["CheckoutLineInfo"],-):- discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)- if not discount_data or not lines_info:- return-- (- discounts_to_create_inputs,- discounts_to_update,- discount_to_remove,- updated_fields,- ) = discount_data-- new_line_discounts = []- with allow_writer():- with transaction.atomic():- # Protect against potential thread race. CheckoutLine object can have only- # single catalogue discount applied.- checkout_id = lines_info[0].line.checkout_id # type: ignore[index]- _checkout_lock = list(- Checkout.objects.filter(pk=checkout_id).select_for_update(of=(["self"]))- )-- if discount_ids_to_remove := [- discount.id for discount in discount_to_remove- ]:- CheckoutLineDiscount.objects.filter(- id__in=discount_ids_to_remove- ).delete()-- if discounts_to_create_inputs:- new_line_discounts = [- CheckoutLineDiscount(**input)- for input in discounts_to_create_inputs- ]- CheckoutLineDiscount.objects.bulk_create(- new_line_discounts, ignore_conflicts=True- )-- if discounts_to_update and updated_fields:- CheckoutLineDiscount.objects.bulk_update(- discounts_to_update, updated_fields- )-- _update_line_info_cached_discounts(- lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove- )---@overload-def prepare_line_discount_objects_for_catalogue_promotions(- lines_info: Iterable["CheckoutLineInfo"],-) -> tuple[- list[dict], list["CheckoutLineDiscount"], list["CheckoutLineDiscount"], list[str]-]: ...---@overload-def prepare_line_discount_objects_for_catalogue_promotions(- lines_info: Iterable["EditableOrderLineInfo"],-) -> tuple[- list[dict], list["OrderLineDiscount"], list["OrderLineDiscount"], list[str]-]: ...---def prepare_line_discount_objects_for_catalogue_promotions(lines_info):- line_discounts_to_create_inputs: list[dict] = []- line_discounts_to_update: list[Union[CheckoutLineDiscount, OrderLineDiscount]] = []- line_discounts_to_remove: list[Union[CheckoutLineDiscount, OrderLineDiscount]] = []- updated_fields: list[str] = []-- if not lines_info:- return-- for line_info in lines_info:- line = line_info.line-- # get the existing catalogue discount for the line- discount_to_update = None- if discounts_to_update := line_info.get_catalogue_discounts():- discount_to_update = discounts_to_update[0]- # Line should never have multiple catalogue discounts associated. Before- # introducing unique_type on discount models, there was such a possibility.- line_discounts_to_remove.extend(discounts_to_update[1:])-- # manual line discount do not stack with other discounts- if [- discount- for discount in line_info.discounts- if discount.type == DiscountType.MANUAL- ]:- line_discounts_to_remove.extend(discounts_to_update)- continue-- # check if the line price is discounted by catalogue promotion- discounted_line = _is_discounted_line_by_catalogue_promotion(- line_info.channel_listing- )-- # delete all existing discounts if the line is not discounted or it is a gift- if not discounted_line or line.is_gift:- line_discounts_to_remove.extend(discounts_to_update)- continue-- if line_info.rules_info:- rule_info = line_info.rules_info[0]- rule = rule_info.rule- rule_discount_amount = _get_rule_discount_amount(- line, rule_info, line_info.channel- )- discount_name = get_discount_name(rule, rule_info.promotion)- translated_name = get_discount_translated_name(rule_info)- reason = _get_discount_reason(rule)- if not discount_to_update:- line_discount_input = {- "line": line,- "type": DiscountType.PROMOTION,- "value_type": rule.reward_value_type,- "value": rule.reward_value,- "amount_value": rule_discount_amount,- "currency": line.currency,- "name": discount_name,- "translated_name": translated_name,- "reason": reason,- "promotion_rule": rule,- "unique_type": DiscountType.PROMOTION,- }- line_discounts_to_create_inputs.append(line_discount_input)- else:- _update_promotion_discount(- rule,- rule_info,- rule_discount_amount,- discount_to_update,- updated_fields,- )- line_discounts_to_update.append(discount_to_update)- else:- # Fallback for unlike mismatch between discount_amount and rules_info- line_discounts_to_remove.extend(discounts_to_update)-- return (- line_discounts_to_create_inputs,- line_discounts_to_update,- line_discounts_to_remove,- updated_fields,- )---def _is_discounted_line_by_catalogue_promotion(- variant_channel_listing: "ProductVariantChannelListing",-) -> bool:- """Return True when the price is discounted by catalogue promotion."""- price_amount = variant_channel_listing.price_amount- discounted_price_amount = variant_channel_listing.discounted_price_amount-- if (- price_amount is None- or discounted_price_amount is None- or price_amount == discounted_price_amount- ):- return False-- return True---def _get_rule_discount_amount(- line: Union["CheckoutLine", "OrderLine"],- rule_info: "VariantPromotionRuleInfo",- channel: "Channel",-) -> Decimal:- """Calculate the discount amount for catalogue promotion rule.-- When the line has overridden price, the discount is applied on the- new overridden base price.- """- variant_listing_promotion_rule = rule_info.variant_listing_promotion_rule- if not variant_listing_promotion_rule:- return Decimal("0.0")-- if isinstance(line, CheckoutLine):- price_override = (- Money(line.price_override, channel.currency_code)- if line.price_override is not None- else None- )- else:- price_override = (- line.undiscounted_base_unit_price if line.is_price_overridden else None- )-- if price_override is not None:- # calculate discount amount on overridden price- discount = rule_info.rule.get_discount(channel.currency_code)- discounted_price = discount(price_override)- discount_amount = (price_override - discounted_price).amount- else:- discount_amount = variant_listing_promotion_rule.discount_amount- return discount_amount * line.quantity---def get_discount_name(rule: "PromotionRule", promotion: "Promotion"):- if promotion.name and rule.name:- return f"{promotion.name}: {rule.name}"- return rule.name or promotion.name---def _get_discount_reason(rule: PromotionRule):- promotion = rule.promotion- if promotion.old_sale_id:- return f"Sale: {graphene.Node.to_global_id('Sale', promotion.old_sale_id)}"- return f"Promotion: {graphene.Node.to_global_id('Promotion', promotion.id)}"---def get_discount_translated_name(rule_info: "VariantPromotionRuleInfo"):- promotion_translation = rule_info.promotion_translation- rule_translation = rule_info.rule_translation- if promotion_translation and rule_translation:- return f"{promotion_translation.name}: {rule_translation.name}"- if rule_translation:- return rule_translation.name- if promotion_translation:- return promotion_translation.name- return None---def _update_promotion_discount(- rule: "PromotionRule",- rule_info: "VariantPromotionRuleInfo",- rule_discount_amount: Decimal,- discount_to_update: Union[- "CheckoutLineDiscount", "CheckoutDiscount", "OrderLineDiscount", "OrderDiscount"- ],- updated_fields: list[str],-):- discount_name = get_discount_name(rule, rule_info.promotion)- translated_name = get_discount_translated_name(rule_info)- reason = prepare_promotion_discount_reason(- rule_info.promotion, get_sale_id(rule_info.promotion)- )- # gift rule has empty reward_value_type- value_type = rule.reward_value_type or RewardValueType.FIXED- # gift rule has empty reward_value- value = rule.reward_value or rule_discount_amount- _update_discount(- rule,- None,- discount_name,- translated_name,- reason,- rule_discount_amount,- value,- value_type,- DiscountType.PROMOTION,- discount_to_update,- updated_fields,- )---def _update_discount(- rule: Optional["PromotionRule"],- voucher: Optional["Voucher"],- discount_name: str,- translated_name: str,- discount_reason: str,- discount_amount: Decimal,- value: Decimal,- value_type: str,- unique_type: str,- discount_to_update: Union[- "CheckoutLineDiscount", "CheckoutDiscount", "OrderLineDiscount", "OrderDiscount"- ],- updated_fields: list[str],-):- if voucher and discount_to_update.voucher_id != voucher.id:- discount_to_update.voucher_id = voucher.id- updated_fields.append("voucher_id")- if rule and discount_to_update.promotion_rule_id != rule.id:- discount_to_update.promotion_rule_id = rule.id- updated_fields.append("promotion_rule_id")- if discount_to_update.value_type != value_type:- discount_to_update.value_type = value_type- updated_fields.append("value_type")- if discount_to_update.value != value:- discount_to_update.value = value- updated_fields.append("value")- if discount_to_update.amount_value != discount_amount:- discount_to_update.amount_value = discount_amount- updated_fields.append("amount_value")- if discount_to_update.name != discount_name:- discount_to_update.name = discount_name- updated_fields.append("name")- if discount_to_update.translated_name != translated_name:- discount_to_update.translated_name = translated_name- updated_fields.append("translated_name")-- if discount_to_update.reason != discount_reason:- discount_to_update.reason = discount_reason- updated_fields.append("reason")- if hasattr(discount_to_update, "unique_type"):- if discount_to_update.unique_type is None:- discount_to_update.unique_type = unique_type- updated_fields.append("unique_type")---def _update_line_info_cached_discounts(- lines_info, new_line_discounts, updated_discounts, line_discount_ids_to_remove-):- if not any([new_line_discounts, updated_discounts, line_discount_ids_to_remove]):- return-- line_id_line_discounts_map = defaultdict(list)- for line_discount in new_line_discounts:- line_id_line_discounts_map[line_discount.line_id].append(line_discount)-- for line_info in lines_info:- line_info.discounts = [- discount- for discount in line_info.discounts- if discount.id not in line_discount_ids_to_remove- ]- if discount := line_id_line_discounts_map.get(line_info.line.id):- line_info.discounts.extend(discount)---def create_checkout_discount_objects_for_order_promotions(- checkout_info: "CheckoutInfo",- lines_info: Iterable["CheckoutLineInfo"],- *,- save: bool = False,- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- # The base prices are required for order promotion discount qualification.- _set_checkout_base_prices(checkout_info, lines_info)-- checkout = checkout_info.checkout-- # Discount from order rules is applied only when the voucher is not set- if checkout.voucher_code:- _clear_checkout_discount(checkout_info, lines_info, save)- return-- channel = checkout_info.channel- rules = fetch_promotion_rules_for_checkout_or_order(- checkout, database_connection_name- )- rule_data = get_best_rule(- rules=rules,- channel=channel,- country=checkout_info.get_country(),- subtotal=checkout.base_subtotal,- database_connection_name=database_connection_name,- )- if not rule_data:- _clear_checkout_discount(checkout_info, lines_info, save)- return-- best_rule, best_discount_amount, gift_listing = rule_data- promotion = best_rule.promotion- currency = channel.currency_code- translation_language_code = checkout.language_code- promotion_translation, rule_translation = get_rule_translations(- promotion, best_rule, translation_language_code- )- rule_info = VariantPromotionRuleInfo(- rule=best_rule,- variant_listing_promotion_rule=None,- promotion=promotion,- promotion_translation=promotion_translation,- rule_translation=rule_translation,- )- # gift rule has empty reward_value and reward_value_type- value_type = best_rule.reward_value_type or RewardValueType.FIXED- amount_value = gift_listing.price_amount if gift_listing else best_discount_amount- value = best_rule.reward_value or amount_value- discount_object_defaults = {- "promotion_rule": best_rule,- "value_type": value_type,- "value": value,- "amount_value": amount_value,- "currency": currency,- "name": get_discount_name(best_rule, promotion),- "translated_name": get_discount_translated_name(rule_info),- "reason": prepare_promotion_discount_reason(promotion, get_sale_id(promotion)),- }- if gift_listing:- _handle_gift_reward_for_checkout(- checkout_info,- lines_info,- gift_listing,- discount_object_defaults,- rule_info,- save,- )- else:- _handle_order_promotion_for_checkout(- checkout_info,- lines_info,- discount_object_defaults,- rule_info,- save,- )---def get_best_rule(- rules: Iterable["PromotionRule"],- channel: "Channel",- country: str,- subtotal: Money,- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- RuleDiscount = namedtuple(- "RuleDiscount", ["rule", "discount_amount", "gift_listing"]- )- currency_code = channel.currency_code- rule_discounts: list[RuleDiscount] = []- gift_rules = [rule for rule in rules if rule.reward_type == RewardType.GIFT]- for rule in rules:- if rule in gift_rules:- continue- discount = rule.get_discount(currency_code)- price = zero_money(currency_code)- if rule.reward_type == RewardType.SUBTOTAL_DISCOUNT:- price = subtotal- discount_amount = (price - discount(price)).amount- rule_discounts.append(RuleDiscount(rule, discount_amount, None))-- if gift_rules:- best_gift_rule, gift_listing = _get_best_gift_reward(- gift_rules, channel, country, database_connection_name- )- if best_gift_rule and gift_listing:- rule_discounts.append(- RuleDiscount(- best_gift_rule, gift_listing.discounted_price_amount, gift_listing- )- )-- if not rule_discounts:- return-- best_rule, best_discount_amount, gift_listing = max(- rule_discounts, key=lambda x: x.discount_amount- )- return best_rule, best_discount_amount, gift_listing---def _set_checkout_base_prices(checkout_info, lines_info):- """Set base checkout prices that includes only catalogue discounts."""- checkout = checkout_info.checkout- subtotal = base_checkout_subtotal(- lines_info, checkout_info.channel, checkout.currency, include_voucher=False- )- shipping_price = base_checkout_delivery_price(- checkout_info, lines_info, include_voucher=False- )- total = subtotal + shipping_price- is_update_needed = not (- checkout.base_subtotal == subtotal and checkout.base_total == total- )- if is_update_needed:- checkout.base_subtotal = subtotal- checkout.base_total = total- with allow_writer():- checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])---def _clear_checkout_discount(- checkout_info: "CheckoutInfo", lines_info: Iterable["CheckoutLineInfo"], save: bool-):- delete_gift_line(checkout_info.checkout, lines_info)- if checkout_info.discounts:- CheckoutDiscount.objects.filter(- checkout=checkout_info.checkout,- type=DiscountType.ORDER_PROMOTION,- ).delete()- checkout_info.discounts = [- discount- for discount in checkout_info.discounts- if discount.type != DiscountType.ORDER_PROMOTION- ]- checkout = checkout_info.checkout- if not checkout_info.voucher_code:- is_update_needed = not (- checkout.discount_amount == 0- and checkout.discount_name is None- and checkout.translated_discount_name is None- )- if is_update_needed:- checkout.discount_amount = 0- checkout.discount_name = None- checkout.translated_discount_name = None-- if save and is_update_needed:- checkout.save(- update_fields=[- "discount_amount",- "discount_name",- "translated_discount_name",- ]- )---def _get_best_gift_reward(- rules: Iterable["PromotionRule"],- channel: "Channel",- country: str,- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-) -> tuple[Optional[PromotionRule], Optional[ProductVariantChannelListing]]:- from ..warehouse.availability import check_stock_quantity_bulk-- rule_ids = [rule.id for rule in rules]- PromotionRuleGift = PromotionRule.gifts.through- rule_gifts = PromotionRuleGift.objects.using(database_connection_name).filter(- promotionrule_id__in=rule_ids- )- variants = ProductVariant.objects.using(database_connection_name).filter(- Exists(- rule_gifts.values("productvariant_id").filter(- productvariant_id=OuterRef("id")- )- )- )- variant_ids_with_insufficient_stock = set()- if not variants:- return None, None-- try:- check_stock_quantity_bulk(- variants,- country,- [1] * variants.count(),- channel.slug,- None,- database_connection_name=database_connection_name,- )- except InsufficientStock as error:- variant_ids_with_insufficient_stock = {- item.variant.pk for item in error.items if item.variant- }-- available_variant_ids = (- set(variants.values_list("id", flat=True)) - variant_ids_with_insufficient_stock- )-- if not available_variant_ids:- return None, None-- # check if variant is available for purchase- available_variant_ids = _get_available_for_purchase_variant_ids(- available_variant_ids,- channel,- database_connection_name=database_connection_name,- )- if not available_variant_ids:- return None, None-- # check variant channel availability- available_variant_listings = ProductVariantChannelListing.objects.using(- database_connection_name- ).filter(- variant_id__in=available_variant_ids,- channel_id=channel.id,- price_amount__isnull=False,- )- if not available_variant_listings:- return None, None-- listing = max(- list(available_variant_listings),- # sort over a top price- key=lambda x: x.discounted_price_amount,- )- rule_gift = rule_gifts.filter(productvariant_id=listing.variant_id).first()- rule = rule_gift.promotionrule if rule_gift else None- return rule, listing---def _get_available_for_purchase_variant_ids(- available_variant_ids: set[int],- channel: "Channel",- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- today = datetime.datetime.now(pytz.UTC)- variants = ProductVariant.objects.using(database_connection_name).filter(- id__in=available_variant_ids- )- product_listings = ProductChannelListing.objects.using(- database_connection_name- ).filter(- Exists(variants.filter(product_id=OuterRef("product_id"))),- available_for_purchase_at__lte=today,- channel_id=channel.id,- )- available_variant_ids = variants.filter(- Exists(product_listings.filter(product_id=OuterRef("product_id")))- ).values_list("id", flat=True)- return set(available_variant_ids)---@allow_writer()-def _handle_order_promotion_for_checkout(- checkout_info: "CheckoutInfo",- lines_info: Iterable["CheckoutLineInfo"],- discount_object_defaults: dict,- rule_info: VariantPromotionRuleInfo,- save: bool = False,-):- checkout = checkout_info.checkout- discount_object, created = checkout.discounts.get_or_create(- type=DiscountType.ORDER_PROMOTION,- defaults=discount_object_defaults,- )- discount_amount = discount_object_defaults["amount_value"]-- if not created:- fields_to_update: list[str] = []- _update_promotion_discount(- discount_object_defaults["promotion_rule"],- rule_info,- discount_amount,- discount_object,- fields_to_update,- )- if fields_to_update:- discount_object.save(update_fields=fields_to_update)-- checkout_info.discounts = [discount_object]- checkout = checkout_info.checkout- checkout.discount_amount = discount_amount- checkout.discount_name = discount_object.name- checkout.translated_discount_name = discount_object.translated_name- if save:- checkout.save(- update_fields=[- "discount_amount",- "discount_name",- "translated_discount_name",- ]- )-- delete_gift_line(checkout, lines_info)---@allow_writer()-def delete_gift_line(- order_or_checkout: Union[Checkout, Order],- lines_info: Iterable[Union["CheckoutLineInfo", "EditableOrderLineInfo"]],-):- if gift_line_infos := [line for line in lines_info if line.line.is_gift]:- order_or_checkout.lines.filter(is_gift=True).delete() # type: ignore[misc]- for gift_line_info in gift_line_infos:- lines_info.remove(gift_line_info) # type: ignore[attr-defined]---@allow_writer()-def _handle_gift_reward_for_checkout(- checkout_info: "CheckoutInfo",- lines_info: Iterable["CheckoutLineInfo"],- gift_listing: ProductVariantChannelListing,- discount_object_defaults: dict,- rule_info: VariantPromotionRuleInfo,- save: bool = False,-):- from ..checkout.fetch import CheckoutLineInfo-- with transaction.atomic():- line, line_created = create_gift_line(- checkout_info.checkout, gift_listing.variant_id- )- (- line_discount,- discount_created,- ) = CheckoutLineDiscount.objects.get_or_create(- type=DiscountType.ORDER_PROMOTION,- line=line,- defaults=discount_object_defaults,- )-- if not discount_created:- fields_to_update = []- if line_discount.line_id != line.id:- line_discount.line = line- fields_to_update.append("line_id")- _update_promotion_discount(- discount_object_defaults["promotion_rule"],- rule_info,- discount_object_defaults["amount_value"],- line_discount,- fields_to_update,- )- if fields_to_update:- line_discount.save(update_fields=fields_to_update)-- checkout_info.discounts = []- checkout_info.checkout.discount_amount = Decimal("0")- if save:- checkout_info.checkout.save(update_fields=["discount_amount"])-- if line_created:- variant = gift_listing.variant- init_values = {- "line": line,- "variant": variant,- "channel_listing": gift_listing,- "discounts": [line_discount],- "rules_info": [rule_info],- "channel": checkout_info.channel,- "product": variant.product,- "product_type": variant.product.product_type,- "collections": [],- "voucher": None,- "voucher_code": None,- }-- gift_line_info = CheckoutLineInfo(**init_values)- lines_info.append(gift_line_info) # type: ignore[attr-defined]- else:- line_info = next(- line_info for line_info in lines_info if line_info.line.pk == line.id- )- line_info.line = line- line_info.discounts = [line_discount]---def create_gift_line(order_or_checkout: Union[Checkout, Order], variant_id: int):- defaults = _get_defaults_for_gift_line(order_or_checkout, variant_id)- line, created = order_or_checkout.lines.get_or_create(- is_gift=True, defaults=defaults- )- if not created:- fields_to_update = []- for field, value in defaults.items():- if getattr(line, field) != value:- setattr(line, field, value)- fields_to_update.append(field)- if fields_to_update:- line.save(update_fields=fields_to_update)-- return line, created---def _get_defaults_for_gift_line(- order_or_checkout: Union[Checkout, Order], variant_id: int-):- if isinstance(order_or_checkout, Checkout):- return {- "variant_id": variant_id,- "quantity": 1,- "currency": order_or_checkout.currency,- }- else:- variant = (- ProductVariant.objects.filter(id=variant_id)- .select_related("product")- .only("sku", "product__name")- .first()- )- return {- "variant_id": variant_id,- "product_name": variant.product.name if variant else "",- "product_sku": variant.sku if variant else "",- "quantity": 1,- "currency": order_or_checkout.currency,- "unit_price_net_amount": Decimal(0),- "unit_price_gross_amount": Decimal(0),- "total_price_net_amount": Decimal(0),- "total_price_gross_amount": Decimal(0),- "is_shipping_required": True,- "is_gift_card": False,- }---def get_variants_to_promotion_rules_map(- variant_qs: "ProductVariantQueryset",-) -> dict[int, list[PromotionRuleInfo]]:- """Return map of variant ids to the list of promotion rules that can be applied.-- The data is returned in the following shape:- {- variant_id_1: [PromotionRuleInfo_1, PromotionRuleInfo_2, PromotionRuleInfo_3],- variant_id_2: [PromotionRuleInfo_1]- }- """- rules_info_per_variant: dict[int, list[PromotionRuleInfo]] = defaultdict(list)-- promotions = Promotion.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).active()- PromotionRuleVariant = PromotionRule.variants.through- promotion_rule_variants = PromotionRuleVariant.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).filter(Exists(variant_qs.filter(id=OuterRef("productvariant_id"))))-- # fetch rules only for active promotions- rules = PromotionRule.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).filter(- Exists(promotions.filter(id=OuterRef("promotion_id"))),- Exists(promotion_rule_variants.filter(promotionrule_id=OuterRef("pk"))),- )- rule_to_channel_ids_map = _get_rule_to_channel_ids_map(rules)- rules_in_bulk = rules.in_bulk()-- for promotion_rule_variant in promotion_rule_variants.iterator():- rule_id = promotion_rule_variant.promotionrule_id- rule = rules_in_bulk.get(rule_id)- # there is no rule when it is a part of inactive promotion- if not rule:- continue- variant_id = promotion_rule_variant.productvariant_id- rules_info_per_variant[variant_id].append(- PromotionRuleInfo(- rule=rule,- channel_ids=rule_to_channel_ids_map.get(rule_id, []),- )- )-- return rules_info_per_variant---def fetch_promotion_rules_for_checkout_or_order(- instance: Union["Checkout", "Order"],- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- from ..graphql.discount.utils import PredicateObjectType, filter_qs_by_predicate-- with allow_writer():- # TODO: channel should be loaded using dataloader- currency = instance.channel.currency_code-- applicable_rules = []- promotions = Promotion.objects.active()- rules = (- PromotionRule.objects.using(database_connection_name)- .filter(Exists(promotions.filter(id=OuterRef("promotion_id"))))- .exclude(order_predicate={})- .prefetch_related("channels")- )- rule_to_channel_ids_map = _get_rule_to_channel_ids_map(rules)-- channel_id = instance.channel_id- qs = instance._meta.model.objects.using(database_connection_name).filter( # type: ignore[attr-defined] # noqa: E501- pk=instance.pk- )- for rule in rules.iterator():- rule_channel_ids = rule_to_channel_ids_map.get(rule.id, [])- if channel_id not in rule_channel_ids:- continue- predicate_type = (- PredicateObjectType.CHECKOUT- if isinstance(instance, Checkout)- else PredicateObjectType.ORDER- )- objects = filter_qs_by_predicate(- rule.order_predicate,- qs,- predicate_type,- currency,- )- if objects.exists():- applicable_rules.append(rule)-- return applicable_rules---def _get_rule_to_channel_ids_map(rules: QuerySet):- rule_to_channel_ids_map = defaultdict(list)- PromotionRuleChannel = PromotionRule.channels.through- promotion_rule_channels = PromotionRuleChannel.objects.using(- settings.DATABASE_CONNECTION_REPLICA_NAME- ).filter(Exists(rules.filter(id=OuterRef("promotionrule_id"))))- for promotion_rule_channel in promotion_rule_channels:- rule_id = promotion_rule_channel.promotionrule_id- channel_id = promotion_rule_channel.channel_id- rule_to_channel_ids_map[rule_id].append(channel_id)- return rule_to_channel_ids_map---def get_current_products_for_rules(rules: "QuerySet[PromotionRule]"):- """Get currently assigned products to promotions.-- Collect all products for variants that are assigned to promotion rules.- """- PromotionRuleVariant = PromotionRule.variants.through- rule_variants = PromotionRuleVariant.objects.filter(- Exists(rules.filter(pk=OuterRef("promotionrule_id")))- )- variants = ProductVariant.objects.filter(- Exists(rule_variants.filter(productvariant_id=OuterRef("id")))- )- return Product.objects.filter(Exists(variants.filter(product_id=OuterRef("id"))))---def update_rule_variant_relation(- rules: QuerySet[PromotionRule], new_rules_variants: list-):- """Update PromotionRule - ProductVariant relation.-- Deletes relations, which are not valid anymore.- Adds new relations, if they don't exist already.- `new_rules_variants` is a list of PromotionRuleVariant objects.- """- with transaction.atomic():- PromotionRuleVariant = PromotionRule.variants.through- existing_rules_variants = PromotionRuleVariant.objects.filter(- Exists(rules.filter(pk=OuterRef("promotionrule_id")))- ).all()- new_rule_variant_set = set(- (rv.promotionrule_id, rv.productvariant_id) for rv in new_rules_variants- )- existing_rule_variant_set = set(- (rv.promotionrule_id, rv.productvariant_id)- for rv in existing_rules_variants- )-- # Clear invalid variants assigned to promotion rules- rule_variant_to_delete_ids = [- rv.id- for rv in existing_rules_variants- if (rv.promotionrule_id, rv.productvariant_id) not in new_rule_variant_set- ]- PromotionRuleVariant.objects.filter(id__in=rule_variant_to_delete_ids).delete()-- # Assign new variants to promotion rules- rules_variants_to_add = [- rv- for rv in new_rules_variants- if (rv.promotionrule_id, rv.productvariant_id)- not in existing_rule_variant_set- ]- PromotionRuleVariant.objects.bulk_create(- rules_variants_to_add, ignore_conflicts=True- )---def create_or_update_discount_objects_for_order(- order: "Order",- lines_info: Iterable["EditableOrderLineInfo"],- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- create_or_update_discount_objects_from_promotion_for_order(- order, lines_info, database_connection_name- )- create_or_update_line_discount_objects_for_manual_discounts(lines_info)- create_or_update_line_discount_objects_from_voucher(order, lines_info)- _copy_unit_discount_data_to_order_line(lines_info)---def create_or_update_discount_objects_from_promotion_for_order(- order: "Order",- lines_info: Iterable["EditableOrderLineInfo"],- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- create_order_line_discount_objects_for_catalogue_promotions(lines_info)- # base unit price must reflect all actual catalogue discounts- _update_base_unit_price_amount_for_catalogue_promotion(lines_info)- create_order_discount_objects_for_order_promotions(- order, lines_info, database_connection_name=database_connection_name- )---def create_order_line_discount_objects_for_catalogue_promotions(- lines_info: Iterable["EditableOrderLineInfo"],-):- discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)- create_order_line_discount_objects(lines_info, discount_data)---def create_order_line_discount_objects(- lines_info: Iterable["EditableOrderLineInfo"],- discount_data: tuple[- list[dict],- list["OrderLineDiscount"],- list["OrderLineDiscount"],- list[str],- ],-):- if not discount_data or not lines_info:- return-- (- discounts_to_create_inputs,- discounts_to_update,- discount_to_remove,- updated_fields,- ) = discount_data-- new_line_discounts: list[OrderLineDiscount] = []- with allow_writer():- with transaction.atomic():- # Protect against potential thread race. OrderLine object can have only- # single catalogue discount applied.- order_id = lines_info[0].line.order_id # type: ignore[index]- _order_lock = list(- Order.objects.filter(id=order_id).select_for_update(of=(["self"]))- )-- if discount_ids_to_remove := [- discount.id for discount in discount_to_remove- ]:- OrderLineDiscount.objects.filter(id__in=discount_ids_to_remove).delete()-- if discounts_to_create_inputs:- new_line_discounts = [- OrderLineDiscount(**input) for input in discounts_to_create_inputs- ]- OrderLineDiscount.objects.bulk_create(- new_line_discounts, ignore_conflicts=True- )-- if discounts_to_update and updated_fields:- OrderLineDiscount.objects.bulk_update(- discounts_to_update, updated_fields- )-- _update_line_info_cached_discounts(- lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove- )- affected_line_ids = [- discount_line.line_id- for discount_line in (new_line_discounts + discounts_to_update)- ]- affected_line_ids.extend(discount_ids_to_remove)- modified_lines_info = [- line_info for line_info in lines_info if line_info.line.id in affected_line_ids- ]- return modified_lines_info---def _copy_unit_discount_data_to_order_line(- lines_info: Iterable["EditableOrderLineInfo"],-):- for line_info in lines_info:- if discounts := line_info.discounts:- line = line_info.line- discount_amount = sum([discount.amount_value for discount in discounts])- unit_discount_amount = discount_amount / line.quantity- discount_reason = "; ".join(- [discount.reason for discount in discounts if discount.reason]- )- discount_type = (- discounts[0].value_type- if len(discounts) == 1- else DiscountValueType.FIXED- )- discount_value = (- discounts[0].value if len(discounts) == 1 else unit_discount_amount- )-- line.unit_discount_amount = unit_discount_amount- line.unit_discount_reason = discount_reason- line.unit_discount_type = discount_type- line.unit_discount_value = discount_value---def _update_base_unit_price_amount_for_catalogue_promotion(- lines_info: Iterable["EditableOrderLineInfo"],-):- for line_info in lines_info:- line = line_info.line- base_unit_price = line.undiscounted_base_unit_price_amount- for discount in line_info.get_catalogue_discounts():- unit_discount = discount.amount_value / line.quantity- base_unit_price -= unit_discount- line.base_unit_price_amount = max(base_unit_price, Decimal(0))---def create_order_discount_objects_for_order_promotions(- order: "Order",- lines_info: Iterable["EditableOrderLineInfo"],- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- from ..order.base_calculations import base_order_subtotal- from ..order.utils import get_order_country-- # If voucher is set or manual discount applied, then skip order promotions- with allow_writer():- # TODO: country and order discounts should be loaded with dataloader- country = get_order_country(order)- if order.voucher_code or order.discounts.filter(type=DiscountType.MANUAL):- _clear_order_discount(order, lines_info)- return-- # The base prices are required for order promotion discount qualification.- _set_order_base_prices(order, lines_info)-- lines = [line_info.line for line_info in lines_info]- subtotal = base_order_subtotal(order, lines)- channel = order.channel- rules = fetch_promotion_rules_for_checkout_or_order(order, database_connection_name)- rule_data = get_best_rule(- rules=rules,- channel=channel,- country=country,- subtotal=subtotal,- database_connection_name=database_connection_name,- )- if not rule_data:- _clear_order_discount(order, lines_info)- return-- best_rule, best_discount_amount, gift_listing = rule_data- promotion = best_rule.promotion- currency = channel.currency_code- translation_language_code = order.language_code- promotion_translation, rule_translation = get_rule_translations(- promotion, best_rule, translation_language_code- )- rule_info = VariantPromotionRuleInfo(- rule=best_rule,- variant_listing_promotion_rule=None,- promotion=best_rule.promotion,- promotion_translation=promotion_translation,- rule_translation=rule_translation,- )- # gift rule has empty reward_value and reward_value_type- value_type = best_rule.reward_value_type or RewardValueType.FIXED- amount_value = gift_listing.price_amount if gift_listing else best_discount_amount- value = best_rule.reward_value or amount_value- discount_object_defaults = {- "promotion_rule": best_rule,- "value_type": value_type,- "value": value,- "amount_value": amount_value,- "currency": currency,- "name": get_discount_name(best_rule, promotion),- "translated_name": get_discount_translated_name(rule_info),- "reason": prepare_promotion_discount_reason(promotion, get_sale_id(promotion)),- }- if gift_listing:- _handle_gift_reward_for_order(- order,- lines_info,- gift_listing,- discount_object_defaults,- rule_info,- )- else:- _handle_order_promotion_for_order(- order,- lines_info,- discount_object_defaults,- rule_info,- )---@allow_writer()-def _clear_order_discount(- order_or_checkout: Union[Checkout, Order],- lines_info: Iterable["EditableOrderLineInfo"],-):- with transaction.atomic():- delete_gift_line(order_or_checkout, lines_info)- order_or_checkout.discounts.filter(type=DiscountType.ORDER_PROMOTION).delete()---def _set_order_base_prices(order: Order, lines_info: Iterable["EditableOrderLineInfo"]):- """Set base order prices that includes only catalogue discounts."""- from ..order.base_calculations import base_order_subtotal-- lines = [line_info.line for line_info in lines_info]- subtotal = base_order_subtotal(order, lines)- shipping_price = order.base_shipping_price- total = subtotal + shipping_price-- update_fields = []- if order.subtotal != TaxedMoney(net=subtotal, gross=subtotal):- order.subtotal = TaxedMoney(net=subtotal, gross=subtotal)- update_fields.extend(["subtotal_net_amount", "subtotal_gross_amount"])- if order.total != TaxedMoney(net=total, gross=total):- order.total = TaxedMoney(net=total, gross=total)- update_fields.extend(["total_net_amount", "total_gross_amount"])-- if update_fields:- with allow_writer():- order.save(update_fields=update_fields)---def _handle_order_promotion_for_order(- order: Order,- lines_info: Iterable["EditableOrderLineInfo"],- discount_object_defaults: dict,- rule_info: VariantPromotionRuleInfo,-):- discount_object, created = order.discounts.get_or_create(- type=DiscountType.ORDER_PROMOTION,- defaults=discount_object_defaults,- )- discount_amount = discount_object_defaults["amount_value"]-- if not created:- fields_to_update: list[str] = []- _update_promotion_discount(- discount_object_defaults["promotion_rule"],- rule_info,- discount_amount,- discount_object,- fields_to_update,- )- if fields_to_update:- discount_object.save(update_fields=fields_to_update)-- delete_gift_line(order, lines_info)---@allow_writer()-def _handle_gift_reward_for_order(- order: Order,- lines_info: Iterable["EditableOrderLineInfo"],- gift_listing: ProductVariantChannelListing,- discount_object_defaults: dict,- rule_info: VariantPromotionRuleInfo,-):- from ..order.fetch import EditableOrderLineInfo-- with transaction.atomic():- line, line_created = create_gift_line(order, gift_listing.variant_id)- (- line_discount,- discount_created,- ) = OrderLineDiscount.objects.get_or_create(- type=DiscountType.ORDER_PROMOTION,- line=line,- defaults=discount_object_defaults,- )-- if not discount_created:- fields_to_update = []- if line_discount.line_id != line.id:- line_discount.line = line- fields_to_update.append("line_id")- _update_promotion_discount(- discount_object_defaults["promotion_rule"],- rule_info,- discount_object_defaults["amount_value"],- line_discount,- fields_to_update,- )- if fields_to_update:- line_discount.save(update_fields=fields_to_update)-- if line_created:- variant = gift_listing.variant- init_values = {- "line": line,- "variant": variant,- "product": variant.product,- "collections": list(variant.product.collections.all()),- "channel_listing": gift_listing,- "discounts": [line_discount],- "rules_info": [rule_info],- "channel": order.channel_id,- "voucher": None,- "voucher_code": None,- }- gift_line_info = EditableOrderLineInfo(**init_values)- lines_info.append(gift_line_info) # type: ignore[attr-defined]- else:- line_info = next(- line_info for line_info in lines_info if line_info.line.pk == line.id- )- line_info.line = line- line_info.discounts = [line_discount]---def create_or_update_line_discount_objects_for_manual_discounts(lines_info):- discount_to_update: list[OrderLineDiscount] = []- for line_info in lines_info:- manual_discount = line_info.get_manual_line_discount()- if not manual_discount:- continue- line = line_info.line- base_unit_price = line.undiscounted_base_unit_price- reduced_unit_price = apply_discount_to_value(- manual_discount.value,- manual_discount.value_type,- line.currency,- base_unit_price,- )- reduced_unit_price = max(reduced_unit_price, zero_money(line.currency))- line.base_unit_price_amount = reduced_unit_price.amount-- discount_unit_amount = (base_unit_price - reduced_unit_price).amount- discount_amount = discount_unit_amount * line.quantity- if manual_discount.amount_value != discount_amount:- manual_discount.amount_value = discount_amount- discount_to_update.append(manual_discount)-- if discount_to_update:- OrderLineDiscount.objects.bulk_update(discount_to_update, ["amount_value"])---def create_or_update_line_discount_objects_from_voucher(order, lines_info):- """Create or update line discount object for voucher applied on lines.-- The LineDiscount object is created for each line with voucher applied.- Only `SPECIFIC_PRODUCT` and `apply_once_per_order` voucher types are applied.-- """- discount_data = prepare_line_discount_objects_for_voucher(lines_info)- modified_lines_info = create_order_line_discount_objects(lines_info, discount_data)- # base unit price must reflect all actual line voucher discounts- if modified_lines_info:- _reduce_base_unit_price_for_voucher_discount(modified_lines_info)---# TODO (SHOPX-912): share the method with checkout-def prepare_line_discount_objects_for_voucher(- lines_info: Iterable["EditableOrderLineInfo"],-):- line_discounts_to_create_inputs: list[dict] = []- line_discounts_to_update: list[OrderLineDiscount] = []- line_discounts_to_remove: list[OrderLineDiscount] = []- updated_fields: list[str] = []-- if not lines_info:- return-- for line_info in lines_info:- line = line_info.line- total_price = line.base_unit_price * line.quantity- discount_amount = calculate_line_discount_amount_from_voucher(- line_info, total_price- )- # only one voucher can be applied- discount_to_update = None- if discounts_to_update := line_info.get_voucher_discounts():- discount_to_update = discounts_to_update[0]-- if not discount_amount or line.is_gift:- if discount_to_update:- line_discounts_to_remove.append(discount_to_update)- continue-- discount_amount = discount_amount.amount- discount_reason = f"Voucher code: {line_info.voucher_code}"- voucher = cast(Voucher, line_info.voucher)- discount_name = f"{voucher.name}"- if discount_to_update:- _update_discount(- None,- voucher,- discount_name,- # TODO (SHOPX-914): set translated voucher name- "",- discount_reason,- discount_amount,- # TODO (SHOPX-914): should be taken from voucher value_type and value- discount_amount,- DiscountValueType.FIXED,- DiscountType.VOUCHER,- discount_to_update,- updated_fields,- )- line_discounts_to_update.append(discount_to_update)- else:- line_discount_input = {- "line": line,- "type": DiscountType.VOUCHER,- # TODO (SHOPX-914): should be taken from voucher value_type and value- "value_type": DiscountValueType.FIXED,- "value": discount_amount,- "amount_value": discount_amount,- "currency": line.currency,- "name": discount_name,- "translated_name": None,- "reason": discount_reason,- "voucher": line_info.voucher,- "unique_type": DiscountType.VOUCHER,- }- line_discounts_to_create_inputs.append(line_discount_input)-- return (- line_discounts_to_create_inputs,- line_discounts_to_update,- line_discounts_to_remove,- updated_fields,- )---def calculate_line_discount_amount_from_voucher(- line_info: "LineInfo", total_price: Money-) -> Money:- """Calculate discount amount for voucher applied on line.-- Included vouchers: `SPECIFIC_PRODUCT` and `apply_once_per_order`.-- Args:- line_info: Order/Checkout line data.- total_price: Total price of the line, should be already reduced by- catalogue discounts if any applied.-- """- if not line_info.voucher:- return zero_money(total_price.currency)-- channel = line_info.channel- quantity = line_info.line.quantity- if not line_info.voucher.apply_once_per_order:- if line_info.voucher.discount_value_type == DiscountValueType.PERCENTAGE:- voucher_discount_amount = line_info.voucher.get_discount_amount_for(- total_price, channel=channel- )- discount_amount = min(voucher_discount_amount, total_price)- else:- unit_price = total_price / quantity- voucher_unit_discount_amount = line_info.voucher.get_discount_amount_for(- unit_price, channel=channel- )- discount_amount = min(- voucher_unit_discount_amount * quantity,- total_price,- )- else:- unit_price = total_price / quantity- voucher_unit_discount_amount = line_info.voucher.get_discount_amount_for(- unit_price, channel=channel- )- discount_amount = min(voucher_unit_discount_amount, unit_price)- return discount_amount---def _reduce_base_unit_price_for_voucher_discount(- lines_info: Iterable["EditableOrderLineInfo"],-):- for line_info in lines_info:- line = line_info.line- base_unit_price = line.base_unit_price_amount- for discount in line_info.get_voucher_discounts():- base_unit_price -= discount.amount_value / line.quantity- line.base_unit_price_amount = max(base_unit_price, Decimal(0))---def get_active_catalogue_promotion_rules(- allow_replica: bool = False,-) -> "QuerySet[PromotionRule]":- promotions = Promotion.objects.active().filter(type=PromotionType.CATALOGUE)- if allow_replica:- promotions = promotions.using(settings.DATABASE_CONNECTION_REPLICA_NAME)- rules = (- PromotionRule.objects.order_by("id")- .filter(- Exists(promotions.filter(id=OuterRef("promotion_id"))),- )- .exclude(catalogue_predicate={})- )- if allow_replica:- rules = rules.using(settings.DATABASE_CONNECTION_REPLICA_NAME)- return rules---def mark_active_catalogue_promotion_rules_as_dirty(channel_ids: Iterable[int]):- """Force promotion rule to recalculate.-- The rules which are marked as dirty, will be recalculated in background.- Products related to these rules will be recalculated as well.- """-- if not channel_ids:- return-- rules = get_active_catalogue_promotion_rules()- PromotionRuleChannel = PromotionRule.channels.through- promotion_rules = PromotionRuleChannel.objects.filter(channel_id__in=channel_ids)- rule_ids = rules.filter(- Exists(promotion_rules.filter(promotionrule_id=OuterRef("id")))- ).values_list("id", flat=True)-- with transaction.atomic():- rule_ids_to_update = list(- PromotionRule.objects.select_for_update(of=("self",))- .filter(id__in=rule_ids, variants_dirty=False)- .order_by("pk")- .values_list("id", flat=True)- )- PromotionRule.objects.filter(id__in=rule_ids_to_update).update(- variants_dirty=True- )---def mark_catalogue_promotion_rules_as_dirty(promotion_pks: Iterable[UUID]):- """Mark rules for promotions as dirty.-- The rules which are marked as dirty, will be recalculated in background.- Products related to these rules will be recalculated as well.- """- if not promotion_pks:- return- with transaction.atomic():- rule_ids_to_update = list(- PromotionRule.objects.select_for_update(of=(["self"]))- .filter(promotion_id__in=promotion_pks, variants_dirty=False)- .order_by("pk")- .values_list("id", flat=True)- )- PromotionRule.objects.filter(id__in=rule_ids_to_update).update(- variants_dirty=True- )diff --git a/saleor/discount/utils/__init__.py b/saleor/discount/utils/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/discount/utils/checkout.py b/saleor/discount/utils/checkout.pynew file mode 100644index 0000000000..60c4283202--- /dev/null+++ b/saleor/discount/utils/checkout.py@@ -0,0 +1,191 @@+from collections.abc import Iterable+from typing import TYPE_CHECKING++from django.conf import settings+from django.db import transaction++from ...checkout.base_calculations import (+ base_checkout_delivery_price,+ base_checkout_subtotal,+)+from ...checkout.models import Checkout+from ...core.db.connection import allow_writer+from .. import DiscountType+from ..models import (+ CheckoutDiscount,+ CheckoutLineDiscount,+)+from .promotion import (+ create_discount_objects_for_order_promotions,+ delete_gift_line,+ prepare_line_discount_objects_for_catalogue_promotions,+)+from .shared import update_line_info_cached_discounts++if TYPE_CHECKING:+ from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo+++def create_or_update_discount_objects_from_promotion_for_checkout(+ checkout_info: "CheckoutInfo",+ lines_info: Iterable["CheckoutLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ create_checkout_line_discount_objects_for_catalogue_promotions(lines_info)+ create_checkout_discount_objects_for_order_promotions(+ checkout_info, lines_info, database_connection_name=database_connection_name+ )+++def create_checkout_line_discount_objects_for_catalogue_promotions(+ lines_info: Iterable["CheckoutLineInfo"],+):+ discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)+ if not discount_data or not lines_info:+ return++ (+ discounts_to_create_inputs,+ discounts_to_update,+ discount_to_remove,+ updated_fields,+ ) = discount_data++ new_line_discounts = []+ with allow_writer():+ with transaction.atomic():+ # Protect against potential thread race. CheckoutLine object can have only+ # single catalogue discount applied.+ checkout_id = lines_info[0].line.checkout_id # type: ignore[index]+ _checkout_lock = list(+ Checkout.objects.filter(pk=checkout_id).select_for_update(of=(["self"]))+ )++ if discount_ids_to_remove := [+ discount.id for discount in discount_to_remove+ ]:+ CheckoutLineDiscount.objects.filter(+ id__in=discount_ids_to_remove+ ).delete()++ if discounts_to_create_inputs:+ new_line_discounts = [+ CheckoutLineDiscount(**input)+ for input in discounts_to_create_inputs+ ]+ CheckoutLineDiscount.objects.bulk_create(+ new_line_discounts, ignore_conflicts=True+ )++ if discounts_to_update and updated_fields:+ CheckoutLineDiscount.objects.bulk_update(+ discounts_to_update, updated_fields+ )++ update_line_info_cached_discounts(+ lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove+ )+++def create_checkout_discount_objects_for_order_promotions(+ checkout_info: "CheckoutInfo",+ lines_info: Iterable["CheckoutLineInfo"],+ *,+ save: bool = False,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ # The base prices are required for order promotion discount qualification.+ _set_checkout_base_prices(checkout_info, lines_info)++ checkout = checkout_info.checkout++ # Discount from order rules is applied only when the voucher is not set+ if checkout.voucher_code:+ _clear_checkout_discount(checkout_info, lines_info, save)+ return++ (+ gift_promotion_applied,+ discount_object,+ ) = create_discount_objects_for_order_promotions(+ checkout,+ lines_info,+ checkout.base_subtotal,+ checkout_info.channel,+ checkout_info.get_country(),+ database_connection_name=database_connection_name,+ )+ if not gift_promotion_applied and not discount_object:+ _clear_checkout_discount(checkout_info, lines_info, save)+ return++ if discount_object:+ checkout_info.discounts = [discount_object]+ checkout = checkout_info.checkout+ checkout.discount_amount = discount_object.amount_value+ checkout.discount_name = discount_object.name+ checkout.translated_discount_name = discount_object.translated_name+ if save:+ checkout.save(+ update_fields=[+ "discount_amount",+ "discount_name",+ "translated_discount_name",+ ]+ )+++def _set_checkout_base_prices(checkout_info, lines_info):+ """Set base checkout prices that includes only catalogue discounts."""+ checkout = checkout_info.checkout+ subtotal = base_checkout_subtotal(+ lines_info, checkout_info.channel, checkout.currency, include_voucher=False+ )+ shipping_price = base_checkout_delivery_price(+ checkout_info, lines_info, include_voucher=False+ )+ total = subtotal + shipping_price+ is_update_needed = not (+ checkout.base_subtotal == subtotal and checkout.base_total == total+ )+ if is_update_needed:+ checkout.base_subtotal = subtotal+ checkout.base_total = total+ with allow_writer():+ checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])+++def _clear_checkout_discount(+ checkout_info: "CheckoutInfo", lines_info: Iterable["CheckoutLineInfo"], save: bool+):+ delete_gift_line(checkout_info.checkout, lines_info)+ if checkout_info.discounts:+ CheckoutDiscount.objects.filter(+ checkout=checkout_info.checkout,+ type=DiscountType.ORDER_PROMOTION,+ ).delete()+ checkout_info.discounts = [+ discount+ for discount in checkout_info.discounts+ if discount.type != DiscountType.ORDER_PROMOTION+ ]+ checkout = checkout_info.checkout+ if not checkout_info.voucher_code:+ is_update_needed = not (+ checkout.discount_amount == 0+ and checkout.discount_name is None+ and checkout.translated_discount_name is None+ )+ if is_update_needed:+ checkout.discount_amount = 0+ checkout.discount_name = None+ checkout.translated_discount_name = None++ if save and is_update_needed:+ checkout.save(+ update_fields=[+ "discount_amount",+ "discount_name",+ "translated_discount_name",+ ]+ )diff --git a/saleor/discount/utils/manual_discount.py b/saleor/discount/utils/manual_discount.pynew file mode 100644index 0000000000..9c4be560d4--- /dev/null+++ b/saleor/discount/utils/manual_discount.py@@ -0,0 +1,27 @@+from decimal import ROUND_HALF_UP, Decimal+from functools import partial+from typing import Optional, Union++from prices import Money, TaxedMoney, fixed_discount, percentage_discount++from .. import DiscountValueType+++def apply_discount_to_value(+ value: Decimal,+ value_type: Optional[str],+ currency: str,+ price_to_discount: Union[Money, TaxedMoney],+):+ """Calculate the price based on the provided values."""+ if value_type == DiscountValueType.PERCENTAGE:+ discount_method = percentage_discount+ discount_kwargs = {"percentage": value, "rounding": ROUND_HALF_UP}+ else:+ discount_method = fixed_discount+ discount_kwargs = {"discount": Money(value, currency)}+ discount = partial(+ discount_method,+ **discount_kwargs,+ )+ return discount(price_to_discount)diff --git a/saleor/discount/utils/order.py b/saleor/discount/utils/order.pynew file mode 100644index 0000000000..2e3b22cf8f--- /dev/null+++ b/saleor/discount/utils/order.py@@ -0,0 +1,252 @@+from collections.abc import Iterable+from decimal import Decimal+from typing import TYPE_CHECKING++from django.conf import settings+from django.db import transaction+from prices import TaxedMoney++from ...core.db.connection import allow_writer+from ...core.taxes import zero_money+from ...order.base_calculations import base_order_subtotal+from ...order.models import Order+from ...order.utils import get_order_country+from .. import DiscountType+from ..models import (+ DiscountValueType,+ OrderLineDiscount,+)+from .manual_discount import apply_discount_to_value+from .promotion import (+ create_discount_objects_for_order_promotions,+ delete_gift_line,+ prepare_line_discount_objects_for_catalogue_promotions,+)+from .shared import update_line_info_cached_discounts+from .voucher import create_or_update_line_discount_objects_from_voucher++if TYPE_CHECKING:+ from ...order.fetch import EditableOrderLineInfo+++def create_or_update_discount_objects_for_order(+ order: "Order",+ lines_info: Iterable["EditableOrderLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ create_or_update_discount_objects_from_promotion_for_order(+ order, lines_info, database_connection_name+ )+ create_or_update_line_discount_objects_for_manual_discounts(lines_info)+ create_or_update_line_discount_objects_from_voucher(order, lines_info)+ _copy_unit_discount_data_to_order_line(lines_info)+++def create_or_update_discount_objects_from_promotion_for_order(+ order: "Order",+ lines_info: Iterable["EditableOrderLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ create_order_line_discount_objects_for_catalogue_promotions(lines_info)+ # base unit price must reflect all actual catalogue discounts+ _update_base_unit_price_amount_for_catalogue_promotion(lines_info)+ create_order_discount_objects_for_order_promotions(+ order, lines_info, database_connection_name=database_connection_name+ )+++def create_order_line_discount_objects_for_catalogue_promotions(+ lines_info: Iterable["EditableOrderLineInfo"],+):+ discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)+ create_order_line_discount_objects(lines_info, discount_data)+++def create_order_line_discount_objects(+ lines_info: Iterable["EditableOrderLineInfo"],+ discount_data: tuple[+ list[dict],+ list["OrderLineDiscount"],+ list["OrderLineDiscount"],+ list[str],+ ],+):+ if not discount_data or not lines_info:+ return++ (+ discounts_to_create_inputs,+ discounts_to_update,+ discount_to_remove,+ updated_fields,+ ) = discount_data++ new_line_discounts: list[OrderLineDiscount] = []+ with allow_writer():+ with transaction.atomic():+ # Protect against potential thread race. OrderLine object can have only+ # single catalogue discount applied.+ order_id = lines_info[0].line.order_id # type: ignore[index]+ _order_lock = list(+ Order.objects.filter(id=order_id).select_for_update(of=(["self"]))+ )++ if discount_ids_to_remove := [+ discount.id for discount in discount_to_remove+ ]:+ OrderLineDiscount.objects.filter(id__in=discount_ids_to_remove).delete()++ if discounts_to_create_inputs:+ new_line_discounts = [+ OrderLineDiscount(**input) for input in discounts_to_create_inputs+ ]+ OrderLineDiscount.objects.bulk_create(+ new_line_discounts, ignore_conflicts=True+ )++ if discounts_to_update and updated_fields:+ OrderLineDiscount.objects.bulk_update(+ discounts_to_update, updated_fields+ )++ update_line_info_cached_discounts(+ lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove+ )+ affected_line_ids = [+ discount_line.line_id+ for discount_line in (new_line_discounts + discounts_to_update)+ ]+ affected_line_ids.extend(discount_ids_to_remove)+ modified_lines_info = [+ line_info for line_info in lines_info if line_info.line.id in affected_line_ids+ ]+ return modified_lines_info+++def _copy_unit_discount_data_to_order_line(+ lines_info: Iterable["EditableOrderLineInfo"],+):+ for line_info in lines_info:+ if discounts := line_info.discounts:+ line = line_info.line+ discount_amount = sum([discount.amount_value for discount in discounts])+ unit_discount_amount = discount_amount / line.quantity+ discount_reason = "; ".join(+ [discount.reason for discount in discounts if discount.reason]+ )+ discount_type = (+ discounts[0].value_type+ if len(discounts) == 1+ else DiscountValueType.FIXED+ )+ discount_value = (+ discounts[0].value if len(discounts) == 1 else unit_discount_amount+ )++ line.unit_discount_amount = unit_discount_amount+ line.unit_discount_reason = discount_reason+ line.unit_discount_type = discount_type+ line.unit_discount_value = discount_value+++def _update_base_unit_price_amount_for_catalogue_promotion(+ lines_info: Iterable["EditableOrderLineInfo"],+):+ for line_info in lines_info:+ line = line_info.line+ base_unit_price = line.undiscounted_base_unit_price_amount+ for discount in line_info.get_catalogue_discounts():+ unit_discount = discount.amount_value / line.quantity+ base_unit_price -= unit_discount+ line.base_unit_price_amount = max(base_unit_price, Decimal(0))+++def create_order_discount_objects_for_order_promotions(+ order: "Order",+ lines_info: Iterable["EditableOrderLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ # If voucher is set or manual discount applied, then skip order promotions+ if order.voucher_code or order.discounts.filter(type=DiscountType.MANUAL):+ _clear_order_discount(order, lines_info)+ return++ # The base prices are required for order promotion discount qualification.+ _set_order_base_prices(order, lines_info)++ lines = [line_info.line for line_info in lines_info]+ subtotal = base_order_subtotal(order, lines)+ with allow_writer():+ country = get_order_country(order)++ (+ gift_promotion_applied,+ discount_object,+ ) = create_discount_objects_for_order_promotions(+ order,+ lines_info,+ subtotal,+ order.channel,+ country,+ database_connection_name=database_connection_name,+ )+ if not gift_promotion_applied and not discount_object:+ _clear_order_discount(order, lines_info)+ return+++def _set_order_base_prices(order: Order, lines_info: Iterable["EditableOrderLineInfo"]):+ """Set base order prices that includes only catalogue discounts."""+ lines = [line_info.line for line_info in lines_info]+ subtotal = base_order_subtotal(order, lines)+ shipping_price = order.base_shipping_price+ total = subtotal + shipping_price++ update_fields = []+ if order.subtotal != TaxedMoney(net=subtotal, gross=subtotal):+ order.subtotal = TaxedMoney(net=subtotal, gross=subtotal)+ update_fields.extend(["subtotal_net_amount", "subtotal_gross_amount"])+ if order.total != TaxedMoney(net=total, gross=total):+ order.total = TaxedMoney(net=total, gross=total)+ update_fields.extend(["total_net_amount", "total_gross_amount"])++ if update_fields:+ with allow_writer():+ order.save(update_fields=update_fields)+++@allow_writer()+def _clear_order_discount(+ order_or_checkout: Order,+ lines_info: Iterable["EditableOrderLineInfo"],+):+ with transaction.atomic():+ delete_gift_line(order_or_checkout, lines_info)+ order_or_checkout.discounts.filter(type=DiscountType.ORDER_PROMOTION).delete()+++def create_or_update_line_discount_objects_for_manual_discounts(lines_info):+ discount_to_update: list[OrderLineDiscount] = []+ for line_info in lines_info:+ manual_discount = line_info.get_manual_line_discount()+ if not manual_discount:+ continue+ line = line_info.line+ base_unit_price = line.undiscounted_base_unit_price+ reduced_unit_price = apply_discount_to_value(+ manual_discount.value,+ manual_discount.value_type,+ line.currency,+ base_unit_price,+ )+ reduced_unit_price = max(reduced_unit_price, zero_money(line.currency))+ line.base_unit_price_amount = reduced_unit_price.amount++ discount_unit_amount = (base_unit_price - reduced_unit_price).amount+ discount_amount = discount_unit_amount * line.quantity+ if manual_discount.amount_value != discount_amount:+ manual_discount.amount_value = discount_amount+ discount_to_update.append(manual_discount)++ if discount_to_update:+ OrderLineDiscount.objects.bulk_update(discount_to_update, ["amount_value"])diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.pynew file mode 100644index 0000000000..336c575976--- /dev/null+++ b/saleor/discount/utils/promotion.py@@ -0,0 +1,967 @@+import datetime+from collections import defaultdict, namedtuple+from collections.abc import Iterable, Iterator+from decimal import Decimal+from typing import TYPE_CHECKING, Callable, Optional, Union, overload+from uuid import UUID++import graphene+import pytz+from django.conf import settings+from django.db import transaction+from django.db.models import Exists, OuterRef, QuerySet+from prices import Money++from ...channel.models import Channel+from ...checkout.fetch import CheckoutLineInfo+from ...checkout.models import Checkout, CheckoutLine+from ...core.db.connection import allow_writer+from ...core.exceptions import InsufficientStock+from ...core.taxes import zero_money+from ...order.fetch import EditableOrderLineInfo+from ...order.models import Order+from ...product.models import (+ Product,+ ProductChannelListing,+ ProductVariant,+ ProductVariantChannelListing,+)+from ...warehouse.availability import check_stock_quantity_bulk+from .. import (+ DiscountType,+ PromotionRuleInfo,+ PromotionType,+ RewardType,+ RewardValueType,+)+from ..interface import VariantPromotionRuleInfo, get_rule_translations+from ..models import (+ CheckoutDiscount,+ CheckoutLineDiscount,+ NotApplicable,+ OrderDiscount,+ OrderLineDiscount,+ Promotion,+ PromotionRule,+)+from .shared import update_line_discount++if TYPE_CHECKING:+ from ...checkout.fetch import CheckoutLineInfo+ from ...order.fetch import EditableOrderLineInfo+ from ...order.models import OrderLine+ from ...product.managers import ProductVariantQueryset+++CatalogueInfo = defaultdict[str, set[Union[int, str]]]+CATALOGUE_FIELDS = ["categories", "collections", "products", "variants"]+++def prepare_promotion_discount_reason(promotion: "Promotion", sale_id: str):+ return f"{'Sale' if promotion.old_sale_id else 'Promotion'}: {sale_id}"+++def get_sale_id(promotion: "Promotion"):+ return (+ graphene.Node.to_global_id("Sale", promotion.old_sale_id)+ if promotion.old_sale_id+ else graphene.Node.to_global_id("Promotion", promotion.id)+ )+++def calculate_discounted_price_for_rules(+ *, price: Money, rules: Iterable["PromotionRule"], currency: str+):+ """Calculate the discounted price for provided rules.++ The discounts from rules summed up and applied to the price.+ """+ total_discount = zero_money(currency)+ for rule in rules:+ discount = rule.get_discount(currency)+ total_discount += price - discount(price)++ return max(price - total_discount, zero_money(currency))+++def calculate_discounted_price_for_promotions(+ *,+ price: Money,+ rules_info_per_variant: dict[int, list[PromotionRuleInfo]],+ channel: "Channel",+ variant_id: int,+) -> Optional[tuple[UUID, Money]]:+ """Return minimum product's price of all prices with promotions applied."""+ applied_discount = None+ rules_info_for_variant = rules_info_per_variant.get(variant_id)+ if rules_info_for_variant:+ applied_discount = get_best_promotion_discount(+ price, rules_info_for_variant, channel+ )+ return applied_discount+++def get_best_promotion_discount(+ price: Money,+ rules_info_for_variant: list[PromotionRuleInfo],+ channel: "Channel",+) -> Optional[tuple[UUID, Money]]:+ """Return the rule with the discount amount for the best promotion.++ The data for the promotion that gives the best saving are returned in the following+ shape:+ (rule_id_1, discount_amount_1)+ """+ available_discounts = []+ for rule_id, discount in get_product_promotion_discounts(+ rules_info=rules_info_for_variant,+ channel=channel,+ ):+ available_discounts.append((rule_id, discount))++ applied_discount = None+ if available_discounts:+ applied_discount = max(+ [+ (rule_id, price - discount(price))+ for rule_id, discount in available_discounts+ ],+ key=lambda x: x[1].amount, # sort over a max discount+ )++ return applied_discount+++def get_product_promotion_discounts(+ *,+ rules_info: list[PromotionRuleInfo],+ channel: "Channel",+) -> Iterator[tuple[UUID, Callable]]:+ """Return rule id, discount value for all rules applicable for given channel."""+ for rule_info in rules_info:+ try:+ yield get_product_discount_on_promotion(rule_info, channel)+ except NotApplicable:+ pass+++def get_product_discount_on_promotion(+ rule_info: PromotionRuleInfo,+ channel: "Channel",+) -> tuple[UUID, Callable]:+ """Return rule id, discount value if rule applied or raise NotApplicable."""+ if channel.id in rule_info.channel_ids:+ return rule_info.rule.id, rule_info.rule.get_discount(channel.currency_code)+ raise NotApplicable("Promotion rule not applicable for this product")+++@overload+def prepare_line_discount_objects_for_catalogue_promotions(+ lines_info: Iterable["CheckoutLineInfo"],+) -> tuple[+ list[dict], list["CheckoutLineDiscount"], list["CheckoutLineDiscount"], list[str]+]: ...+++@overload+def prepare_line_discount_objects_for_catalogue_promotions(+ lines_info: Iterable["EditableOrderLineInfo"],+) -> tuple[+ list[dict], list["OrderLineDiscount"], list["OrderLineDiscount"], list[str]+]: ...+++def prepare_line_discount_objects_for_catalogue_promotions(lines_info):+ line_discounts_to_create_inputs: list[dict] = []+ line_discounts_to_update: list[Union[CheckoutLineDiscount, OrderLineDiscount]] = []+ line_discounts_to_remove: list[Union[CheckoutLineDiscount, OrderLineDiscount]] = []+ updated_fields: list[str] = []++ if not lines_info:+ return++ for line_info in lines_info:+ line = line_info.line++ # get the existing catalogue discount for the line+ discount_to_update = None+ if discounts_to_update := line_info.get_catalogue_discounts():+ discount_to_update = discounts_to_update[0]+ # Line should never have multiple catalogue discounts associated. Before+ # introducing unique_type on discount models, there was such a possibility.+ line_discounts_to_remove.extend(discounts_to_update[1:])++ # manual line discount do not stack with other discounts+ if [+ discount+ for discount in line_info.discounts+ if discount.type == DiscountType.MANUAL+ ]:+ line_discounts_to_remove.extend(discounts_to_update)+ continue++ # check if the line price is discounted by catalogue promotion+ discounted_line = _is_discounted_line_by_catalogue_promotion(+ line_info.channel_listing+ )++ # delete all existing discounts if the line is not discounted or it is a gift+ if not discounted_line or line.is_gift:+ line_discounts_to_remove.extend(discounts_to_update)+ continue++ if line_info.rules_info:+ rule_info = line_info.rules_info[0]+ rule = rule_info.rule+ rule_discount_amount = _get_rule_discount_amount(+ line, rule_info, line_info.channel+ )+ discount_name = get_discount_name(rule, rule_info.promotion)+ translated_name = get_discount_translated_name(rule_info)+ reason = _get_discount_reason(rule)+ if not discount_to_update:+ line_discount_input = {+ "line": line,+ "type": DiscountType.PROMOTION,+ "value_type": rule.reward_value_type,+ "value": rule.reward_value,+ "amount_value": rule_discount_amount,+ "currency": line.currency,+ "name": discount_name,+ "translated_name": translated_name,+ "reason": reason,+ "promotion_rule": rule,+ "unique_type": DiscountType.PROMOTION,+ }+ line_discounts_to_create_inputs.append(line_discount_input)+ else:+ _update_promotion_discount(+ rule,+ rule_info,+ rule_discount_amount,+ discount_to_update,+ updated_fields,+ )+ line_discounts_to_update.append(discount_to_update)+ else:+ # Fallback for unlike mismatch between discount_amount and rules_info+ line_discounts_to_remove.extend(discounts_to_update)++ return (+ line_discounts_to_create_inputs,+ line_discounts_to_update,+ line_discounts_to_remove,+ updated_fields,+ )+++def _is_discounted_line_by_catalogue_promotion(+ variant_channel_listing: "ProductVariantChannelListing",+) -> bool:+ """Return True when the price is discounted by catalogue promotion."""+ price_amount = variant_channel_listing.price_amount+ discounted_price_amount = variant_channel_listing.discounted_price_amount++ if (+ price_amount is None+ or discounted_price_amount is None+ or price_amount == discounted_price_amount+ ):+ return False++ return True+++def _get_rule_discount_amount(+ line: Union["CheckoutLine", "OrderLine"],+ rule_info: "VariantPromotionRuleInfo",+ channel: "Channel",+) -> Decimal:+ """Calculate the discount amount for catalogue promotion rule.++ When the line has overridden price, the discount is applied on the+ new overridden base price.+ """+ variant_listing_promotion_rule = rule_info.variant_listing_promotion_rule+ if not variant_listing_promotion_rule:+ return Decimal("0.0")++ if isinstance(line, CheckoutLine):+ price_override = (+ Money(line.price_override, channel.currency_code)+ if line.price_override is not None+ else None+ )+ else:+ price_override = (+ line.undiscounted_base_unit_price if line.is_price_overridden else None+ )++ if price_override is not None:+ # calculate discount amount on overridden price+ discount = rule_info.rule.get_discount(channel.currency_code)+ discounted_price = discount(price_override)+ discount_amount = (price_override - discounted_price).amount+ else:+ discount_amount = variant_listing_promotion_rule.discount_amount+ return discount_amount * line.quantity+++def get_discount_name(rule: "PromotionRule", promotion: "Promotion"):+ if promotion.name and rule.name:+ return f"{promotion.name}: {rule.name}"+ return rule.name or promotion.name+++def _get_discount_reason(rule: PromotionRule):+ promotion = rule.promotion+ if promotion.old_sale_id:+ return f"Sale: {graphene.Node.to_global_id('Sale', promotion.old_sale_id)}"+ return f"Promotion: {graphene.Node.to_global_id('Promotion', promotion.id)}"+++def get_discount_translated_name(rule_info: "VariantPromotionRuleInfo"):+ promotion_translation = rule_info.promotion_translation+ rule_translation = rule_info.rule_translation+ if promotion_translation and rule_translation:+ return f"{promotion_translation.name}: {rule_translation.name}"+ if rule_translation:+ return rule_translation.name+ if promotion_translation:+ return promotion_translation.name+ return None+++def _update_promotion_discount(+ rule: "PromotionRule",+ rule_info: "VariantPromotionRuleInfo",+ rule_discount_amount: Decimal,+ discount_to_update: Union[+ "CheckoutLineDiscount", "CheckoutDiscount", "OrderLineDiscount", "OrderDiscount"+ ],+ updated_fields: list[str],+):+ discount_name = get_discount_name(rule, rule_info.promotion)+ translated_name = get_discount_translated_name(rule_info)+ reason = prepare_promotion_discount_reason(+ rule_info.promotion, get_sale_id(rule_info.promotion)+ )+ # gift rule has empty reward_value_type+ value_type = rule.reward_value_type or RewardValueType.FIXED+ # gift rule has empty reward_value+ value = rule.reward_value or rule_discount_amount+ update_line_discount(+ rule,+ None,+ discount_name,+ translated_name,+ reason,+ rule_discount_amount,+ value,+ value_type,+ DiscountType.PROMOTION,+ discount_to_update,+ updated_fields,+ )+++def get_best_rule(+ rules: Iterable["PromotionRule"],+ channel: "Channel",+ country: str,+ subtotal: Money,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ RuleDiscount = namedtuple(+ "RuleDiscount", ["rule", "discount_amount", "gift_listing"]+ )+ currency_code = channel.currency_code+ rule_discounts: list[RuleDiscount] = []+ gift_rules = [rule for rule in rules if rule.reward_type == RewardType.GIFT]+ for rule in rules:+ if rule in gift_rules:+ continue+ discount = rule.get_discount(currency_code)+ price = zero_money(currency_code)+ if rule.reward_type == RewardType.SUBTOTAL_DISCOUNT:+ price = subtotal+ discount_amount = (price - discount(price)).amount+ rule_discounts.append(RuleDiscount(rule, discount_amount, None))++ if gift_rules:+ best_gift_rule, gift_listing = _get_best_gift_reward(+ gift_rules, channel, country, database_connection_name+ )+ if best_gift_rule and gift_listing:+ rule_discounts.append(+ RuleDiscount(+ best_gift_rule, gift_listing.discounted_price_amount, gift_listing+ )+ )++ if not rule_discounts:+ return++ best_rule, best_discount_amount, gift_listing = max(+ rule_discounts, key=lambda x: x.discount_amount+ )+ return best_rule, best_discount_amount, gift_listing+++def _get_best_gift_reward(+ rules: Iterable["PromotionRule"],+ channel: "Channel",+ country: str,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+) -> tuple[Optional[PromotionRule], Optional[ProductVariantChannelListing]]:+ rule_ids = [rule.id for rule in rules]+ PromotionRuleGift = PromotionRule.gifts.through+ rule_gifts = PromotionRuleGift.objects.using(database_connection_name).filter(+ promotionrule_id__in=rule_ids+ )+ variants = ProductVariant.objects.using(database_connection_name).filter(+ Exists(+ rule_gifts.values("productvariant_id").filter(+ productvariant_id=OuterRef("id")+ )+ )+ )+ variant_ids_with_insufficient_stock = set()+ if not variants:+ return None, None++ try:+ check_stock_quantity_bulk(+ variants,+ country,+ [1] * variants.count(),+ channel.slug,+ None,+ database_connection_name=database_connection_name,+ )+ except InsufficientStock as error:+ variant_ids_with_insufficient_stock = {+ item.variant.pk for item in error.items if item.variant+ }++ available_variant_ids = (+ set(variants.values_list("id", flat=True)) - variant_ids_with_insufficient_stock+ )++ if not available_variant_ids:+ return None, None++ # check if variant is available for purchase+ available_variant_ids = _get_available_for_purchase_variant_ids(+ available_variant_ids,+ channel,+ database_connection_name=database_connection_name,+ )+ if not available_variant_ids:+ return None, None++ # check variant channel availability+ available_variant_listings = ProductVariantChannelListing.objects.using(+ database_connection_name+ ).filter(+ variant_id__in=available_variant_ids,+ channel_id=channel.id,+ price_amount__isnull=False,+ )+ if not available_variant_listings:+ return None, None++ listing = max(+ list(available_variant_listings),+ # sort over a top price+ key=lambda x: x.discounted_price_amount,+ )+ rule_gift = rule_gifts.filter(productvariant_id=listing.variant_id).first()+ rule = rule_gift.promotionrule if rule_gift else None+ return rule, listing+++def _get_available_for_purchase_variant_ids(+ available_variant_ids: set[int],+ channel: "Channel",+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ today = datetime.datetime.now(pytz.UTC)+ variants = ProductVariant.objects.using(database_connection_name).filter(+ id__in=available_variant_ids+ )+ product_listings = ProductChannelListing.objects.using(+ database_connection_name+ ).filter(+ Exists(variants.filter(product_id=OuterRef("product_id"))),+ available_for_purchase_at__lte=today,+ channel_id=channel.id,+ )+ available_variant_ids = variants.filter(+ Exists(product_listings.filter(product_id=OuterRef("product_id")))+ ).values_list("id", flat=True)+ return set(available_variant_ids)+++@allow_writer()+def delete_gift_line(+ order_or_checkout: Union[Checkout, Order],+ lines_info: Iterable[Union["CheckoutLineInfo", "EditableOrderLineInfo"]],+):+ if gift_line_infos := [line for line in lines_info if line.line.is_gift]:+ order_or_checkout.lines.filter(is_gift=True).delete() # type: ignore[misc]+ for gift_line_info in gift_line_infos:+ lines_info.remove(gift_line_info) # type: ignore[attr-defined]+++def create_gift_line(order_or_checkout: Union[Checkout, Order], variant_id: int):+ defaults = _get_defaults_for_gift_line(order_or_checkout, variant_id)+ line, created = order_or_checkout.lines.get_or_create(+ is_gift=True, defaults=defaults+ )+ if not created:+ fields_to_update = []+ for field, value in defaults.items():+ if getattr(line, field) != value:+ setattr(line, field, value)+ fields_to_update.append(field)+ if fields_to_update:+ line.save(update_fields=fields_to_update)++ return line, created+++def _get_defaults_for_gift_line(+ order_or_checkout: Union[Checkout, Order], variant_id: int+):+ if isinstance(order_or_checkout, Checkout):+ return {+ "variant_id": variant_id,+ "quantity": 1,+ "currency": order_or_checkout.currency,+ }+ else:+ variant = (+ ProductVariant.objects.filter(id=variant_id)+ .select_related("product")+ .only("sku", "product__name")+ .first()+ )+ return {+ "variant_id": variant_id,+ "product_name": variant.product.name if variant else "",+ "product_sku": variant.sku if variant else "",+ "quantity": 1,+ "currency": order_or_checkout.currency,+ "unit_price_net_amount": Decimal(0),+ "unit_price_gross_amount": Decimal(0),+ "total_price_net_amount": Decimal(0),+ "total_price_gross_amount": Decimal(0),+ "is_shipping_required": True,+ "is_gift_card": False,+ }+++def get_variants_to_promotion_rules_map(+ variant_qs: "ProductVariantQueryset",+) -> dict[int, list[PromotionRuleInfo]]:+ """Return map of variant ids to the list of promotion rules that can be applied.++ The data is returned in the following shape:+ {+ variant_id_1: [PromotionRuleInfo_1, PromotionRuleInfo_2, PromotionRuleInfo_3],+ variant_id_2: [PromotionRuleInfo_1]+ }+ """+ rules_info_per_variant: dict[int, list[PromotionRuleInfo]] = defaultdict(list)++ promotions = Promotion.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).active()+ PromotionRuleVariant = PromotionRule.variants.through+ promotion_rule_variants = PromotionRuleVariant.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(Exists(variant_qs.filter(id=OuterRef("productvariant_id"))))++ # fetch rules only for active promotions+ rules = PromotionRule.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(+ Exists(promotions.filter(id=OuterRef("promotion_id"))),+ Exists(promotion_rule_variants.filter(promotionrule_id=OuterRef("pk"))),+ )+ rule_to_channel_ids_map = _get_rule_to_channel_ids_map(rules)+ rules_in_bulk = rules.in_bulk()++ for promotion_rule_variant in promotion_rule_variants.iterator():+ rule_id = promotion_rule_variant.promotionrule_id+ rule = rules_in_bulk.get(rule_id)+ # there is no rule when it is a part of inactive promotion+ if not rule:+ continue+ variant_id = promotion_rule_variant.productvariant_id+ rules_info_per_variant[variant_id].append(+ PromotionRuleInfo(+ rule=rule,+ channel_ids=rule_to_channel_ids_map.get(rule_id, []),+ )+ )++ return rules_info_per_variant+++def fetch_promotion_rules_for_checkout_or_order(+ instance: Union["Checkout", "Order"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ from ...graphql.discount.utils import PredicateObjectType, filter_qs_by_predicate++ with allow_writer():+ # TODO: channel should be loaded using dataloader+ currency = instance.channel.currency_code++ applicable_rules = []+ promotions = Promotion.objects.active()+ rules = (+ PromotionRule.objects.using(database_connection_name)+ .filter(Exists(promotions.filter(id=OuterRef("promotion_id"))))+ .exclude(order_predicate={})+ .prefetch_related("channels")+ )+ rule_to_channel_ids_map = _get_rule_to_channel_ids_map(rules)++ channel_id = instance.channel_id+ qs = instance._meta.model.objects.using(database_connection_name).filter( # type: ignore[attr-defined] # noqa: E501+ pk=instance.pk+ )+ for rule in rules.iterator():+ rule_channel_ids = rule_to_channel_ids_map.get(rule.id, [])+ if channel_id not in rule_channel_ids:+ continue+ predicate_type = (+ PredicateObjectType.CHECKOUT+ if isinstance(instance, Checkout)+ else PredicateObjectType.ORDER+ )+ objects = filter_qs_by_predicate(+ rule.order_predicate,+ qs,+ predicate_type,+ currency,+ )+ if objects.exists():+ applicable_rules.append(rule)++ return applicable_rules+++def _get_rule_to_channel_ids_map(rules: QuerySet):+ rule_to_channel_ids_map = defaultdict(list)+ PromotionRuleChannel = PromotionRule.channels.through+ promotion_rule_channels = PromotionRuleChannel.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(Exists(rules.filter(id=OuterRef("promotionrule_id"))))+ for promotion_rule_channel in promotion_rule_channels:+ rule_id = promotion_rule_channel.promotionrule_id+ channel_id = promotion_rule_channel.channel_id+ rule_to_channel_ids_map[rule_id].append(channel_id)+ return rule_to_channel_ids_map+++def get_current_products_for_rules(rules: "QuerySet[PromotionRule]"):+ """Get currently assigned products to promotions.++ Collect all products for variants that are assigned to promotion rules.+ """+ PromotionRuleVariant = PromotionRule.variants.through+ rule_variants = PromotionRuleVariant.objects.filter(+ Exists(rules.filter(pk=OuterRef("promotionrule_id")))+ )+ variants = ProductVariant.objects.filter(+ Exists(rule_variants.filter(productvariant_id=OuterRef("id")))+ )+ return Product.objects.filter(Exists(variants.filter(product_id=OuterRef("id"))))+++def update_rule_variant_relation(+ rules: QuerySet[PromotionRule], new_rules_variants: list+):+ """Update PromotionRule - ProductVariant relation.++ Deletes relations, which are not valid anymore.+ Adds new relations, if they don't exist already.+ `new_rules_variants` is a list of PromotionRuleVariant objects.+ """+ with transaction.atomic():+ PromotionRuleVariant = PromotionRule.variants.through+ existing_rules_variants = PromotionRuleVariant.objects.filter(+ Exists(rules.filter(pk=OuterRef("promotionrule_id")))+ ).all()+ new_rule_variant_set = set(+ (rv.promotionrule_id, rv.productvariant_id) for rv in new_rules_variants+ )+ existing_rule_variant_set = set(+ (rv.promotionrule_id, rv.productvariant_id)+ for rv in existing_rules_variants+ )++ # Clear invalid variants assigned to promotion rules+ rule_variant_to_delete_ids = [+ rv.id+ for rv in existing_rules_variants+ if (rv.promotionrule_id, rv.productvariant_id) not in new_rule_variant_set+ ]+ PromotionRuleVariant.objects.filter(id__in=rule_variant_to_delete_ids).delete()++ # Assign new variants to promotion rules+ rules_variants_to_add = [+ rv+ for rv in new_rules_variants+ if (rv.promotionrule_id, rv.productvariant_id)+ not in existing_rule_variant_set+ ]+ PromotionRuleVariant.objects.bulk_create(+ rules_variants_to_add, ignore_conflicts=True+ )+++def create_discount_objects_for_order_promotions(+ order_or_checkout: Union[Checkout, Order],+ lines_info: Union[Iterable["EditableOrderLineInfo"], Iterable["CheckoutLineInfo"]],+ subtotal: Money,+ channel: "Channel",+ country: str,+ *,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+):+ """Create discount object for order promotions.++ If the best promotion is gift promotion, new gift line is created.+ """+ gift_promotion_applied = False+ discount_object = None+ rules = fetch_promotion_rules_for_checkout_or_order(+ order_or_checkout, database_connection_name+ )+ rule_data = get_best_rule(+ rules=rules,+ channel=channel,+ country=country,+ subtotal=subtotal,+ database_connection_name=database_connection_name,+ )+ if not rule_data:+ return gift_promotion_applied, discount_object++ best_rule, best_discount_amount, gift_listing = rule_data+ promotion = best_rule.promotion+ currency = channel.currency_code+ translation_language_code = order_or_checkout.language_code+ promotion_translation, rule_translation = get_rule_translations(+ promotion, best_rule, translation_language_code+ )+ rule_info = VariantPromotionRuleInfo(+ rule=best_rule,+ variant_listing_promotion_rule=None,+ promotion=best_rule.promotion,+ promotion_translation=promotion_translation,+ rule_translation=rule_translation,+ )+ # gift rule has empty reward_value and reward_value_type+ value_type = best_rule.reward_value_type or RewardValueType.FIXED+ amount_value = gift_listing.price_amount if gift_listing else best_discount_amount+ value = best_rule.reward_value or amount_value+ discount_object_defaults = {+ "promotion_rule": best_rule,+ "value_type": value_type,+ "value": value,+ "amount_value": amount_value,+ "currency": currency,+ "name": get_discount_name(best_rule, promotion),+ "translated_name": get_discount_translated_name(rule_info),+ "reason": prepare_promotion_discount_reason(promotion, get_sale_id(promotion)),+ }+ if gift_listing:+ _handle_gift_reward(+ order_or_checkout,+ lines_info,+ gift_listing,+ channel,+ discount_object_defaults,+ rule_info,+ )+ gift_promotion_applied = True+ else:+ discount_object = _handle_order_promotion(+ order_or_checkout,+ lines_info,+ discount_object_defaults,+ rule_info,+ )+ return gift_promotion_applied, discount_object+++@allow_writer()+def _handle_order_promotion(+ order_or_checkout: Union[Order, Checkout],+ lines_info: Union[Iterable["EditableOrderLineInfo"], Iterable["CheckoutLineInfo"]],+ discount_object_defaults: dict,+ rule_info: VariantPromotionRuleInfo,+):+ discount_object, created = order_or_checkout.discounts.get_or_create(+ type=DiscountType.ORDER_PROMOTION,+ defaults=discount_object_defaults,+ )+ discount_amount = discount_object_defaults["amount_value"]++ if not created:+ fields_to_update: list[str] = []+ _update_promotion_discount(+ discount_object_defaults["promotion_rule"],+ rule_info,+ discount_amount,+ discount_object,+ fields_to_update,+ )+ if fields_to_update:+ discount_object.save(update_fields=fields_to_update)++ delete_gift_line(order_or_checkout, lines_info)+ return discount_object+++@allow_writer()+def _handle_gift_reward(+ order_or_checkout: Union[Order, Checkout],+ lines_info: Union[Iterable["EditableOrderLineInfo"], Iterable["CheckoutLineInfo"]],+ gift_listing: ProductVariantChannelListing,+ channel: "Channel",+ discount_object_defaults: dict,+ rule_info: VariantPromotionRuleInfo,+):+ discount_model = (+ CheckoutLineDiscount+ if isinstance(order_or_checkout, Checkout)+ else OrderLineDiscount+ )+ with transaction.atomic():+ line, line_created = create_gift_line(+ order_or_checkout, gift_listing.variant_id+ )+ (+ line_discount,+ discount_created,+ ) = discount_model.objects.get_or_create( # type: ignore[attr-defined]+ type=DiscountType.ORDER_PROMOTION,+ line=line,+ defaults=discount_object_defaults,+ )++ if not discount_created:+ fields_to_update = []+ if line_discount.line_id != line.id:+ line_discount.line = line+ fields_to_update.append("line_id")+ _update_promotion_discount(+ discount_object_defaults["promotion_rule"],+ rule_info,+ discount_object_defaults["amount_value"],+ line_discount,+ fields_to_update,+ )+ if fields_to_update:+ line_discount.save(update_fields=fields_to_update)++ if line_created:+ variant = gift_listing.variant+ init_values = {+ "line": line,+ "variant": variant,+ "product": variant.product,+ "product_type": variant.product.product_type,+ "collections": [],+ "channel_listing": gift_listing,+ "discounts": [line_discount],+ "rules_info": [rule_info],+ "channel": channel,+ "voucher": None,+ "voucher_code": None,+ }+ if isinstance(order_or_checkout, Checkout):+ gift_line_info = CheckoutLineInfo(**init_values)+ else:+ gift_line_info = EditableOrderLineInfo(**init_values) # type: ignore+ lines_info.append(gift_line_info) # type: ignore+ else:+ line_info = next(+ line_info for line_info in lines_info if line_info.line.pk == line.id+ )+ line_info.line = line+ line_info.discounts = [line_discount]+++def get_active_catalogue_promotion_rules(+ allow_replica: bool = False,+) -> "QuerySet[PromotionRule]":+ promotions = Promotion.objects.active().filter(type=PromotionType.CATALOGUE)+ if allow_replica:+ promotions = promotions.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ rules = (+ PromotionRule.objects.order_by("id")+ .filter(+ Exists(promotions.filter(id=OuterRef("promotion_id"))),+ )+ .exclude(catalogue_predicate={})+ )+ if allow_replica:+ rules = rules.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ return rules+++def mark_active_catalogue_promotion_rules_as_dirty(channel_ids: Iterable[int]):+ """Force promotion rule to recalculate.++ The rules which are marked as dirty, will be recalculated in background.+ Products related to these rules will be recalculated as well.+ """++ if not channel_ids:+ return++ rules = get_active_catalogue_promotion_rules()+ PromotionRuleChannel = PromotionRule.channels.through+ promotion_rules = PromotionRuleChannel.objects.filter(channel_id__in=channel_ids)+ rule_ids = rules.filter(+ Exists(promotion_rules.filter(promotionrule_id=OuterRef("id")))+ ).values_list("id", flat=True)++ with transaction.atomic():+ rule_ids_to_update = list(+ PromotionRule.objects.select_for_update(of=("self",))+ .filter(id__in=rule_ids, variants_dirty=False)+ .order_by("pk")+ .values_list("id", flat=True)+ )+ PromotionRule.objects.filter(id__in=rule_ids_to_update).update(+ variants_dirty=True+ )+++def mark_catalogue_promotion_rules_as_dirty(promotion_pks: Iterable[UUID]):+ """Mark rules for promotions as dirty.++ The rules which are marked as dirty, will be recalculated in background.+ Products related to these rules will be recalculated as well.+ """+ if not promotion_pks:+ return+ with transaction.atomic():+ rule_ids_to_update = list(+ PromotionRule.objects.select_for_update(of=(["self"]))+ .filter(promotion_id__in=promotion_pks, variants_dirty=False)+ .order_by("pk")+ .values_list("id", flat=True)+ )+ PromotionRule.objects.filter(id__in=rule_ids_to_update).update(+ variants_dirty=True+ )diff --git a/saleor/discount/utils/shared.py b/saleor/discount/utils/shared.pynew file mode 100644index 0000000000..347f559e30--- /dev/null+++ b/saleor/discount/utils/shared.py@@ -0,0 +1,81 @@+from collections import defaultdict+from decimal import Decimal+from typing import TYPE_CHECKING, Optional, Union++from ..models import (+ CheckoutDiscount,+ CheckoutLineDiscount,+ OrderDiscount,+ OrderLineDiscount,+ PromotionRule,+ Voucher,+)++if TYPE_CHECKING:+ from ..models import Voucher+++def update_line_discount(+ rule: Optional["PromotionRule"],+ voucher: Optional["Voucher"],+ discount_name: str,+ translated_name: str,+ discount_reason: str,+ discount_amount: Decimal,+ value: Decimal,+ value_type: str,+ unique_type: str,+ discount_to_update: Union[+ "CheckoutLineDiscount", "CheckoutDiscount", "OrderLineDiscount", "OrderDiscount"+ ],+ updated_fields: list[str],+):+ if voucher and discount_to_update.voucher_id != voucher.id:+ discount_to_update.voucher_id = voucher.id+ updated_fields.append("voucher_id")+ if rule and discount_to_update.promotion_rule_id != rule.id:+ discount_to_update.promotion_rule_id = rule.id+ updated_fields.append("promotion_rule_id")+ if discount_to_update.value_type != value_type:+ discount_to_update.value_type = value_type+ updated_fields.append("value_type")+ if discount_to_update.value != value:+ discount_to_update.value = value+ updated_fields.append("value")+ if discount_to_update.amount_value != discount_amount:+ discount_to_update.amount_value = discount_amount+ updated_fields.append("amount_value")+ if discount_to_update.name != discount_name:+ discount_to_update.name = discount_name+ updated_fields.append("name")+ if discount_to_update.translated_name != translated_name:+ discount_to_update.translated_name = translated_name+ updated_fields.append("translated_name")++ if discount_to_update.reason != discount_reason:+ discount_to_update.reason = discount_reason+ updated_fields.append("reason")+ if hasattr(discount_to_update, "unique_type"):+ if discount_to_update.unique_type is None:+ discount_to_update.unique_type = unique_type+ updated_fields.append("unique_type")+++def update_line_info_cached_discounts(+ lines_info, new_line_discounts, updated_discounts, line_discount_ids_to_remove+):+ if not any([new_line_discounts, updated_discounts, line_discount_ids_to_remove]):+ return++ line_id_line_discounts_map = defaultdict(list)+ for line_discount in new_line_discounts:+ line_id_line_discounts_map[line_discount.line_id].append(line_discount)++ for line_info in lines_info:+ line_info.discounts = [+ discount+ for discount in line_info.discounts+ if discount.id not in line_discount_ids_to_remove+ ]+ if discount := line_id_line_discounts_map.get(line_info.line.id):+ line_info.discounts.extend(discount)diff --git a/saleor/discount/utils/voucher.py b/saleor/discount/utils/voucher.pynew file mode 100644index 0000000000..2827c4ed24--- /dev/null+++ b/saleor/discount/utils/voucher.py@@ -0,0 +1,448 @@+from collections.abc import Iterable+from decimal import Decimal+from typing import TYPE_CHECKING, Optional, cast++from django.db.models import Exists, F, OuterRef+from django.utils import timezone+from prices import Money++from ...channel.models import Channel+from ...core.taxes import zero_money+from ...core.utils.promo_code import InvalidPromoCode+from ...order.models import Order+from .. import (+ DiscountType,+ VoucherType,+)+from ..models import (+ DiscountValueType,+ NotApplicable,+ OrderLineDiscount,+ Voucher,+ VoucherCode,+ VoucherCustomer,+)+from .shared import update_line_discount++if TYPE_CHECKING:+ from ...account.models import User+ from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo+ from ...core.pricing.interface import LineInfo+ from ...order.fetch import EditableOrderLineInfo+ from ...order.models import OrderLine+ from ...plugins.manager import PluginsManager+ from ..interface import VoucherInfo+ from ..models import Voucher+++def is_order_level_voucher(voucher: Optional[Voucher]):+ return bool(+ voucher+ and voucher.type == VoucherType.ENTIRE_ORDER+ and not voucher.apply_once_per_order+ )+++def increase_voucher_usage(+ voucher: "Voucher",+ code: "VoucherCode",+ customer_email: Optional[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") + 1+ code.save(update_fields=["used"])+++def decrease_voucher_code_usage_value(code: "VoucherCode") -> None:+ """Decrease voucher code uses by 1."""+ code.used = F("used") - 1+ code.save(update_fields=["used"])+++def deactivate_voucher_code(code: "VoucherCode") -> None:+ """Mark voucher code as used."""+ code.is_active = False+ code.save(update_fields=["is_active"])+++def activate_voucher_code(code: "VoucherCode") -> None:+ """Mark voucher code as unused."""+ code.is_active = True+ code.save(update_fields=["is_active"])+++def add_voucher_usage_by_customer(+ code: "VoucherCode", customer_email: Optional[str]+) -> None:+ if not customer_email:+ raise NotApplicable("Unable to apply voucher as customer details are missing.")++ _, created = VoucherCustomer.objects.get_or_create(+ voucher_code=code, customer_email=customer_email+ )+ if not created:+ raise NotApplicable("This offer is only valid once per customer.")+++def remove_voucher_usage_by_customer(code: "VoucherCode", customer_email: str) -> None:+ voucher_customer = VoucherCustomer.objects.filter(+ voucher_code=code, customer_email=customer_email+ )+ if voucher_customer:+ voucher_customer.delete()+++def release_voucher_code_usage(+ code: Optional["VoucherCode"],+ voucher: Optional["Voucher"],+ user_email: Optional[str],+):+ if not code:+ return+ if voucher and voucher.usage_limit:+ decrease_voucher_code_usage_value(code)+ if voucher and voucher.single_use:+ activate_voucher_code(code)+ if user_email:+ remove_voucher_usage_by_customer(code, user_email)+++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 get_active_voucher_code(voucher, channel_slug):+ """Return an active VoucherCode instance.++ This method along with `Voucher.code` should be removed in Saleor 4.0.+ """++ voucher_queryset = Voucher.objects.active_in_channel(timezone.now(), channel_slug)+ if not voucher_queryset.filter(pk=voucher.pk).exists():+ raise InvalidPromoCode()+ voucher_code = VoucherCode.objects.filter(voucher=voucher, is_active=True).first()+ if not voucher_code:+ raise InvalidPromoCode()+ return voucher_code+++def apply_voucher_to_line(+ voucher_info: "VoucherInfo",+ lines_info: Iterable["LineInfo"],+):+ """Attach voucher to valid checkout or order lines info.++ Apply a voucher to checkout/order line info when the voucher has the type+ SPECIFIC_PRODUCTS or is applied only to the cheapest item.+ """+ voucher = voucher_info.voucher+ discounted_lines_by_voucher: list[LineInfo] = []+ lines_included_in_discount = lines_info+ if voucher.type == VoucherType.SPECIFIC_PRODUCT:+ discounted_lines_by_voucher.extend(+ get_discounted_lines(lines_info, voucher_info)+ )+ lines_included_in_discount = discounted_lines_by_voucher+ if voucher.apply_once_per_order:+ if cheapest_line := _get_the_cheapest_line(lines_included_in_discount):+ discounted_lines_by_voucher = [cheapest_line]+ for line_info in lines_info:+ if line_info in discounted_lines_by_voucher:+ line_info.voucher = voucher+ line_info.voucher_code = voucher_info.voucher_code+++def get_discounted_lines(+ lines: Iterable["LineInfo"], voucher_info: "VoucherInfo"+) -> Iterable["LineInfo"]:+ discounted_lines = []+ if (+ voucher_info.product_pks+ or voucher_info.collection_pks+ or voucher_info.category_pks+ or voucher_info.variant_pks+ ):+ for line_info in lines:+ if line_info.line.is_gift:+ continue+ line_variant = line_info.variant+ line_product = line_info.product+ if not line_variant or not line_product:+ continue+ line_category = line_product.category+ line_collections = set(+ [collection.pk for collection in line_info.collections]+ )+ if line_info.variant and (+ line_variant.pk in voucher_info.variant_pks+ or line_product.pk in voucher_info.product_pks+ or line_category+ and line_category.pk in voucher_info.category_pks+ or line_collections.intersection(voucher_info.collection_pks)+ ):+ discounted_lines.append(line_info)+ else:+ # If there's no discounted products, collections or categories,+ # it means that all products are discounted+ discounted_lines.extend(lines)+ return discounted_lines+++def _get_the_cheapest_line(+ lines_info: Optional[Iterable["LineInfo"]],+) -> Optional["LineInfo"]:+ if not lines_info:+ return None+ return min(+ lines_info, key=lambda line_info: line_info.channel_listing.discounted_price+ )+++def validate_voucher_for_checkout(+ manager: "PluginsManager",+ voucher: "Voucher",+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+):+ from ...checkout import base_calculations+ from ...checkout.utils import calculate_checkout_quantity++ quantity = calculate_checkout_quantity(lines)+ subtotal = base_calculations.base_checkout_subtotal(+ lines,+ checkout_info.channel,+ checkout_info.checkout.currency,+ )++ customer_email = cast(str, checkout_info.get_customer_email())+ validate_voucher(+ voucher,+ subtotal,+ quantity,+ customer_email,+ checkout_info.channel,+ checkout_info.user,+ )+++def validate_voucher_in_order(+ order: "Order", lines: Iterable["OrderLine"], channel: "Channel"+):+ if not order.voucher:+ return++ from ...order.utils import get_total_quantity++ subtotal = order.subtotal+ quantity = get_total_quantity(lines)+ customer_email = order.get_customer_email()+ tax_configuration = channel.tax_configuration+ prices_entered_with_tax = tax_configuration.prices_entered_with_tax+ value = subtotal.gross if prices_entered_with_tax else subtotal.net++ validate_voucher(+ order.voucher, value, quantity, customer_email, channel, order.user+ )+++def validate_voucher(+ voucher: "Voucher",+ total_price: Money,+ quantity: int,+ customer_email: str,+ channel: Channel,+ customer: Optional["User"],+) -> None:+ voucher.validate_min_spent(total_price, channel)+ voucher.validate_min_checkout_items_quantity(quantity)+ if voucher.apply_once_per_customer:+ voucher.validate_once_per_customer(customer_email)+ if voucher.only_for_staff:+ voucher.validate_only_for_staff(customer)+++def get_products_voucher_discount(+ voucher: "Voucher", prices: Iterable[Money], channel: Channel+) -> Money:+ """Calculate discount value for a voucher of product or category type."""+ if voucher.apply_once_per_order:+ return voucher.get_discount_amount_for(min(prices), channel)+ discounts = (voucher.get_discount_amount_for(price, channel) for price in prices)+ total_amount = sum(discounts, zero_money(channel.currency_code))+ return total_amount+++def create_or_update_line_discount_objects_from_voucher(order, lines_info):+ """Create or update line discount object for voucher applied on lines.++ The LineDiscount object is created for each line with voucher applied.+ Only `SPECIFIC_PRODUCT` and `apply_once_per_order` voucher types are applied.++ """+ # FIXME: temporary - create_order_line_discount_objects should be moved to shared+ from .order import create_order_line_discount_objects++ discount_data = prepare_line_discount_objects_for_voucher(lines_info)+ modified_lines_info = create_order_line_discount_objects(lines_info, discount_data)+ # base unit price must reflect all actual line voucher discounts+ if modified_lines_info:+ _reduce_base_unit_price_for_voucher_discount(modified_lines_info)+++# TODO (SHOPX-912): share the method with checkout+def prepare_line_discount_objects_for_voucher(+ lines_info: Iterable["EditableOrderLineInfo"],+):+ line_discounts_to_create_inputs: list[dict] = []+ line_discounts_to_update: list[OrderLineDiscount] = []+ line_discounts_to_remove: list[OrderLineDiscount] = []+ updated_fields: list[str] = []++ if not lines_info:+ return++ for line_info in lines_info:+ line = line_info.line+ total_price = line.base_unit_price * line.quantity+ discount_amount = calculate_line_discount_amount_from_voucher(+ line_info, total_price+ )+ # only one voucher can be applied+ discount_to_update = None+ if discounts_to_update := line_info.get_voucher_discounts():+ discount_to_update = discounts_to_update[0]++ if not discount_amount or line.is_gift:+ if discount_to_update:+ line_discounts_to_remove.append(discount_to_update)+ continue++ discount_amount = discount_amount.amount+ discount_reason = f"Voucher code: {line_info.voucher_code}"+ voucher = cast(Voucher, line_info.voucher)+ discount_name = f"{voucher.name}"+ if discount_to_update:+ update_line_discount(+ None,+ voucher,+ discount_name,+ # TODO (SHOPX-914): set translated voucher name+ "",+ discount_reason,+ discount_amount,+ # TODO (SHOPX-914): should be taken from voucher value_type and value+ discount_amount,+ DiscountValueType.FIXED,+ DiscountType.VOUCHER,+ discount_to_update,+ updated_fields,+ )+ line_discounts_to_update.append(discount_to_update)+ else:+ line_discount_input = {+ "line": line,+ "type": DiscountType.VOUCHER,+ # TODO (SHOPX-914): should be taken from voucher value_type and value+ "value_type": DiscountValueType.FIXED,+ "value": discount_amount,+ "amount_value": discount_amount,+ "currency": line.currency,+ "name": discount_name,+ "translated_name": None,+ "reason": discount_reason,+ "voucher": line_info.voucher,+ "unique_type": DiscountType.VOUCHER,+ }+ line_discounts_to_create_inputs.append(line_discount_input)++ return (+ line_discounts_to_create_inputs,+ line_discounts_to_update,+ line_discounts_to_remove,+ updated_fields,+ )+++def calculate_line_discount_amount_from_voucher(+ line_info: "LineInfo", total_price: Money+) -> Money:+ """Calculate discount amount for voucher applied on line.++ Included vouchers: `SPECIFIC_PRODUCT` and `apply_once_per_order`.++ Args:+ line_info: Order/Checkout line data.+ total_price: Total price of the line, should be already reduced by+ catalogue discounts if any applied.++ """+ if not line_info.voucher:+ return zero_money(total_price.currency)++ channel = line_info.channel+ quantity = line_info.line.quantity+ if not line_info.voucher.apply_once_per_order:+ if line_info.voucher.discount_value_type == DiscountValueType.PERCENTAGE:+ voucher_discount_amount = line_info.voucher.get_discount_amount_for(+ total_price, channel=channel+ )+ discount_amount = min(voucher_discount_amount, total_price)+ else:+ unit_price = total_price / quantity+ voucher_unit_discount_amount = line_info.voucher.get_discount_amount_for(+ unit_price, channel=channel+ )+ discount_amount = min(+ voucher_unit_discount_amount * quantity,+ total_price,+ )+ else:+ unit_price = total_price / quantity+ voucher_unit_discount_amount = line_info.voucher.get_discount_amount_for(+ unit_price, channel=channel+ )+ discount_amount = min(voucher_unit_discount_amount, unit_price)+ return discount_amount+++def _reduce_base_unit_price_for_voucher_discount(+ lines_info: Iterable["EditableOrderLineInfo"],+):+ for line_info in lines_info:+ line = line_info.line+ base_unit_price = line.base_unit_price_amount+ for discount in line_info.get_voucher_discounts():+ base_unit_price -= discount.amount_value / line.quantity+ line.base_unit_price_amount = max(base_unit_price, Decimal(0))diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex 4c5e27c37d..8905b1f3e5 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -22,7 +22,7 @@ from ...checkout.problems import (from ...core.db.connection import allow_writer_in_contextfrom ...discount import VoucherTypefrom ...discount.interface import VariantPromotionRuleInfo-from ...discount.utils import apply_voucher_to_line+from ...discount.utils.voucher import apply_voucher_to_linefrom ...payment.models import TransactionItemfrom ...product.models import ProductChannelListingfrom ...warehouse.models import Stockdiff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex c39a3a2d83..0edb9b1ea2 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -33,7 +33,7 @@ from ....checkout.utils import (from ....core.exceptions import InsufficientStock, PermissionDeniedfrom ....discount import DiscountType, DiscountValueTypefrom ....discount.models import CheckoutLineDiscount, PromotionRule-from ....discount.utils import (+from ....discount.utils.promotion import (create_gift_line,fetch_promotion_rules_for_checkout_or_order,get_best_rule,diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex d8da000fd7..6eefbd6eb4 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -1297,7 +1297,7 @@ def test_add_checkout_lines_gift_discount_applies(}# when- with django_assert_num_queries(113):+ with django_assert_num_queries(112):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# thendiff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.pyindex 97306790d0..5597d5275f 100644--- a/saleor/graphql/core/types/taxes.py+++ b/saleor/graphql/core/types/taxes.py@@ -8,7 +8,7 @@ from ....checkout import base_calculationsfrom ....checkout.models import Checkout, CheckoutLinefrom ....core.prices import quantize_pricefrom ....discount import DiscountType-from ....discount.utils import is_order_level_voucher+from ....discount.utils.voucher import is_order_level_voucherfrom ....order.models import Order, OrderLinefrom ....order.utils import get_order_countryfrom ....tax.utils import get_charge_taxesdiff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_update.pyindex 67451e3056..0ee640b08c 100644--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py@@ -5,7 +5,7 @@ from django.core.exceptions import ValidationErrorfrom django.db import transactionfrom .....discount import PromotionType, events, models-from .....discount.utils import get_current_products_for_rules+from .....discount.utils.promotion import get_current_products_for_rulesfrom .....permission.enums import DiscountPermissionsfrom .....product.utils.product import mark_products_in_channels_as_dirtyfrom .....webhook.event_types import WebhookEventAsyncTypediff --git a/saleor/graphql/discount/mutations/promotion/promotion_update.py b/saleor/graphql/discount/mutations/promotion/promotion_update.pyindex 63d8db9b41..592d2d2f4c 100644--- a/saleor/graphql/discount/mutations/promotion/promotion_update.py+++ b/saleor/graphql/discount/mutations/promotion/promotion_update.py@@ -7,7 +7,7 @@ from django.core.exceptions import ValidationErrorfrom django.db import transactionfrom .....discount import PromotionType, events, models-from .....discount.utils import mark_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import DiscountPermissionsfrom .....plugins.manager import PluginsManagerfrom .....webhook.event_types import WebhookEventAsyncTypediff --git a/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py b/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.pyindex e335b8ebff..504de252d2 100644--- a/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py+++ b/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py@@ -10,7 +10,7 @@ from .....core.tracing import traced_atomic_transactionfrom .....discount import DiscountValueTypefrom .....discount.error_codes import DiscountErrorCodefrom .....discount.models import Promotion, PromotionRule-from .....discount.utils import mark_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import DiscountPermissionsfrom .....product.utils.product import mark_products_in_channels_as_dirtyfrom ....channel import ChannelContextdiff --git a/saleor/graphql/discount/mutations/sale/sale_create.py b/saleor/graphql/discount/mutations/sale/sale_create.pyindex 9130d3df18..2487bf736b 100644--- a/saleor/graphql/discount/mutations/sale/sale_create.py+++ b/saleor/graphql/discount/mutations/sale/sale_create.py@@ -8,7 +8,7 @@ from .....core.tracing import traced_atomic_transactionfrom .....discount import PromotionType, modelsfrom .....discount.error_codes import DiscountErrorCodefrom .....discount.models import Promotion-from .....discount.utils import mark_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import DiscountPermissionsfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....channel import ChannelContextdiff --git a/saleor/graphql/discount/mutations/sale/sale_update.py b/saleor/graphql/discount/mutations/sale/sale_update.pyindex fffa4c6458..68c147ef77 100644--- a/saleor/graphql/discount/mutations/sale/sale_update.py+++ b/saleor/graphql/discount/mutations/sale/sale_update.py@@ -8,7 +8,7 @@ from django.db.models import Exists, OuterReffrom .....core.tracing import traced_atomic_transactionfrom .....discount import modelsfrom .....discount.error_codes import DiscountErrorCode-from .....discount.utils import CATALOGUE_FIELDS+from .....discount.utils.promotion import CATALOGUE_FIELDSfrom .....permission.enums import DiscountPermissionsfrom .....product import models as product_modelsfrom .....product.utils.product import mark_products_in_channels_as_dirtydiff --git a/saleor/graphql/discount/mutations/utils.py b/saleor/graphql/discount/mutations/utils.pyindex ed69f6dc36..55e2a9b30a 100644--- a/saleor/graphql/discount/mutations/utils.py+++ b/saleor/graphql/discount/mutations/utils.py@@ -5,7 +5,7 @@ from django.db.models import QuerySetfrom ....discount import PromotionTypefrom ....discount.models import Promotion, PromotionRule-from ....discount.utils import CatalogueInfo, update_rule_variant_relation+from ....discount.utils.promotion import CatalogueInfo, update_rule_variant_relationfrom ....product.models import ProductVariantCATALOGUE_FIELD_TO_TYPE_NAME = {diff --git a/saleor/graphql/discount/utils.py b/saleor/graphql/discount/utils.pyindex cc983aa8ac..97471ef0fb 100644--- a/saleor/graphql/discount/utils.py+++ b/saleor/graphql/discount/utils.py@@ -10,7 +10,7 @@ from graphene.utils.str_converters import to_snake_casefrom ...checkout.models import Checkoutfrom ...discount.models import Promotion, PromotionRule-from ...discount.utils import update_rule_variant_relation+from ...discount.utils.promotion import update_rule_variant_relationfrom ...order.models import Orderfrom ...product.managers import ProductsQueryset, ProductVariantQuerysetfrom ...product.models import (diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex 8c78e9fe33..773e63b334 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -10,7 +10,7 @@ from ....core.postgres import FlatConcatSearchVectorfrom ....core.taxes import zero_taxed_moneyfrom ....core.tracing import traced_atomic_transactionfrom ....discount.models import VoucherCode-from ....discount.utils import add_voucher_usage_by_customer+from ....discount.utils.voucher import add_voucher_usage_by_customerfrom ....order import OrderStatus, modelsfrom ....order.actions import order_createdfrom ....order.calculations import fetch_order_prices_if_expireddiff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex 3912c5529c..5e19174c5a 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -10,7 +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 (+from ....discount.utils.voucher import (get_active_voucher_code,get_voucher_code_instance,increase_voucher_usage,diff --git a/saleor/graphql/order/mutations/draft_order_delete.py b/saleor/graphql/order/mutations/draft_order_delete.pyindex a89522372a..3e607a7aae 100644--- a/saleor/graphql/order/mutations/draft_order_delete.py+++ b/saleor/graphql/order/mutations/draft_order_delete.py@@ -3,7 +3,7 @@ from django.core.exceptions import ValidationErrorfrom ....core.tracing import traced_atomic_transactionfrom ....discount.models import VoucherCode-from ....discount.utils import release_voucher_code_usage+from ....discount.utils.voucher import release_voucher_code_usagefrom ....order import OrderStatus, modelsfrom ....order.error_codes import OrderErrorCodefrom ....permission.enums import OrderPermissionsdiff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.pyindex 7e8303375d..1cf6a68665 100644--- a/saleor/graphql/order/utils.py+++ b/saleor/graphql/order/utils.py@@ -10,7 +10,7 @@ from django.core.exceptions import ValidationErrorfrom ...core.exceptions import InsufficientStockfrom ...discount.interface import VariantPromotionRuleInfofrom ...discount.models import NotApplicable-from ...discount.utils import validate_voucher_in_order+from ...discount.utils.voucher import validate_voucher_in_orderfrom ...order.error_codes import OrderErrorCodefrom ...order.utils import (get_total_quantity,diff --git a/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py b/saleor/graphql/product/bulk_mutations/collection_bulk_delete.pyindex 4f27fecf86..c18525d4bb 100644--- a/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py+++ b/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py@@ -1,7 +1,7 @@import graphenefrom django.db.models import Exists, OuterRef-from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....product.models import ProductChannelListingdiff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.pyindex 81ab665335..bdd9bf64c4 100644--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py@@ -15,7 +15,7 @@ from ....core.tracing import traced_atomic_transactionfrom ....core.utils import prepare_unique_slugfrom ....core.utils.editorjs import clean_editor_jsfrom ....core.utils.validators import get_oembed_data-from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom ....permission.enums import ProductPermissionsfrom ....product import ProductMediaTypes, modelsfrom ....product.error_codes import ProductBulkCreateErrorCodediff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.pyindex 49a18ffc3b..917b41534e 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py@@ -9,7 +9,7 @@ from graphene.utils.str_converters import to_camel_casefrom ....attribute import AttributeTypefrom ....core.tracing import traced_atomic_transaction-from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....product.error_codes import ProductVariantBulkErrorCodediff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.pyindex 60a3e434f0..baf9b441d9 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py@@ -10,7 +10,7 @@ from ....attribute import AttributeInputTypefrom ....attribute import models as attribute_modelsfrom ....core.postgres import FlatConcatSearchVectorfrom ....core.tracing import traced_atomic_transaction-from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom ....order import events as order_eventsfrom ....order import models as order_modelsfrom ....order.tasks import recalculate_orders_taskdiff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.pyindex 7a4824d644..08db571a23 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py@@ -8,7 +8,7 @@ from django.utils import timezonefrom graphene.utils.str_converters import to_camel_casefrom ....core.tracing import traced_atomic_transaction-from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....product.error_codes import ProductErrorCode, ProductVariantBulkErrorCodediff --git a/saleor/graphql/product/mutations/category/category_update.py b/saleor/graphql/product/mutations/category/category_update.pyindex 7a2316d444..0deab54372 100644--- a/saleor/graphql/product/mutations/category/category_update.py+++ b/saleor/graphql/product/mutations/category/category_update.py@@ -1,7 +1,7 @@import graphenefrom django.db.models import Exists, OuterRef-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....thumbnail import models as thumbnail_modelsdiff --git a/saleor/graphql/product/mutations/collection/collection_add_products.py b/saleor/graphql/product/mutations/collection/collection_add_products.pyindex 2eb61c9ad0..e1c5b498cd 100644--- a/saleor/graphql/product/mutations/collection/collection_add_products.py+++ b/saleor/graphql/product/mutations/collection/collection_add_products.py@@ -2,7 +2,7 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom .....core.tracing import traced_atomic_transaction-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....product.error_codes import CollectionErrorCodediff --git a/saleor/graphql/product/mutations/collection/collection_create.py b/saleor/graphql/product/mutations/collection/collection_create.pyindex 46ad21f627..0df97a8ec3 100644--- a/saleor/graphql/product/mutations/collection/collection_create.py+++ b/saleor/graphql/product/mutations/collection/collection_create.py@@ -5,7 +5,7 @@ import pytzfrom django.core.exceptions import ValidationErrorfrom .....core.utils.date_time import convert_to_utc_date_time-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....product.error_codes import CollectionErrorCodediff --git a/saleor/graphql/product/mutations/collection/collection_delete.py b/saleor/graphql/product/mutations/collection/collection_delete.pyindex 94244b99cd..56cd038a4d 100644--- a/saleor/graphql/product/mutations/collection/collection_delete.py+++ b/saleor/graphql/product/mutations/collection/collection_delete.py@@ -1,6 +1,6 @@import graphene-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....product.tasks import collection_product_updated_taskdiff --git a/saleor/graphql/product/mutations/collection/collection_remove_products.py b/saleor/graphql/product/mutations/collection/collection_remove_products.pyindex d59226f2f1..5a7b7fb0a8 100644--- a/saleor/graphql/product/mutations/collection/collection_remove_products.py+++ b/saleor/graphql/product/mutations/collection/collection_remove_products.py@@ -1,6 +1,6 @@import graphene-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom ....channel import ChannelContextdiff --git a/saleor/graphql/product/mutations/collection/collection_update.py b/saleor/graphql/product/mutations/collection/collection_update.pyindex 24358ba34f..cb740cae0c 100644--- a/saleor/graphql/product/mutations/collection/collection_update.py+++ b/saleor/graphql/product/mutations/collection/collection_update.py@@ -1,7 +1,7 @@import graphenefrom django.db.models import Exists, OuterRef-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....thumbnail import models as thumbnail_modelsdiff --git a/saleor/graphql/product/mutations/product/product_update.py b/saleor/graphql/product/mutations/product/product_update.pyindex a7a7afdca1..91c41c31a6 100644--- a/saleor/graphql/product/mutations/product/product_update.py+++ b/saleor/graphql/product/mutations/product/product_update.py@@ -1,7 +1,7 @@import graphenefrom .....attribute import models as attribute_models-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom ....attribute.utils import AttrValuesInput, ProductAttributeAssignmentMixindiff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.pyindex 7b3abb4e2e..c39a0de826 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py@@ -7,7 +7,7 @@ from django.utils.text import slugifyfrom .....attribute import AttributeInputTypefrom .....attribute import models as attribute_modelsfrom .....core.tracing import traced_atomic_transaction-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....product.error_codes import ProductErrorCodediff --git a/saleor/graphql/product/mutations/product_variant/product_variant_delete.py b/saleor/graphql/product/mutations/product_variant/product_variant_delete.pyindex f96712502f..5ed40f553c 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_delete.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_delete.py@@ -7,7 +7,7 @@ from django.db.models import Exists, OuterReffrom .....attribute import AttributeInputTypefrom .....attribute import models as attribute_modelsfrom .....core.tracing import traced_atomic_transaction-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....order import events as order_eventsfrom .....order import models as order_modelsfrom .....order.tasks import recalculate_orders_taskdiff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.pyindex 94020d9d3c..552d5d0cca 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py@@ -6,7 +6,7 @@ from django.utils.text import slugifyfrom .....attribute import AttributeInputTypefrom .....attribute import models as attribute_models-from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....product.models import ProductChannelListingdiff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex 25a37dc2a6..ecfec4db16 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -12,7 +12,7 @@ from .....attribute.tests.model_helpers import (get_product_attribute_values,get_product_attributes,)-from .....discount.utils import get_active_catalogue_promotion_rules+from .....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom .....product.error_codes import ProductBulkCreateErrorCodefrom .....product.models import Productfrom .....product.tests.utils import create_imagediff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.pyindex c1884af71c..52d130cbb7 100644--- a/saleor/graphql/product/tests/mutations/test_product_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_create.py@@ -10,7 +10,7 @@ from django.utils.text import slugifyfrom freezegun import freeze_timefrom .....core.taxes import TaxType-from .....discount.utils import get_active_catalogue_promotion_rules+from .....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom .....graphql.core.enums import AttributeErrorCodefrom .....graphql.tests.utils import (get_graphql_content,diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.pyindex 7a348dd1b3..429fc11dd3 100644--- a/saleor/graphql/product/tests/mutations/test_product_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_update.py@@ -20,7 +20,7 @@ from .....attribute.tests.model_helpers import ()from .....attribute.utils import associate_attribute_values_to_instancefrom .....core.taxes import TaxType-from .....discount.utils import get_active_catalogue_promotion_rules+from .....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom .....graphql.core.enums import AttributeErrorCodefrom .....graphql.tests.utils import get_graphql_contentfrom .....plugins.manager import PluginsManagerdiff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.pyindex e5a2611d84..6b3708b53a 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py@@ -9,7 +9,7 @@ from django.conf import settingsfrom freezegun import freeze_timefrom .....attribute import AttributeInputType-from .....discount.utils import get_active_catalogue_promotion_rules+from .....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom .....product.error_codes import ProductVariantBulkErrorCodefrom .....product.models import (ProductChannelListing,diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.pyindex 9decc564a6..cbbd844257 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py@@ -5,7 +5,7 @@ import graphenefrom django.test import override_settingsfrom .....discount.models import PromotionRule-from .....discount.utils import get_active_catalogue_promotion_rules+from .....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom .....graphql.webhook.subscription_payload import get_pre_save_payload_keyfrom .....product.error_codes import ProductVariantBulkErrorCodefrom .....product.models import ProductChannelListingdiff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.pyindex c467da01a5..55fb88c49d 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py@@ -9,7 +9,7 @@ from django.conf import settingsfrom django.utils.text import slugifyfrom freezegun import freeze_time-from .....discount.utils import get_active_catalogue_promotion_rules+from .....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom .....product.error_codes import ProductErrorCodefrom .....tests.utils import dummy_editorjs, flush_post_commit_hooksfrom ....core.enums import WeightUnitsEnumdiff --git a/saleor/graphql/product/tests/mutations/test_product_variant_delete.py b/saleor/graphql/product/tests/mutations/test_product_variant_delete.pyindex cc7da83f72..9a4d114a8a 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_delete.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_delete.py@@ -4,7 +4,7 @@ import grapheneimport pytestfrom prices import Money, TaxedMoney-from .....discount.utils import get_active_catalogue_promotion_rules+from .....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom .....order import OrderEvents, OrderStatusfrom .....order.models import OrderEvent, OrderLinefrom .....product.models import ProductVariantdiff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.pyindex 3b1b3a42da..b8ac5e7046 100644--- a/saleor/graphql/product/tests/test_bulk_delete.py+++ b/saleor/graphql/product/tests/test_bulk_delete.py@@ -10,7 +10,7 @@ from ....attribute.models import AttributeValuefrom ....attribute.utils import associate_attribute_values_to_instancefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity-from ....discount.utils import get_active_catalogue_promotion_rules+from ....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom ....order import OrderEvents, OrderStatusfrom ....order.models import OrderEvent, OrderLinefrom ....plugins.manager import get_plugins_managerdiff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.pyindex fd1ccbb8e9..9860ccf6be 100644--- a/saleor/graphql/product/tests/test_category.py+++ b/saleor/graphql/product/tests/test_category.py@@ -12,7 +12,7 @@ from freezegun import freeze_timefrom graphql_relay import to_global_idfrom ....core.utils.json_serializer import CustomJsonEncoder-from ....discount.utils import get_active_catalogue_promotion_rules+from ....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom ....product.error_codes import ProductErrorCodefrom ....product.models import Category, Product, ProductChannelListingfrom ....product.tests.utils import create_image, create_zip_file_with_image_extdiff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.pyindex 19f50ea45f..71c4b8a7f2 100644--- a/saleor/graphql/product/tests/test_collection.py+++ b/saleor/graphql/product/tests/test_collection.py@@ -8,7 +8,7 @@ import pytzfrom django.core.files import Filefrom graphql_relay import to_global_id-from ....discount.utils import get_active_catalogue_promotion_rules+from ....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom ....product.error_codes import CollectionErrorCode, ProductErrorCodefrom ....product.models import Collection, CollectionChannelListing, Productfrom ....product.tests.utils import create_image, create_zip_file_with_image_extdiff --git a/saleor/graphql/product/tests/test_product_discounted_price.py b/saleor/graphql/product/tests/test_product_discounted_price.pyindex 806d313b52..396c29589c 100644--- a/saleor/graphql/product/tests/test_product_discounted_price.py+++ b/saleor/graphql/product/tests/test_product_discounted_price.py@@ -4,7 +4,7 @@ from freezegun import freeze_timefrom graphql_relay import to_global_idfrom ....discount.models import Promotion, PromotionRule-from ....discount.utils import (+from ....discount.utils.promotion import (get_active_catalogue_promotion_rules,get_current_products_for_rules,)diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.pyindex b1df2d7dad..a32a67e163 100644--- a/saleor/order/base_calculations.py+++ b/saleor/order/base_calculations.py@@ -9,7 +9,8 @@ from ..core.prices import quantize_pricefrom ..core.taxes import zero_moneyfrom ..discount import DiscountType, DiscountValueType, VoucherTypefrom ..discount.models import OrderDiscount-from ..discount.utils import apply_discount_to_value, is_order_level_voucher+from ..discount.utils.manual_discount import apply_discount_to_value+from ..discount.utils.voucher import is_order_level_voucherfrom ..shipping.models import ShippingMethodChannelListingfrom .interface import OrderTaxedPricesDatadiff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex 1f788009b8..d89abe085b 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -12,7 +12,7 @@ from ..core.db.connection import allow_writerfrom ..core.prices import quantize_pricefrom ..core.taxes import TaxData, TaxEmptyData, TaxError, zero_taxed_moneyfrom ..discount import DiscountType-from ..discount.utils import create_or_update_discount_objects_for_order+from ..discount.utils.order import create_or_update_discount_objects_for_orderfrom ..payment.model_helpers import get_subtotalfrom ..plugins import PLUGIN_IDENTIFIER_PREFIXfrom ..plugins.manager import PluginsManagerdiff --git a/saleor/order/fetch.py b/saleor/order/fetch.pyindex 0e1edb329a..2e24bac2f4 100644--- a/saleor/order/fetch.py+++ b/saleor/order/fetch.py@@ -14,7 +14,7 @@ from ..discount.interface import (fetch_voucher_info,)from ..discount.models import OrderLineDiscount-from ..discount.utils import apply_voucher_to_line+from ..discount.utils.voucher import apply_voucher_to_linefrom ..payment.models import Paymentfrom ..product.models import (DigitalContent,@@ -100,6 +100,7 @@ def fetch_draft_order_lines_info("variant__channel_listings__variantlistingpromotionrule__promotion_rule__promotion__translations","variant__channel_listings__variantlistingpromotionrule__promotion_rule__translations","variant__product__collections",+ "variant__product__product_type",]if lines is None:with allow_writer():@@ -133,6 +134,7 @@ def fetch_draft_order_lines_info(line=line,variant=variant,product=product,+ product_type=product.product_type,collections=list(product.collections.all()) if product else [],channel_listing=variant_channel_listing,discounts=list(line.discounts.all()),diff --git a/saleor/order/tests/benchmark/test_fetch_order_prices.py b/saleor/order/tests/benchmark/test_fetch_order_prices.pyindex 5a1a17e4c6..dcb51f1d98 100644--- a/saleor/order/tests/benchmark/test_fetch_order_prices.py+++ b/saleor/order/tests/benchmark/test_fetch_order_prices.py@@ -41,7 +41,7 @@ def test_fetch_order_prices_catalogue_discount(tc.save()# when- with django_assert_num_queries(43):+ with django_assert_num_queries(44):fetch_order_prices_if_expired(order, plugins_manager, None, True)# then@@ -136,7 +136,7 @@ def test_fetch_order_prices_multiple_catalogue_discounts(tc.save()# when- with django_assert_num_queries(43):+ with django_assert_num_queries(44):fetch_order_prices_if_expired(order, plugins_manager, None, True)# thendiff --git a/saleor/order/tests/test_fetch.py b/saleor/order/tests/test_fetch.pyindex dd2f9cde09..74ac9b38cf 100644--- a/saleor/order/tests/test_fetch.py+++ b/saleor/order/tests/test_fetch.py@@ -34,7 +34,7 @@ def test_fetch_draft_order_lines_info()# when- with django_assert_num_queries(11):+ with django_assert_num_queries(12):lines_info = fetch_draft_order_lines_info(order)# thendiff --git a/saleor/order/tests/test_fetch_order_prices.py b/saleor/order/tests/test_fetch_order_prices.pyindex 544e59a207..6b6cc441c9 100644--- a/saleor/order/tests/test_fetch_order_prices.py+++ b/saleor/order/tests/test_fetch_order_prices.py@@ -2283,7 +2283,8 @@ def test_fetch_order_prices_catalogue_discount_race_condition(calculations.fetch_order_prices_if_expired(order, plugins_manager, None, True)with before_after.before(- "saleor.discount.utils.prepare_line_discount_objects_for_catalogue_promotions",+ "saleor.discount.utils.promotion."+ "prepare_line_discount_objects_for_catalogue_promotions",call_before_creating_catalogue_line_discount,):calculations.fetch_order_prices_if_expired(order, plugins_manager, None, True)diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex 134b4c4d9d..68d3f50e37 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -12,7 +12,7 @@ from ...discount.interface import VariantPromotionRuleInfofrom ...discount.models import (DiscountValueType,)-from ...discount.utils import validate_voucher_in_order+from ...discount.utils.voucher import validate_voucher_in_orderfrom ...graphql.core.utils import to_global_id_or_nonefrom ...graphql.order.utils import OrderLineDatafrom ...graphql.tests.utils import get_graphql_content@@ -661,7 +661,7 @@ def test_get_order_weight_non_existing_product(assert old_weight == new_weight-@patch("saleor.discount.utils.validate_voucher")+@patch("saleor.discount.utils.voucher.validate_voucher")def test_get_voucher_discount_for_order_voucher_validation(mock_validate_voucher, voucher, order_with_lines):@@ -685,7 +685,7 @@ def test_get_voucher_discount_for_order_voucher_validation()-@patch("saleor.discount.utils.validate_voucher")+@patch("saleor.discount.utils.voucher.validate_voucher")def test_validate_voucher_in_order_without_voucher(mock_validate_voucher, order_with_lines):diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex ea26d74892..77497c2166 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -20,8 +20,10 @@ from ..discount.models import (OrderLineDiscount,VoucherType,)-from ..discount.utils import (+from ..discount.utils.manual_discount import (apply_discount_to_value,+)+from ..discount.utils.promotion import (get_discount_name,get_discount_translated_name,get_sale_id,diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.pyindex 443c69d616..dea8979478 100644--- a/saleor/plugins/avatax/__init__.py+++ b/saleor/plugins/avatax/__init__.py@@ -19,7 +19,7 @@ from ...checkout.utils import get_address_for_checkout_taxes, is_shipping_requirfrom ...core.http_client import HTTPClientfrom ...core.taxes import TaxErrorfrom ...discount import DiscountType, VoucherType-from ...discount.utils import is_order_level_voucher+from ...discount.utils.voucher import is_order_level_voucherfrom ...order import base_calculations as base_order_calculationsfrom ...order.utils import (get_address_for_order_taxes,diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex bd86a7b407..c89c6a8529 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -22,7 +22,7 @@ from ....core.prices import quantize_pricefrom ....core.taxes import TaxError, TaxType, zero_money, zero_taxed_moneyfrom ....discount import DiscountType, DiscountValueType, RewardValueType, VoucherTypefrom ....discount.models import CheckoutLineDiscount, Promotion, PromotionRule-from ....discount.utils import (+from ....discount.utils.checkout import (create_or_update_discount_objects_from_promotion_for_checkout,)from ....order import OrderStatusdiff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex b74c3aae24..272e06e7e9 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -34,7 +34,7 @@ from ....core.notify_events import NotifyEventTypefrom ....core.utils.url import prepare_urlfrom ....discount import RewardType, RewardValueTypefrom ....discount.interface import VariantPromotionRuleInfo-from ....discount.utils import (+from ....discount.utils.checkout import (create_or_update_discount_objects_from_promotion_for_checkout,)from ....graphql.discount.utils import convert_migrated_sale_predicate_to_catalogue_infodiff --git a/saleor/product/models.py b/saleor/product/models.pyindex 1885558044..6c8833cc3a 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -395,7 +395,7 @@ class ProductVariant(SortableModel, ModelWithMetadata, ModelWithExternalReferencIf a custom price is provided, return the price with applied discounts fromvalid promotion rules for this variant."""- from ..discount.utils import calculate_discounted_price_for_rules+ from ..discount.utils.promotion import calculate_discounted_price_for_rulesif price_override is None:return channel_listing.discounted_price or channel_listing.pricediff --git a/saleor/product/tests/test_category.py b/saleor/product/tests/test_category.pyindex 909ffa270c..a7954c6600 100644--- a/saleor/product/tests/test_category.py+++ b/saleor/product/tests/test_category.py@@ -1,6 +1,6 @@from unittest.mock import patch-from ...discount.utils import get_active_catalogue_promotion_rules+from ...discount.utils.promotion import get_active_catalogue_promotion_rulesfrom ...plugins.manager import get_plugins_managerfrom ...tests.utils import flush_post_commit_hooksfrom ..models import Categorydiff --git a/saleor/product/tests/test_fetch_variants_for_promotion_rules.py b/saleor/product/tests/test_fetch_variants_for_promotion_rules.pyindex c0f24c7880..cb463c3ab6 100644--- a/saleor/product/tests/test_fetch_variants_for_promotion_rules.py+++ b/saleor/product/tests/test_fetch_variants_for_promotion_rules.py@@ -5,7 +5,7 @@ import graphenefrom ...discount import RewardValueTypefrom ...discount.models import PromotionRule-from ...discount.utils import update_rule_variant_relation+from ...discount.utils.promotion import update_rule_variant_relationfrom ..utils.variants import fetch_variants_for_promotion_rulesdiff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.pyindex 65a60e04a3..6cc5129cef 100644--- a/saleor/product/utils/__init__.py+++ b/saleor/product/utils/__init__.py@@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Unionfrom ...core.taxes import TaxedMoney, zero_taxed_moneyfrom ...core.tracing import traced_atomic_transactionfrom ...core.utils.events import call_event-from ...discount.utils import mark_active_catalogue_promotion_rules_as_dirty+from ...discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirtyfrom ...webhook.event_types import WebhookEventAsyncTypefrom ...webhook.utils import get_webhooks_for_eventfrom ..models import Product, ProductChannelListingdiff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.pyindex 6eb87e91cb..012d17e901 100644--- a/saleor/product/utils/variant_prices.py+++ b/saleor/product/utils/variant_prices.py@@ -11,7 +11,7 @@ from ...channel.models import Channelfrom ...core.taxes import zero_moneyfrom ...discount import PromotionRuleInfofrom ...discount.models import PromotionRule-from ...discount.utils import (+from ...discount.utils.promotion import (calculate_discounted_price_for_promotions,get_variants_to_promotion_rules_map,)diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.pyindex f3d0f45d54..6c820cf0e1 100644--- a/saleor/product/utils/variants.py+++ b/saleor/product/utils/variants.py@@ -6,7 +6,7 @@ from django.db.models import QuerySetfrom ...attribute import AttributeTypefrom ...discount.models import PromotionRule-from ...discount.utils import update_rule_variant_relation+from ...discount.utils.promotion import update_rule_variant_relationfrom ..models import ProductVariantif TYPE_CHECKING:diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.pyindex c026cda0be..d9f1028d92 100644--- a/saleor/tax/tests/test_checkout_calculations.py+++ b/saleor/tax/tests/test_checkout_calculations.py@@ -7,7 +7,9 @@ from ...checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ...checkout.utils import add_variant_to_checkoutfrom ...core.prices import quantize_pricefrom ...core.taxes import zero_taxed_money-from ...discount.utils import create_checkout_discount_objects_for_order_promotions+from ...discount.utils.checkout import (+ create_checkout_discount_objects_for_order_promotions,+)from ...plugins.manager import get_plugins_managerfrom ...tax.models import TaxClassCountryRatefrom .. import TaxCalculationStrategydiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex b06d60e476..8a2be452a9 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -80,7 +80,7 @@ from ..discount.models import (VoucherCustomer,VoucherTranslation,)-from ..discount.utils import (+from ..discount.utils.voucher import (get_products_voucher_discount,validate_voucher_in_order,)diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex fd9ec95f96..4818ea981c 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -33,7 +33,7 @@ from ..core.utils.anonymization import ()from ..core.utils.json_serializer import CustomJsonEncoderfrom ..discount import VoucherType-from ..discount.utils import is_order_level_voucher+from ..discount.utils.voucher import is_order_level_voucherfrom ..order import FulfillmentStatus, OrderStatusfrom ..order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ..order.utils import get_order_countrydiff --git a/saleor/webhook/tests/test_webhook_serializers.py b/saleor/webhook/tests/test_webhook_serializers.pyindex a8f06308c9..8e5dc8dcef 100644--- a/saleor/webhook/tests/test_webhook_serializers.py+++ b/saleor/webhook/tests/test_webhook_serializers.py@@ -12,7 +12,7 @@ from ...checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ...core.prices import quantize_pricefrom ...discount import DiscountTypefrom ...discount.models import PromotionRule-from ...discount.utils import (+from ...discount.utils.checkout import (create_or_update_discount_objects_from_promotion_for_checkout,)from ...plugins.manager import get_plugins_manager