Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix failing discounted price calculations when PromotionRule was deleted in the meantime (#14583)
Iga Karbowiak396d4d2d26de
diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.pyindex 9e83daf276..85cde01738 100644--- a/saleor/product/tests/test_product_minimal_variant_price.py+++ b/saleor/product/tests/test_product_minimal_variant_price.py@@ -1,13 +1,14 @@from decimal import ROUND_HALF_UP, Decimalfrom unittest.mock import patch+import before_afterimport grapheneimport pytestfrom django.core.management import call_commandfrom prices import Moneyfrom ...discount import RewardValueType-from ...discount.models import Promotion+from ...discount.models import Promotion, PromotionRulefrom ...product.models import Product, VariantChannelListingPromotionRulefrom ..utils.variant_prices import update_discounted_prices_for_promotion@@ -485,3 +486,116 @@ def test_management_commmand_update_all_products_discounted_price(for (args, kwargs), product in zip(call_args_list, product_list):assert len(args[0]) == 1assert args[0][0].pk == product.pk+++def test_update_discounted_price_for_promotion_promotion_rule_deleted_in_meantime(+ product, channel_USD+):+ # given+ variant = product.variants.first()+ variant_channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)+ product_channel_listing = product.channel_listings.get(channel_id=channel_USD.id)+ variant_price = Money("9.99", "USD")+ variant_channel_listing.price = variant_price+ variant_channel_listing.discounted_price = variant_price+ variant_channel_listing.save()+ product_channel_listing.refresh_from_db()++ reward_value = Decimal("2")+ promotion = Promotion.objects.create(+ name="Promotion",+ )+ rule = promotion.rules.create(+ name="Percentage promotion rule",+ promotion=promotion,+ catalogue_predicate={+ "variantPredicate": {+ "ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]+ }+ },+ reward_value_type=RewardValueType.FIXED,+ reward_value=reward_value,+ )+ rule.channels.add(variant_channel_listing.channel)++ def delete_promotion_rule(*args, **kwargs):+ PromotionRule.objects.all().delete()++ # when+ with before_after.before(+ "saleor.product.utils.variant_prices._get_discounted_variants_prices_for_promotions",+ delete_promotion_rule,+ ):+ update_discounted_prices_for_promotion(+ Product.objects.filter(id__in=[product.id])+ )++ # then+ expected_price_amount = variant_price.amount - reward_value+ product_channel_listing.refresh_from_db()+ variant_channel_listing.refresh_from_db()+ assert product_channel_listing.discounted_price_amount == expected_price_amount+ assert variant_channel_listing.discounted_price_amount == expected_price_amount+ assert not variant_channel_listing.promotion_rules.all()+ assert not variant_channel_listing.variantlistingpromotionrule.exists()++[email protected]_db(transaction=False)+def test_update_discounted_price_rule_deleted_in_meantime_promotion_listing_exist(+ product, channel_USD+):+ # given+ variant = product.variants.first()+ variant_channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)+ product_channel_listing = product.channel_listings.get(channel_id=channel_USD.id)+ variant_price = Money("9.99", "USD")+ variant_channel_listing.price = variant_price+ variant_channel_listing.discounted_price = variant_price+ variant_channel_listing.save()+ product_channel_listing.refresh_from_db()++ reward_value = Decimal("2")+ promotion = Promotion.objects.create(+ name="Promotion",+ )+ rule = promotion.rules.create(+ name="Percentage promotion rule",+ promotion=promotion,+ catalogue_predicate={+ "variantPredicate": {+ "ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]+ }+ },+ reward_value_type=RewardValueType.FIXED,+ reward_value=reward_value,+ )+ rule.channels.add(variant_channel_listing.channel)++ listing_promotion_rule = VariantChannelListingPromotionRule.objects.create(+ variant_channel_listing=variant_channel_listing,+ promotion_rule=rule,+ discount_amount=Decimal("1"),+ currency=channel_USD.currency_code,+ )++ def delete_promotion_rule(*args, **kwargs):+ rule.delete()++ # when+ with before_after.before(+ "saleor.product.utils.variant_prices._update_or_create_listings",+ delete_promotion_rule,+ ):+ update_discounted_prices_for_promotion(+ Product.objects.filter(id__in=[product.id])+ )++ # then+ expected_price_amount = variant_price.amount - reward_value+ product_channel_listing.refresh_from_db()+ variant_channel_listing.refresh_from_db()+ assert product_channel_listing.discounted_price_amount == expected_price_amount+ assert variant_channel_listing.discounted_price_amount == expected_price_amount+ with pytest.raises(VariantChannelListingPromotionRule.DoesNotExist):+ listing_promotion_rule.refresh_from_db()+ assert not variant_channel_listing.variantlistingpromotionrule.exists()diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.pyindex 28257d40bf..8732d2b53e 100644--- a/saleor/product/utils/variant_prices.py+++ b/saleor/product/utils/variant_prices.py@@ -3,12 +3,14 @@ from decimal import Decimalfrom typing import Optionalfrom uuid import UUID+from django.db import transactionfrom django.db.models import Exists, OuterReffrom prices import Moneyfrom ...channel.models import Channelfrom ...core.taxes import zero_moneyfrom ...discount import PromotionRuleInfo+from ...discount.models import PromotionRulefrom ...discount.utils import (calculate_discounted_price_for_promotions,fetch_active_promotion_rules,@@ -117,11 +119,8 @@ def _update_or_create_listings(changed_variants_listings_to_update, ["discounted_price_amount"])if changed_variant_listing_promotion_rule_to_create:- # after migrating to Django 4.0 we should use `update_conflicts` instead- # of `ignore_conflicts`- # https://docs.djangoproject.com/en/4.1/ref/models/querysets/#bulk-create- VariantChannelListingPromotionRule.objects.bulk_create(- changed_variant_listing_promotion_rule_to_create, ignore_conflicts=True+ _create_variant_listing_promotion_rule(+ changed_variant_listing_promotion_rule_to_create)if changed_variant_listing_promotion_rule_to_update:VariantChannelListingPromotionRule.objects.bulk_update(@@ -129,6 +128,43 @@ def _update_or_create_listings()+def _create_variant_listing_promotion_rule(variant_listing_promotion_rule_to_create):+ with transaction.atomic():+ rule_ids = [+ listing.promotion_rule_id+ for listing in variant_listing_promotion_rule_to_create+ ]+ listing_ids = [+ listing.variant_channel_listing_id+ for listing in variant_listing_promotion_rule_to_create+ ]+ # Lock PromotionRule and ProductVariantChannelListing before bulk_create+ rules = PromotionRule.objects.filter(id__in=rule_ids).select_for_update()+ variant_listings = ProductVariantChannelListing.objects.filter(+ id__in=listing_ids+ ).select_for_update()+ # Do not create VariantChannelListingPromotionRule for rules that were deleted.+ if len(rules) < len(rule_ids):+ variant_listing_promotion_rule_to_create = [+ listing+ for listing in variant_listing_promotion_rule_to_create+ if listing.promotion_rule_id in {rule.id for rule in rules}+ ]+ if len(variant_listings) < len(listing_ids):+ variant_listing_promotion_rule_to_create = [+ listing+ for listing in variant_listing_promotion_rule_to_create+ if listing.variant_channel_listing_id+ in {listing.id for listing in variant_listings}+ ]+ # After migrating to Django 4.0 we should use `update_conflicts` instead+ # of `ignore_conflicts`+ # https://docs.djangoproject.com/en/4.1/ref/models/querysets/#bulk-create+ VariantChannelListingPromotionRule.objects.bulk_create(+ variant_listing_promotion_rule_to_create, ignore_conflicts=True+ )++def _get_product_to_variant_channel_listings_per_channel_map(variants: ProductVariantQueryset,):