Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Always apply discount from single promotion rule (#15309)
Maciej Korycinski7b6b4d865721
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a04488ffc8..c7eb5d3dea 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ All notable, unreleased changes to this project will be documented in this file.### Breaking changes- Drop `OrderBulkCreateInput.voucher` field. Use `OrderBulkCreateInput.voucherCode` instead. - #14553 by @zedzior+- Do not stack promotion rules within the promotion. Only the best promotion rule will be applied within the promotion. Previously discounts from all rules within the promotion that gives the best discount were applied to the variant's price - #15309 by @korycins### GraphQL APIdiff --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 ae25fc3f22..8213a4be53 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@@ -52,39 +52,32 @@ def test_variant_discounts_multiple_promotions(product, channel_USD):rule_high.channels.add(channel_USD)rules_info_per_promotion_id = {- variant.id: {- promotion_low_discount.id: [- PromotionRuleInfo(- rule=rule_low,- channel_ids=[channel_USD.id],- )- ],- promotion_high_discount.id: [- PromotionRuleInfo(- rule=rule_high,- channel_ids=[channel_USD.id],- )- ],- }+ variant.id: [+ PromotionRuleInfo(+ rule=rule_low,+ channel_ids=[channel_USD.id],+ ),+ PromotionRuleInfo(+ rule=rule_high,+ channel_ids=[channel_USD.id],+ ),+ ],}variant_channel_listing = variant.channel_listings.get(channel=channel_USD)price = variant_channel_listing.price# when- applied_discounts = calculate_discounted_price_for_promotions(+ applied_rule_id, applied_discount = calculate_discounted_price_for_promotions(price=price,- rules_info_per_variant_and_promotion_id=rules_info_per_promotion_id,+ rules_info_per_variant=rules_info_per_promotion_id,channel=channel_USD,variant_id=variant.id,)# then- assert len(applied_discounts) == 1- assert applied_discounts[0] == (- rule_high.id,- price - rule_high.reward_value / 100 * price,- )+ assert applied_rule_id == rule_high.id+ assert applied_discount == (price - rule_high.reward_value / 100 * price)def test_variant_discounts_multiple_promotions_and_rules(product, channel_USD):@@ -143,40 +136,33 @@ def test_variant_discounts_multiple_promotions_and_rules(product, channel_USD):channel_USD.promotionrule_set.add(rule_low_1, rule_low_2, rule_high_1)rules_info_per_promotion_id = {- variant.id: {- promotion_low_discount.id: [- PromotionRuleInfo(- rule=rule_low_1,- channel_ids=[channel_USD.id],- ),- PromotionRuleInfo(- rule=rule_low_2,- channel_ids=[channel_USD.id],- ),- ],- promotion_high_discount.id: [- PromotionRuleInfo(- rule=rule_high_1,- channel_ids=[channel_USD.id],- ),- ],- }+ variant.id: [+ PromotionRuleInfo(+ rule=rule_low_1,+ channel_ids=[channel_USD.id],+ ),+ PromotionRuleInfo(+ rule=rule_low_2,+ channel_ids=[channel_USD.id],+ ),+ PromotionRuleInfo(+ rule=rule_high_1,+ channel_ids=[channel_USD.id],+ ),+ ],}variant_channel_listing = variant.channel_listings.get(channel=channel_USD)price = variant_channel_listing.price# when- applied_discounts = calculate_discounted_price_for_promotions(+ applied_rule_id, applied_discount = calculate_discounted_price_for_promotions(price=price,- rules_info_per_variant_and_promotion_id=rules_info_per_promotion_id,+ rules_info_per_variant=rules_info_per_promotion_id,channel=channel_USD,variant_id=variant.id,)# then- assert len(applied_discounts) == 1- assert applied_discounts[0] == (- rule_high_1.id,- price - rule_high_1.reward_value / 100 * price,- )+ assert applied_rule_id == rule_high_1.id+ assert applied_discount == (price - rule_high_1.reward_value / 100 * price)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 d687ca682a..cae4c0b7e9 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_promotions_map+from ...utils import get_variants_to_promotion_rules_mapdef test_get_variants_to_promotions_map(@@ -48,22 +48,18 @@ def test_get_variants_to_promotions_map(variants = ProductVariant.objects.all()# when- rules_info_per_variant_and_promotion_id = get_variants_to_promotions_map(variants)+ rules_info_per_variant = get_variants_to_promotion_rules_map(variants)# then- assert len(rules_info_per_variant_and_promotion_id) == 3- assert rules_info_per_variant_and_promotion_id[variant.id] == {- promotion.id: [- PromotionRuleInfo(rule=rule_1, channel_ids=[channel_USD.id]),- ]- }+ assert len(rules_info_per_variant) == 3+ assert rules_info_per_variant[variant.id] == [+ PromotionRuleInfo(rule=rule_1, channel_ids=[channel_USD.id]),+ ]for variant in product_with_two_variants.variants.all():- assert rules_info_per_variant_and_promotion_id[variant.id] == {- promotion.id: [- PromotionRuleInfo(rule=rule_2, channel_ids=[channel_USD.id]),- ]- }+ assert rules_info_per_variant[variant.id] == [+ PromotionRuleInfo(rule=rule_2, channel_ids=[channel_USD.id]),+ ]def test_get_variants_to_promotions_map_from_different_promotions(@@ -106,17 +102,17 @@ def test_get_variants_to_promotions_map_from_different_promotions(variants = ProductVariant.objects.all()# when- rules_info_per_variant_and_promotion_id = get_variants_to_promotions_map(variants)+ rules_info_per_variant = get_variants_to_promotion_rules_map(variants)# then- assert len(rules_info_per_variant_and_promotion_id) == 1- assert len(rules_info_per_variant_and_promotion_id[variant.id]) == 2- assert rules_info_per_variant_and_promotion_id[variant.id][promotion.id] == [- PromotionRuleInfo(rule=rule_1, channel_ids=[channel_USD.id])- ]- assert rules_info_per_variant_and_promotion_id[variant.id][promotion_2.id] == [- PromotionRuleInfo(rule=rule_2, channel_ids=[channel_USD.id])+ assert len(rules_info_per_variant) == 1+ assert len(rules_info_per_variant[variant.id]) == 2+ expected_rules = [+ PromotionRuleInfo(rule=rule_1, channel_ids=[channel_USD.id]),+ PromotionRuleInfo(rule=rule_2, channel_ids=[channel_USD.id]),]+ for rule in rules_info_per_variant[variant.id]:+ assert rule in expected_rulesdef test_get_variants_to_promotions_map_no_active_rules(product):@@ -125,10 +121,10 @@ def test_get_variants_to_promotions_map_no_active_rules(product):fetch_variants_for_promotion_rules(PromotionRule.objects.all())# when- rules_per_promotion = get_variants_to_promotions_map(variants)+ rules_info_per_variant = get_variants_to_promotion_rules_map(variants)# then- assert not rules_per_promotion+ assert not rules_info_per_variantdef test_get_variants_to_promotions_map_no_matching_rules(@@ -155,7 +151,7 @@ def test_get_variants_to_promotions_map_no_matching_rules(variants = ProductVariant.objects.filter(id=variant.id)# when- rules_per_promotion = get_variants_to_promotions_map(variants)+ rules_info_per_variant = get_variants_to_promotion_rules_map(variants)# then- assert not rules_per_promotion+ assert not rules_info_per_variantdiff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 055509cf7d..1786e2d418 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -2,13 +2,7 @@ from collections import defaultdictfrom collections.abc import Iterable, Iteratorfrom decimal import ROUND_HALF_UP, Decimalfrom functools import partial-from typing import (- TYPE_CHECKING,- Callable,- Optional,- Union,- cast,-)+from typing import TYPE_CHECKING, Callable, Optional, Union, castfrom uuid import UUIDimport graphene@@ -174,57 +168,49 @@ def calculate_discounted_price_for_rules(def calculate_discounted_price_for_promotions(*,price: Money,- rules_info_per_variant_and_promotion_id: dict[- int, dict[UUID, list[PromotionRuleInfo]]- ],+ rules_info_per_variant: dict[int, list[PromotionRuleInfo]],channel: "Channel",variant_id: int,-) -> list[tuple[UUID, Money]]:+) -> Optional[tuple[UUID, Money]]:"""Return minimum product's price of all prices with promotions applied."""- applied_discounts = []- rules_info_per_promotion_id = rules_info_per_variant_and_promotion_id.get(- variant_id- )- if rules_info_per_promotion_id:- applied_discounts = get_best_promotion_discount(- price, rules_info_per_promotion_id, channel+ 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_discounts+ return applied_discountdef get_best_promotion_discount(price: Money,- rules_info_per_promotion_id: dict[UUID, list[PromotionRuleInfo]],+ rules_info_for_variant: list[PromotionRuleInfo],channel: "Channel",-) -> list[tuple[UUID, Money]]:- """Return the rules with the discount amounts for the best promotion.+) -> 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 followingshape:- [- (rule_id_1, discount_amount_1),- (rule_id_2, discount_amount_2),- ]+ (rule_id_1, discount_amount_1)"""- available_discounts = [- [- (rule_id, discount)- for rule_id, discount in get_product_promotion_discounts(- rules_info=rules_info,- channel=channel,- )- ]- for _, rules_info in rules_info_per_promotion_id.items()- ]- applied_discounts = max(- [- [(rule_id, price - discount(price)) for rule_id, discount in discounts]- for discounts in available_discounts- ],- key=lambda x: sum(y[1].amount for y in x), # sort over a max discount- )+ 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_discounts+ return applied_discountdef get_product_promotion_discounts(@@ -505,25 +491,18 @@ def _update_line_discount(updated_fields.append("translated_name")-def get_variants_to_promotions_map(+def get_variants_to_promotion_rules_map(variant_qs: "ProductVariantQueryset",-) -> dict[int, dict[UUID, list[PromotionRuleInfo]]]:+) -> 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: {- promotion_id_1: [PromotionRuleInfo_1, PromotionRuleInfo_2],- promotion_id_2: [PromotionRuleInfo_3],- }- variant_id_2: {- promotion_id_1: [PromotionRuleInfo_1]- }+ variant_id_1: [PromotionRuleInfo_1, PromotionRuleInfo_2, PromotionRuleInfo_3],+ variant_id_2: [PromotionRuleInfo_1]}"""- rules_info_per_variant_and_promotion_id: dict[- int, dict[UUID, list[PromotionRuleInfo]]- ] = defaultdict(lambda: defaultdict(list))+ rules_info_per_variant: dict[int, list[PromotionRuleInfo]] = defaultdict(list)promotions = Promotion.objects.active()PromotionRuleVariant = PromotionRule.variants.through@@ -546,14 +525,14 @@ def get_variants_to_promotions_map(if not rule:continuevariant_id = promotion_rule_variant.productvariant_id- rules_info_per_variant_and_promotion_id[variant_id][rule.promotion_id].append(+ 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_and_promotion_id+ return rules_info_per_variantdef _get_rule_to_channel_ids_map(rules: QuerySet):diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.pyindex 1bf0f2050f..74ea971ab6 100644--- a/saleor/product/tests/test_product_minimal_variant_price.py+++ b/saleor/product/tests/test_product_minimal_variant_price.py@@ -1,4 +1,4 @@-from decimal import ROUND_HALF_UP, Decimal+from decimal import Decimalfrom unittest.mock import patchimport before_after@@ -179,25 +179,12 @@ def test_update_discounted_price_for_promotion_discount_multiple_applicable_ruleupdate_discounted_prices_for_promotion(Product.objects.filter(id__in=[product.id]))# then- percentage_reward_value = (- (variant_price * (percentage_reward_value / 100))- .quantize(rounding=ROUND_HALF_UP)- .amount- )- expected_price_amount = round(- variant_price.amount - reward_value - percentage_reward_value, 2- )+ expected_price_amount = round(variant_price.amount - reward_value, 2)product_channel_listing.refresh_from_db()variant_channel_listing.refresh_from_db()assert product_channel_listing.discounted_price_amount == expected_price_amountassert variant_channel_listing.discounted_price_amount == expected_price_amount- assert variant_channel_listing.promotion_rules.count() == 2- assert (- variant_channel_listing.variantlistingpromotionrule.get(- promotion_rule_id=rule_1.id- ).discount_amount- == percentage_reward_value- )+ assert variant_channel_listing.promotion_rules.count() == 1assert (variant_channel_listing.variantlistingpromotionrule.get(promotion_rule_id=rule_2.iddiff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.pyindex 03ebbb68ae..d5a7e1a7fa 100644--- a/saleor/product/utils/variant_prices.py+++ b/saleor/product/utils/variant_prices.py@@ -12,7 +12,7 @@ from ...discount import PromotionRuleInfofrom ...discount.models import PromotionRulefrom ...discount.utils import (calculate_discounted_price_for_promotions,- get_variants_to_promotions_map,+ get_variants_to_promotion_rules_map,)from ..managers import ProductsQueryset, ProductVariantQuerysetfrom ..models import (@@ -35,7 +35,7 @@ def update_discounted_prices_for_promotion(products: ProductsQueryset):variant_qs = ProductVariant.objects.filter(Exists(products.filter(id=OuterRef("product_id"))))- rules_info_per_variant_and_promotion_id = get_variants_to_promotions_map(variant_qs)+ rules_info_per_variant = get_variants_to_promotion_rules_map(variant_qs)product_to_variant_listings_per_channel_map = (_get_product_to_variant_channel_listings_per_channel_map(variant_qs))@@ -67,7 +67,7 @@ def update_discounted_prices_for_promotion(products: ProductsQueryset):variant_listing_promotion_rule_to_update,) = _get_discounted_variants_prices_for_promotions(variant_listings,- rules_info_per_variant_and_promotion_id,+ rules_info_per_variant,product_channel_listing.channel,variant_listing_to_listing_rule_per_rule_map,)@@ -218,9 +218,7 @@ def _get_variant_listings_to_listing_rule_per_rule_id_map(def _get_discounted_variants_prices_for_promotions(variant_listings: list[ProductVariantChannelListing],- rules_info_per_variant_and_promotion_id: dict[- int, dict[UUID, list[PromotionRuleInfo]]- ],+ rules_info_per_variant: dict[int, list[PromotionRuleInfo]],channel: Channel,variant_listing_to_listing_rule_per_rule_map: dict,) -> tuple[@@ -238,22 +236,22 @@ def _get_discounted_variants_prices_for_promotions(VariantChannelListingPromotionRule] = []for variant_listing in variant_listings:- applied_discounts = calculate_discounted_price_for_promotions(+ applied_discount = calculate_discounted_price_for_promotions(price=variant_listing.price,- rules_info_per_variant_and_promotion_id=(- rules_info_per_variant_and_promotion_id- ),+ rules_info_per_variant=rules_info_per_variant,channel=channel,variant_id=variant_listing.variant_id,)- rule_ids = []discounted_variant_price = variant_listing.price- for rule_id, discount in applied_discounts:- if discounted_variant_price.amount < discount.amount:- discount = discounted_variant_price- discounted_variant_price = zero_money(discounted_variant_price.currency)- else:- discounted_variant_price -= discount++ rule_id = None+ if applied_discount:+ rule_id, discount = applied_discount+ discounted_variant_price -= discount+ discounted_variant_price = max(+ discounted_variant_price, zero_money(discounted_variant_price.currency)+ )+_handle_discount_rule_id(variant_listing,rule_id,@@ -263,9 +261,6 @@ def _get_discounted_variants_prices_for_promotions(variant_listing_promotion_rule_to_update,variant_listing_promotion_rule_to_create,)- rule_ids.append(rule_id)- if discounted_variant_price.amount == 0:- breakif variant_listing.discounted_price != discounted_variant_price:variant_listing.discounted_price_amount = discounted_variant_price.amount@@ -275,7 +270,7 @@ def _get_discounted_variants_prices_for_promotions(# anymoreVariantChannelListingPromotionRule.objects.filter(variant_channel_listing_id=variant_listing.id- ).exclude(promotion_rule_id__in=rule_ids).delete()+ ).exclude(promotion_rule_id=rule_id).delete()discounted_variants_price.append(discounted_variant_price)