Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Optimize updating discounted prices for promotions (#15040)

Iga Karbowiak10993a59db61
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
index d09cd25d79..0b269f78fa 100644
--- a/saleor/discount/__init__.py
+++ b/saleor/discount/__init__.py
@@ -1,8 +1,6 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING
-from django.db.models import QuerySet
-
if TYPE_CHECKING:
from .models import PromotionRule
@@ -76,6 +74,4 @@ class PromotionEvents:
@dataclass
class PromotionRuleInfo:
rule: "PromotionRule"
- variant_ids: list[int]
- variants: QuerySet
channel_ids: list[int]
diff --git a/saleor/discount/migrations/0066_promotionrule_variants.py b/saleor/discount/migrations/0066_promotionrule_variants.py
new file mode 100644
index 0000000000..3eec6846ff
--- /dev/null
+++ b/saleor/discount/migrations/0066_promotionrule_variants.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.23 on 2023-12-08 11:11
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product", "0189_merge_20230929_0857"),
+ ("discount", "0065_vouchercode_created_at_check"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="promotionrule",
+ name="variants",
+ field=models.ManyToManyField(blank=True, to="product.ProductVariant"),
+ ),
+ ]
diff --git a/saleor/discount/migrations/0067_fulfill_promotionrule_variants.py b/saleor/discount/migrations/0067_fulfill_promotionrule_variants.py
new file mode 100644
index 0000000000..589e8b8830
--- /dev/null
+++ b/saleor/discount/migrations/0067_fulfill_promotionrule_variants.py
@@ -0,0 +1,28 @@
+# Generated by Django 3.2.23 on 2023-12-12 08:35
+
+from django.apps import apps as registry
+from django.db import migrations
+from django.db.models.signals import post_migrate
+
+from ..tasks import set_promotion_rule_variants_task
+
+
+def update_promotion_rule_variants(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ set_promotion_rule_variants_task.delay()
+
+ sender = registry.get_app_config("discount")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("discount", "0066_promotionrule_variants"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ update_promotion_rule_variants,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/discount/migrations/0068_promotion_start_end_date_indexes.py b/saleor/discount/migrations/0068_promotion_start_end_date_indexes.py
new file mode 100644
index 0000000000..db2dee9518
--- /dev/null
+++ b/saleor/discount/migrations/0068_promotion_start_end_date_indexes.py
@@ -0,0 +1,28 @@
+# Generated by Django 3.2.22 on 2023-12-14 09:41
+
+import django.contrib.postgres.indexes
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("discount", "0067_fulfill_promotionrule_variants"),
+ ]
+
+ atomic = False
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="promotion",
+ index=django.contrib.postgres.indexes.BTreeIndex(
+ fields=["start_date"], name="start_date_idx"
+ ),
+ ),
+ AddIndexConcurrently(
+ model_name="promotion",
+ index=django.contrib.postgres.indexes.BTreeIndex(
+ fields=["end_date"], name="end_date_idx"
+ ),
+ ),
+ ]
diff --git a/saleor/discount/migrations/0070_merge_20231215_0911.py b/saleor/discount/migrations/0070_merge_20231215_0911.py
new file mode 100644
index 0000000000..46187e93a1
--- /dev/null
+++ b/saleor/discount/migrations/0070_merge_20231215_0911.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.22 on 2023-12-15 09:11
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("discount", "0068_promotion_start_end_date_indexes"),
+ ("discount", "0069_merge_20231117_0959"),
+ ]
+
+ operations = []
diff --git a/saleor/discount/migrations/0071_merge_20231215_0943.py b/saleor/discount/migrations/0071_merge_20231215_0943.py
new file mode 100644
index 0000000000..4fa0926f3c
--- /dev/null
+++ b/saleor/discount/migrations/0071_merge_20231215_0943.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.23 on 2023-12-15 09:43
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("discount", "0070_alter_promotion_options"),
+ ("discount", "0070_merge_20231215_0911"),
+ ]
+
+ operations = []
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index a91e2c8095..9b6f423d9c 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -327,6 +327,10 @@ class Promotion(ModelWithMetadata):
"Manage promotions and vouchers.",
),
)
+ indexes = [
+ BTreeIndex(fields=["start_date"], name="start_date_idx"),
+ BTreeIndex(fields=["end_date"], name="end_date_idx"),
+ ]
def is_active(self, date=None):
if date is None:
@@ -369,6 +373,7 @@ class PromotionRule(models.Model):
catalogue_predicate = models.JSONField(
blank=True, default=dict, encoder=CustomJsonEncoder
)
+ variants = models.ManyToManyField("product.ProductVariant", blank=True)
reward_value_type = models.CharField(
max_length=255, choices=RewardValueType.CHOICES, blank=True, null=True
)
diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.py
index a71c0977a3..ab41a46016 100644
--- a/saleor/discount/tasks.py
+++ b/saleor/discount/tasks.py
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING
import graphene
import pytz
from celery.utils.log import get_task_logger
+from django.conf import settings
from django.db.models import Exists, F, OuterRef, Q, QuerySet
from ..celeryconf import app
@@ -32,6 +33,9 @@ from .models import (
if TYPE_CHECKING:
from uuid import UUID
+# Results in update time ~0.1s
+EXPIRED_RULES_BATCH_SIZE = 5000
+
task_logger = get_task_logger(__name__)
# Batch of size 100 takes ~1 sec and consumes ~3mb at peak
PROMOTION_TOGGLE_BATCH_SIZE = 100
@@ -83,9 +87,19 @@ def handle_promotion_toggle():
}
manager.sale_toggle(promotion, catalogues)
+ if ending_promotions:
+ clear_promotion_rule_variants_task.delay()
+
+ rule_ids = list(
+ PromotionRule.objects.filter(
+ Exists(promotions.filter(id=OuterRef("promotion_id")))
+ ).values_list("pk", flat=True)
+ )
if product_ids:
# Recalculate discounts of affected products
- update_products_discounted_prices_for_promotion_task.delay(product_ids)
+ update_products_discounted_prices_for_promotion_task.delay(
+ product_ids, rule_ids
+ )
starting_promotion_ids = ", ".join(
[str(staring_promo.id) for staring_promo in starting_promotions]
@@ -174,6 +188,28 @@ def fetch_promotion_variants_and_product_ids(promotions: "QuerySet[Promotion]"):
return promotion_id_to_variants, list(products.values_list("id", flat=True))
+def clear_promotion_rule_variants_task():
+ """Clear all promotion rule variants."""
+ promotions = Promotion.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).expired()
+ rules = PromotionRule.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(Exists(promotions.filter(id=OuterRef("promotion_id"))))
+ PromotionRuleVariant = PromotionRule.variants.through
+ rule_variants_id = list(
+ PromotionRuleVariant.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(Exists(rules.filter(pk=OuterRef("promotionrule_id"))))[
+ :EXPIRED_RULES_BATCH_SIZE
+ ]
+ .values_list("pk", flat=True)
+ )
+ if rule_variants_id:
+ PromotionRuleVariant.objects.filter(pk__in=rule_variants_id).delete()
+ clear_promotion_rule_variants_task.delay()
+
+
def decrease_voucher_code_usage_of_draft_orders(channel_id: int):
codes = Order.objects.filter(
channel_id=channel_id, status=OrderStatus.DRAFT, voucher_code__isnull=False
@@ -268,3 +304,34 @@ def update_discounted_prices_task():
products = Product.objects.filter(id__in=products_ids)
update_discounted_prices_for_promotion(products)
update_discounted_prices_task.delay()
+
+
+ name="saleor.discount.migrations.tasks.saleor3_17.set_promotion_rule_variants"
+)
+def set_promotion_rule_variants_task(start_id=None):
+ # WARNING: this function is run during `0067_fulfill_promotionrule_variants`
+ # migration, be careful while updating.
+ # This task can be deleted after we introduce a different process for calculating
+ # discounted prices for promotions.
+
+ # Results in update time ~0.4s and consumes ~20MB memory at peak
+ from ..product.utils.variants import fetch_variants_for_promotion_rules
+
+ PROMOTION_RULE_BATCH_SIZE = 250
+
+ promotions = Promotion.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).active()
+ kwargs = {"id__gt": start_id} if start_id else {}
+ rules = (
+ PromotionRule.objects.order_by("id")
+ .using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(Exists(promotions.filter(id=OuterRef("promotion_id"))), **kwargs)[
+ :PROMOTION_RULE_BATCH_SIZE
+ ]
+ )
+ if ids := list(rules.values_list("pk", flat=True)):
+ qs = PromotionRule.objects.filter(pk__in=ids)
+ fetch_variants_for_promotion_rules(rules=qs)
+ set_promotion_rule_variants_task.delay(ids[-1])
diff --git a/saleor/discount/tests/test_rounding_issue.py b/saleor/discount/tests/test_rounding_issue.py
index 1a92a2068e..78a32b4cc5 100644
--- a/saleor/discount/tests/test_rounding_issue.py
+++ b/saleor/discount/tests/test_rounding_issue.py
@@ -5,9 +5,11 @@ import pytest
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...checkout.utils import add_variant_to_checkout
+from ...discount.models import PromotionRule
from ...plugins.manager import get_plugins_manager
from ...product.models import Product, ProductVariantChannelListing
from ...product.utils.variant_prices import update_discounted_prices_for_promotion
+from ...product.utils.variants import fetch_variants_for_promotion_rules
from .. import DiscountValueType, RewardValueType
from ..models import Promotion
from ..utils import create_or_update_discount_objects_from_promotion_for_checkout
@@ -97,6 +99,7 @@ def test_rounding_issue_with_percentage_promotion(
variant_channel_listings, ["price_amount"]
)
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
update_discounted_prices_for_promotion(Product.objects.all())
checkout_info = fetch_checkout_info(
diff --git a/saleor/discount/tests/test_tasks.py b/saleor/discount/tests/test_tasks.py
index 321a6c4fc2..f4ce9dbcd4 100644
--- a/saleor/discount/tests/test_tasks.py
+++ b/saleor/discount/tests/test_tasks.py
@@ -4,6 +4,7 @@ from unittest.mock import ANY, patch
import graphene
import pytest
+from django.db.models import Exists, OuterRef
from django.utils import timezone
from freezegun import freeze_time
@@ -11,10 +12,12 @@ from ...order.models import Order
from .. import DiscountType, RewardValueType
from ..models import OrderDiscount, OrderLineDiscount, Promotion, PromotionRule
from ..tasks import (
+ clear_promotion_rule_variants_task,
decrease_voucher_codes_usage_task,
disconnect_voucher_codes_from_draft_orders_task,
fetch_promotion_variants_and_product_ids,
handle_promotion_toggle,
+ set_promotion_rule_variants_task,
)
@@ -54,6 +57,7 @@ def test_fetch_promotion_variants_and_product_ids(
@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.discount.tasks.clear_promotion_rule_variants_task.delay")
@patch(
"saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
)
@@ -65,6 +69,7 @@ def test_handle_promotion_toggle(
promotion_ended_mock,
sale_toggle_mock,
mock_update_products_discounted_prices_for_promotion_task,
+ mock_clear_promotion_rule_variants_task,
product_list,
):
# given
@@ -185,6 +190,53 @@ def test_handle_promotion_toggle(
product_list[2].id,
}
+ assert {rule_id for rule_id in args[1]} == {
+ rules[0].id,
+ rules[2].id,
+ }
+
+ mock_clear_promotion_rule_variants_task.assert_called_once()
+
+
+def test_clear_promotion_rule_variants_task(promotion_list):
+ # given
+ expired_promotion = promotion_list[-1]
+ expired_promotion.start_date = timezone.now() - timedelta(days=5)
+ expired_promotion.end_date = timezone.now() - timedelta(days=1)
+ expired_promotion.save(update_fields=["start_date", "end_date"])
+
+ PromotionRuleVariant = PromotionRule.variants.through
+ expired_rules = PromotionRule.objects.filter(promotion_id=expired_promotion.id)
+ rule_variants_count = PromotionRuleVariant.objects.count()
+ expired_rule_variants_count = PromotionRuleVariant.objects.filter(
+ Exists(expired_rules.filter(pk=OuterRef("promotionrule_id")))
+ ).count()
+ assert expired_rule_variants_count > 0
+
+ # when
+ clear_promotion_rule_variants_task()
+
+ # then
+ assert (
+ PromotionRuleVariant.objects.count()
+ == rule_variants_count - expired_rule_variants_count
+ )
+
+
+def test_set_promotion_rule_variants_task(promotion_list):
+ # given
+ Promotion.objects.update(start_date=timezone.now() - timedelta(days=5))
+ PromotionRuleVariant = PromotionRule.variants.through
+ PromotionRuleVariant.objects.all().delete()
+
+ # when
+ set_promotion_rule_variants_task()
+
+ # then
+ assert set(
+ PromotionRuleVariant.objects.values_list("promotionrule_id", flat=True)
+ ) == set(PromotionRule.objects.values_list("id", flat=True))
+
def test_decrease_voucher_code_usage_task_multiple_use(
draft_order_list_with_multiple_use_voucher, voucher_multiple_use
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.py
index 4445e87e15..ae25fc3f22 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,22 +52,20 @@ def test_variant_discounts_multiple_promotions(product, channel_USD):
rule_high.channels.add(channel_USD)
rules_info_per_promotion_id = {
- promotion_low_discount.id: [
- PromotionRuleInfo(
- rule=rule_low,
- variants=[variant],
- variant_ids=[variant.id],
- channel_ids=[channel_USD.id],
- )
- ],
- promotion_high_discount.id: [
- PromotionRuleInfo(
- rule=rule_high,
- variants=[variant],
- variant_ids=[variant.id],
- channel_ids=[channel_USD.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_channel_listing = variant.channel_listings.get(channel=channel_USD)
@@ -76,7 +74,7 @@ def test_variant_discounts_multiple_promotions(product, channel_USD):
# when
applied_discounts = calculate_discounted_price_for_promotions(
price=price,
- rules_info_per_promotion_id=rules_info_per_promotion_id,
+ rules_info_per_variant_and_promotion_id=rules_info_per_promotion_id,
channel=channel_USD,
variant_id=variant.id,
)
@@ -145,28 +143,24 @@ 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 = {
- promotion_low_discount.id: [
- PromotionRuleInfo(
- rule=rule_low_1,
- variants=[variant],
- variant_ids=[variant.id],
- channel_ids=[channel_USD.id],
- ),
- PromotionRuleInfo(
- rule=rule_low_2,
- variants=[variant],
- variant_ids=[variant.id],
- channel_ids=[channel_USD.id],
- ),
- ],
- promotion_high_discount.id: [
- PromotionRuleInfo(
- rule=rule_high_1,
- variants=[variant],
- variant_ids=[variant.id],
- channel_ids=[channel_USD.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_channel_listing = variant.channel_listings.get(channel=channel_USD)
@@ -175,7 +169,7 @@ def test_variant_discounts_multiple_promotions_and_rules(product, channel_USD):
# when
applied_discounts = calculate_discounted_price_for_promotions(
price=price,
- rules_info_per_promotion_id=rules_info_per_promotion_id,
+ rules_info_per_variant_and_promotion_id=rules_info_per_promotion_id,
channel=channel_USD,
variant_id=variant.id,
)
diff --git a/saleor/discount/tests/test_utils/test_fetch_active_promotion_rules.py b/saleor/discount/tests/test_utils/test_fetch_active_promotion_rules.py
deleted file mode 100644
index f6d8e11666..0000000000
--- a/saleor/discount/tests/test_utils/test_fetch_active_promotion_rules.py
+++ /dev/null
@@ -1,110 +0,0 @@
-from datetime import timedelta
-
-from django.utils import timezone
-
-from ....discount.models import Promotion
-from ....product.models import ProductVariant
-from ...utils import fetch_active_promotion_rules
-
-
-def test_fetch_active_promotion_rules(promotion, product, channel_USD):
- # given
- variants = ProductVariant.objects.all()
-
- # when
- rules_per_promotion = fetch_active_promotion_rules(variants)
-
- # then
- rules_info = rules_per_promotion.get(promotion.id)
- assert rules_info
- assert len(rules_info) == 2
-
- rules_info.sort(key=lambda info: info.rule.name)
-
- fixed_rule, percentage_rule = promotion.rules.all().order_by("name")
- fixed_rule_info, percentage_rule_info = rules_info
- assert fixed_rule_info.rule == fixed_rule
- assert fixed_rule_info.variant_ids == []
- assert not fixed_rule_info.variants
- assert fixed_rule_info.channel_ids == [channel_USD.id]
-
- assert percentage_rule_info.rule == percentage_rule
- assert set(percentage_rule_info.variant_ids) == {variant.id for variant in variants}
- assert {variant for variant in percentage_rule_info.variants} == {
- variant for variant in variants
- }
- assert percentage_rule_info.channel_ids == [channel_USD.id]
-
-
-def test_fetch_active_promotion_rules_from_different_promotions(
- promotion_list, product, collection
-):
- # given
- Promotion.objects.update(start_date=timezone.now() - timedelta(days=1))
- variants = ProductVariant.objects.all()
-
- # when
- rules_per_promotion = fetch_active_promotion_rules(variants)
-
- # then
- assert len(rules_per_promotion) == len(promotion_list)
-
-
-def test_fetch_active_promotion_rules_no_active_rules(product):
- # given
- variants = ProductVariant.objects.all()
-
- # when
- rules_per_promotion = fetch_active_promotion_rules(variants)
-
- # then
- assert not rules_per_promotion
-
-
-def test_fetch_active_promotion_rules_with_given_date(promotion, product, channel_USD):
- # given
- variants = ProductVariant.objects.all()
-
- # when
- rules_per_promotion = fetch_active_promotion_rules(
- variants, date=timezone.now() + timedelta(days=1)
- )
-
- # then
- rules_info = rules_per_promotion.get(promotion.id)
- assert rules_info
- assert len(rules_info) == 2
-
- rules_info.sort(key=lambda info: info.rule.name)
-
- fixed_rule, percentage_rule = promotion.rules.all().order_by("name")
- fixed_rule_info, percentage_rule_info = rules_info
- assert fixed_rule_info.rule == fixed_rule
- assert fixed_rule_info.variant_ids == []
- assert not fixed_rule_info.variants
- assert fixed_rule_info.channel_ids == [channel_USD.id]
-
- assert percentage_rule_info.rule == percentage_rule
- assert set(percentage_rule_info.variant_ids) == {variant.id for variant in variants}
- assert {variant for variant in percentage_rule_info.variants} == {
- variant for variant in variants
- }
- assert percentage_rule_info.channel_ids == [channel_USD.id]
-
-
-def test_fetch_active_promotion_rules_no_matching_rules_for_given_date(
- promotion, product
-):
- # given
- promotion.start_date = timezone.now() + timedelta(days=5)
- promotion.save(update_fields=["start_date"])
-
- variants = ProductVariant.objects.all()
-
- # when
- rules_per_promotion = fetch_active_promotion_rules(
- variants, date=timezone.now() + timedelta(days=1)
- )
-
- # then
- assert not rules_per_promotion
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.py
new file mode 100644
index 0000000000..d687ca682a
--- /dev/null
+++ b/saleor/discount/tests/test_utils/test_get_variants_to_promotions_map.py
@@ -0,0 +1,161 @@
+from decimal import Decimal
+
+import graphene
+
+from ....product.models import ProductVariant
+from ....product.utils.variants import fetch_variants_for_promotion_rules
+from ... import PromotionRuleInfo, RewardValueType
+from ...models import Promotion, PromotionRule
+from ...utils import get_variants_to_promotions_map
+
+
+def test_get_variants_to_promotions_map(
+ promotion_without_rules, product, product_with_two_variants, channel_USD
+):
+ # given
+ promotion = promotion_without_rules
+ variant = product.variants.first()
+
+ percentage_reward_value = Decimal("10")
+ reward_value = Decimal("2")
+ rule_1 = promotion.rules.create(
+ name="Percentage promotion rule",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=percentage_reward_value,
+ )
+ rule_2 = promotion.rules.create(
+ name="Fixed promotion rule",
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [
+ graphene.Node.to_global_id("Product", product_with_two_variants.id)
+ ]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule_1.channels.add(channel_USD)
+ rule_2.channels.add(channel_USD)
+ rule_1.variants.add(variant)
+ rule_2.variants.set(product_with_two_variants.variants.all())
+
+ variants = ProductVariant.objects.all()
+
+ # when
+ rules_info_per_variant_and_promotion_id = get_variants_to_promotions_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]),
+ ]
+ }
+
+ 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]),
+ ]
+ }
+
+
+def test_get_variants_to_promotions_map_from_different_promotions(
+ promotion_without_rules, product, channel_USD
+):
+ # given
+ promotion = promotion_without_rules
+ promotion_2 = Promotion.objects.create(
+ name="Promotion",
+ )
+ variant = product.variants.first()
+
+ percentage_reward_value = Decimal("10")
+ reward_value = Decimal("2")
+ rule_1 = promotion.rules.create(
+ name="Percentage promotion rule",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=percentage_reward_value,
+ )
+ rule_2 = promotion_2.rules.create(
+ name="Fixed promotion rule",
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [graphene.Node.to_global_id("Product", product.id)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule_1.channels.add(channel_USD)
+ rule_2.channels.add(channel_USD)
+ rule_1.variants.add(variant)
+ rule_2.variants.add(variant)
+
+ variants = ProductVariant.objects.all()
+
+ # when
+ rules_info_per_variant_and_promotion_id = get_variants_to_promotions_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])
+ ]
+
+
+def test_get_variants_to_promotions_map_no_active_rules(product):
+ # given
+ variants = ProductVariant.objects.all()
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+
+ # when
+ rules_per_promotion = get_variants_to_promotions_map(variants)
+
+ # then
+ assert not rules_per_promotion
+
+
+def test_get_variants_to_promotions_map_no_matching_rules(
+ product_with_two_variants, variant, promotion_without_rules
+):
+ # given
+ promotion = promotion_without_rules
+
+ percentage_reward_value = Decimal("10")
+ rule = promotion.rules.create(
+ name="Percentage promotion rule",
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [
+ graphene.Node.to_global_id("Product", product_with_two_variants.id)
+ ]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=percentage_reward_value,
+ )
+ rule.variants.set(product_with_two_variants.variants.all())
+
+ variants = ProductVariant.objects.filter(id=variant.id)
+
+ # when
+ rules_per_promotion = get_variants_to_promotions_map(variants)
+
+ # then
+ assert not rules_per_promotion
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index fa087668b5..1edf6d303d 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -1,4 +1,3 @@
-import datetime
from collections import defaultdict
from collections.abc import Iterable, Iterator
from decimal import ROUND_HALF_UP, Decimal
@@ -21,6 +20,7 @@ from ..channel.models import Channel
from ..core.taxes import zero_money
from ..core.utils.promo_code import InvalidPromoCode
from ..discount.models import VoucherCustomer
+from ..product.models import Product, ProductVariant
from . import DiscountType, PromotionRuleInfo
from .models import (
CheckoutLineDiscount,
@@ -173,15 +173,20 @@ def calculate_discounted_price_for_rules(
def calculate_discounted_price_for_promotions(
*,
price: Money,
- rules_info_per_promotion_id: dict[UUID, list[PromotionRuleInfo]],
+ rules_info_per_variant_and_promotion_id: dict[
+ int, dict[UUID, list[PromotionRuleInfo]]
+ ],
channel: "Channel",
- variant_id: Optional[int] = None,
+ variant_id: int,
) -> list[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, variant_id
+ price, rules_info_per_promotion_id, channel
)
return applied_discounts
@@ -190,7 +195,6 @@ def get_best_promotion_discount(
price: Money,
rules_info_per_promotion_id: dict[UUID, list[PromotionRuleInfo]],
channel: "Channel",
- variant_id: Optional[int] = None,
) -> list[tuple[UUID, Money]]:
"""Return the rules with the discount amounts for the best promotion.
@@ -207,7 +211,6 @@ def get_best_promotion_discount(
for rule_id, discount in get_product_promotion_discounts(
rules_info=rules_info,
channel=channel,
- variant_id=variant_id,
)
]
for _, rules_info in rules_info_per_promotion_id.items()
@@ -227,12 +230,11 @@ def get_product_promotion_discounts(
*,
rules_info: list[PromotionRuleInfo],
channel: "Channel",
- variant_id: Optional[int],
) -> Iterator[tuple[UUID, Callable]]:
- """Return promotion rule id, discount value for all rules applicable on product."""
+ """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, variant_id)
+ yield get_product_discount_on_promotion(rule_info, channel)
except NotApplicable:
pass
@@ -240,10 +242,9 @@ def get_product_promotion_discounts(
def get_product_discount_on_promotion(
rule_info: PromotionRuleInfo,
channel: "Channel",
- variant_id: Optional[int] = None,
) -> tuple[UUID, Callable]:
"""Return rule id, discount value if rule applied or raise NotApplicable."""
- if variant_id in rule_info.variant_ids and channel.id in rule_info.channel_ids:
+ 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")
@@ -503,30 +504,55 @@ def _update_line_discount(
updated_fields.append("translated_name")
-def fetch_active_promotion_rules(
+def get_variants_to_promotions_map(
variant_qs: "ProductVariantQueryset",
- date: Optional[datetime.date] = None,
-) -> dict[UUID, list[PromotionRuleInfo]]:
- from ..graphql.discount.utils import get_variants_for_predicate
-
- rules_info_per_promotion_id = defaultdict(list)
+) -> dict[int, dict[UUID, 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]
+ }
+ }
+ """
+ rules_info_per_variant_and_promotion_id: dict[
+ int, dict[UUID, list[PromotionRuleInfo]]
+ ] = defaultdict(lambda: defaultdict(list))
+
+ promotions = Promotion.objects.active()
+ PromotionRuleVariant = PromotionRule.variants.through
+ promotion_rule_variants = PromotionRuleVariant.objects.filter(
+ Exists(variant_qs.filter(id=OuterRef("productvariant_id")))
+ )
- promotions = Promotion.objects.active(date)
+ # fetch rules only for active promotions
rules = PromotionRule.objects.filter(
- Exists(promotions.filter(id=OuterRef("promotion_id")))
+ Exists(promotions.filter(id=OuterRef("promotion_id"))),
+ Exists(promotion_rule_variants.filter(promotionrule_id=OuterRef("pk"))),
).prefetch_related("channels")
rule_to_channel_ids_map = _get_rule_to_channel_ids_map(rules)
- for rule in rules.iterator():
- variants = get_variants_for_predicate(rule.catalogue_predicate, variant_qs)
- rules_info_per_promotion_id[rule.promotion_id].append(
+ rules_in_bulk = rules.in_bulk()
+
+ for promotion_rule_variant in list(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_and_promotion_id[variant_id][rule.promotion_id].append(
PromotionRuleInfo(
rule=rule,
- variants=variants,
- variant_ids=list(variants.values_list("id", flat=True)),
- channel_ids=rule_to_channel_ids_map.get(rule.id, []),
+ channel_ids=rule_to_channel_ids_map.get(rule_id, []),
)
)
- return rules_info_per_promotion_id
+
+ return rules_info_per_variant_and_promotion_id
def _get_rule_to_channel_ids_map(rules: QuerySet):
@@ -540,3 +566,18 @@ def _get_rule_to_channel_ids_map(rules: QuerySet):
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"))))
diff --git a/saleor/graphql/discount/mutations/bulk_mutations.py b/saleor/graphql/discount/mutations/bulk_mutations.py
index 95138c762e..6074283f47 100644
--- a/saleor/graphql/discount/mutations/bulk_mutations.py
+++ b/saleor/graphql/discount/mutations/bulk_mutations.py
@@ -6,9 +6,9 @@ from django.db.models import Exists, OuterRef, QuerySet
from ....discount import models
from ....discount.error_codes import DiscountErrorCode
+from ....discount.utils import get_current_products_for_rules
from ....permission.enums import DiscountPermissions
-from ....product import models as product_models
-from ....product.tasks import update_products_discounted_prices_for_promotion_task
+from ....product.tasks import update_discounted_prices_task
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...core import ResolveInfo
@@ -22,10 +22,7 @@ from ...core.utils import (
)
from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import Sale, Voucher
-from ..utils import (
- convert_migrated_sale_predicate_to_catalogue_info,
- get_variants_for_predicate,
-)
+from ..utils import convert_migrated_sale_predicate_to_catalogue_info
class SaleBulkDelete(ModelBulkDeleteMutation):
@@ -90,7 +87,7 @@ class SaleBulkDelete(ModelBulkDeleteMutation):
(sale, cls.get_catalogue_info(sale_id_to_rule.get(sale.id)))
for sale in queryset
]
- product_ids = cls.get_product_ids(sale_id_to_rule)
+ product_ids = cls.get_product_ids_for_promotions(queryset)
queryset.delete()
@@ -100,8 +97,7 @@ class SaleBulkDelete(ModelBulkDeleteMutation):
cls.call_event(
manager.sale_deleted, sale, catalogue_info, webhooks=webhooks
)
-
- update_products_discounted_prices_for_promotion_task.delay(list(product_ids))
+ update_discounted_prices_task.delay(list(product_ids))
@classmethod
def get_sale_and_rules(cls, qs: QuerySet[models.Promotion]):
@@ -118,15 +114,11 @@ class SaleBulkDelete(ModelBulkDeleteMutation):
)
@classmethod
- def get_product_ids(cls, get_sale_and_rules: dict):
- variants = product_models.ProductVariant.objects.none()
- for rule in get_sale_and_rules.values():
- variants |= get_variants_for_predicate(rule.catalogue_predicate)
-
- products = product_models.Product.objects.filter(
- Exists(variants.filter(product_id=OuterRef("id")))
+ def get_product_ids_for_promotions(cls, qs: QuerySet[models.Promotion]):
+ rules = models.PromotionRule.objects.filter(
+ Exists(qs.filter(id=OuterRef("promotion_id")))
)
- return set(products.values_list("id", flat=True))
+ return set(get_current_products_for_rules(rules).values_list("id", flat=True))
class VoucherBulkDelete(ModelBulkDeleteMutation):
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_bulk_delete.py b/saleor/graphql/discount/mutations/promotion/promotion_bulk_delete.py
index eb1bb93e37..149aabb4e0 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_bulk_delete.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_bulk_delete.py
@@ -2,9 +2,9 @@ import graphene
from django.db.models import Exists, OuterRef, QuerySet
from .....discount import models
+from .....discount.utils import get_current_products_for_rules
from .....permission.enums import DiscountPermissions
-from .....product import models as product_models
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
+from .....product.tasks import update_discounted_prices_task
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.utils import get_webhooks_for_event
from ....core import ResolveInfo
@@ -15,7 +15,6 @@ from ....core.types import DiscountError, NonNullList
from ....core.utils import WebhookEventInfo
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import Promotion
-from ...utils import get_variants_for_predicate
class PromotionBulkDelete(ModelBulkDeleteMutation):
@@ -48,17 +47,12 @@ class PromotionBulkDelete(ModelBulkDeleteMutation):
for promotion in promotions:
cls.call_event(manager.promotion_deleted, promotion, webhooks=webhooks)
- update_products_discounted_prices_for_promotion_task.delay(list(product_ids))
+ update_discounted_prices_task.delay(list(product_ids))
@classmethod
def get_product_ids(cls, qs: QuerySet[models.Promotion]):
rules = models.PromotionRule.objects.filter(
Exists(qs.filter(id=OuterRef("promotion_id")))
)
- variants = product_models.ProductVariant.objects.none()
- for rule in rules:
- variants |= get_variants_for_predicate(rule.catalogue_predicate)
- products = product_models.Product.objects.filter(
- Exists(variants.filter(product_id=OuterRef("id")))
- )
+ products = get_current_products_for_rules(rules)
return set(products.values_list("id", flat=True))
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_delete.py b/saleor/graphql/discount/mutations/promotion/promotion_delete.py
index 4cde3dd251..bfd8f067fb 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_delete.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_delete.py
@@ -2,16 +2,16 @@ import graphene
from django.db import transaction
from .....discount import models
+from .....discount.utils import get_current_products_for_rules
from .....graphql.core.mutations import ModelDeleteMutation
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
+from .....product.tasks import update_discounted_prices_task
from .....webhook.event_types import WebhookEventAsyncType
from ....core import ResolveInfo
from ....core.descriptions import ADDED_IN_317, PREVIEW_FEATURE
from ....core.doc_category import DOC_CATEGORY_DISCOUNTS
from ....core.types import Error
from ....core.utils import WebhookEventInfo
-from ....discount.utils import get_products_for_promotion
from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import PromotionDeleteErrorCode
from ...types import Promotion
@@ -48,7 +48,9 @@ class PromotionDelete(ModelDeleteMutation):
instance = cls.get_node_or_error(info, id, only_type=Promotion)
manager = get_plugin_manager_promise(info.context).get()
product_ids = list(
- get_products_for_promotion(instance).values_list("id", flat=True)
+ get_current_products_for_rules(instance.rules.all()).values_list(
+ "id", flat=True
+ )
)
promotion_id = instance.id
@@ -56,5 +58,5 @@ class PromotionDelete(ModelDeleteMutation):
response = super().perform_mutation(root, info, id=id)
instance.id = promotion_id
cls.call_event(manager.promotion_deleted, instance)
- update_products_discounted_prices_for_promotion_task.delay(product_ids)
+ update_discounted_prices_task.delay(product_ids)
return response
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py
index cde00d3212..84ffedb353 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py
@@ -5,7 +5,7 @@ from django.core.exceptions import ValidationError
from .....discount import events, models
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
+from .....product.tasks import update_discounted_prices_task
from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
@@ -68,9 +68,9 @@ class PromotionRuleCreate(ModelMutation):
@classmethod
def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
- products = get_products_for_rule(instance)
+ products = get_products_for_rule(instance, update_rule_variants=True)
if products:
- update_products_discounted_prices_for_promotion_task.delay(
+ update_discounted_prices_task.delay(
list(products.values_list("id", flat=True))
)
clear_promotion_old_sale_id(instance.promotion, save=True)
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_delete.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_delete.py
index e7acd372b2..450d96d327 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_delete.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_delete.py
@@ -1,9 +1,10 @@
import graphene
from .....discount import events, models
+from .....discount.utils import get_current_products_for_rules
from .....graphql.core.mutations import ModelDeleteMutation
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
+from .....product.tasks import update_discounted_prices_task
from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
@@ -14,7 +15,6 @@ from ....core.utils import WebhookEventInfo
from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import PromotionRuleDeleteErrorCode
from ...types import PromotionRule
-from ...utils import get_products_for_rule
from ..utils import clear_promotion_old_sale_id
@@ -50,7 +50,9 @@ class PromotionRuleDelete(ModelDeleteMutation):
instance = cls.get_instance(info, external_reference=external_reference, id=id)
cls.clean_instance(info, instance)
- products = get_products_for_rule(instance)
+ products = get_current_products_for_rules(
+ models.PromotionRule.objects.filter(id=instance.id)
+ )
product_ids = list(products.values_list("id", flat=True))
db_id = instance.id
@@ -64,7 +66,7 @@ class PromotionRuleDelete(ModelDeleteMutation):
instance.id = db_id
if product_ids:
- update_products_discounted_prices_for_promotion_task.delay(product_ids)
+ update_discounted_prices_task.delay(product_ids)
app = get_app_promise(info.context).get()
events.rule_deleted_event(info.context.user, app, [instance])
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py
index 0253011a90..9992697c2f 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py
@@ -3,8 +3,9 @@ from django.core.exceptions import ValidationError
from django.db import transaction
from .....discount import RewardValueType, events, models
+from .....discount.utils import get_current_products_for_rules
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
+from .....product.tasks import update_discounted_prices_task
from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
@@ -79,7 +80,9 @@ class PromotionRuleUpdate(ModelMutation):
cleaned_input = cls.clean_input(info, instance, data)
instance = cls.construct_instance(instance, cleaned_input)
- previous_products = get_products_for_rule(instance)
+ previous_products = get_current_products_for_rules(
+ models.PromotionRule.objects.filter(id=instance.id)
+ )
previous_product_ids = set(previous_products.values_list("id", flat=True))
cls.clean_instance(info, instance)
cls.save(info, instance, cleaned_input)
@@ -194,12 +197,10 @@ class PromotionRuleUpdate(ModelMutation):
@classmethod
def post_save_actions(cls, info: ResolveInfo, instance, previous_product_ids):
- products = get_products_for_rule(instance)
+ products = get_products_for_rule(instance, update_rule_variants=True)
product_ids = set(products.values_list("id", flat=True)) | previous_product_ids
if product_ids:
- update_products_discounted_prices_for_promotion_task.delay(
- list(product_ids)
- )
+ update_discounted_prices_task.delay(list(product_ids))
clear_promotion_old_sale_id(instance.promotion, save=True)
app = get_app_promise(info.context).get()
events.rule_updated_event(info.context.user, app, [instance])
diff --git a/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py b/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
index 42742a2862..0a1996f083 100644
--- a/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
+++ b/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
@@ -3,19 +3,19 @@ from typing import Union
import graphene
from django.core.exceptions import ValidationError
+from django.db.models import Exists, OuterRef
from .....discount.error_codes import DiscountErrorCode
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
+from .....product import models as product_models
+from .....product.tasks import update_discounted_prices_task
from .....product.utils import get_products_ids_without_variants
from ....core import ResolveInfo
from ....core.mutations import BaseMutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ....product.types import Category, Collection, Product, ProductVariant
from ...types import Sale
-from ...utils import (
- convert_catalogue_info_into_predicate,
- get_product_ids_for_predicate,
-)
+from ...utils import convert_catalogue_info_into_predicate, get_variants_for_predicate
+from ..utils import update_variants_for_promotion
from ..voucher.voucher_add_catalogues import CatalogueInput
CatalogueInfo = defaultdict[str, set[Union[int, str]]]
@@ -51,8 +51,14 @@ class SaleBaseCatalogueMutation(BaseMutation):
previous_predicate = convert_catalogue_info_into_predicate(previous_catalogue)
new_predicate = convert_catalogue_info_into_predicate(new_catalogue)
- previous_product_ids = get_product_ids_for_predicate(previous_predicate)
- new_product_ids = get_product_ids_for_predicate(new_predicate)
+ previous_product_ids = cls.get_product_ids_for_predicate(previous_predicate)
+ new_variants = get_variants_for_predicate(new_predicate)
+ new_product_ids = set(
+ product_models.Product.objects.filter(
+ Exists(new_variants.filter(product_id=OuterRef("id")))
+ ).values_list("id", flat=True)
+ )
+ update_variants_for_promotion(new_variants, promotion)
if previous_product_ids != new_product_ids:
is_add_mutation = len(new_product_ids) > len(previous_product_ids)
@@ -60,9 +66,15 @@ class SaleBaseCatalogueMutation(BaseMutation):
product_ids = new_product_ids - previous_product_ids
else:
product_ids = previous_product_ids - new_product_ids
- update_products_discounted_prices_for_promotion_task.delay(
- list(product_ids)
- )
+ update_discounted_prices_task.delay(list(product_ids))
+
+ @classmethod
+ def get_product_ids_for_predicate(cls, predicate: dict) -> set[int]:
+ variants = get_variants_for_predicate(predicate)
+ products = product_models.Product.objects.filter(
+ Exists(variants.filter(product_id=OuterRef("id")))
+ )
+ return set(products.values_list("id", flat=True))
@classmethod
def get_catalogue_info_from_input(cls, input) -> CatalogueInfo:
diff --git a/saleor/graphql/discount/mutations/sale/sale_delete.py b/saleor/graphql/discount/mutations/sale/sale_delete.py
index e2b2abc219..8b937d3387 100644
--- a/saleor/graphql/discount/mutations/sale/sale_delete.py
+++ b/saleor/graphql/discount/mutations/sale/sale_delete.py
@@ -5,7 +5,7 @@ from .....discount import models
from .....discount.error_codes import DiscountErrorCode
from .....graphql.core.mutations import ModelDeleteMutation
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
+from .....product.tasks import update_discounted_prices_task
from .....webhook.event_types import WebhookEventAsyncType
from ....channel import ChannelContext
from ....core import ResolveInfo
@@ -68,9 +68,7 @@ class SaleDelete(ModelDeleteMutation):
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.sale_deleted, promotion, previous_catalogue)
- update_products_discounted_prices_for_promotion_task.delay(
- list(product_ids)
- )
+ update_discounted_prices_task.delay(list(product_ids))
return response
diff --git a/saleor/graphql/discount/mutations/sale/sale_update.py b/saleor/graphql/discount/mutations/sale/sale_update.py
index 3ca82501ed..82c53b9667 100644
--- a/saleor/graphql/discount/mutations/sale/sale_update.py
+++ b/saleor/graphql/discount/mutations/sale/sale_update.py
@@ -3,13 +3,15 @@ from datetime import datetime
import graphene
import pytz
from django.core.exceptions import ValidationError
+from django.db.models import Exists, OuterRef
from .....core.tracing import traced_atomic_transaction
from .....discount import models
from .....discount.error_codes import DiscountErrorCode
from .....discount.utils import CATALOGUE_FIELDS
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
+from .....product import models as product_models
+from .....product.tasks import update_discounted_prices_task
from .....webhook.event_types import WebhookEventAsyncType
from ....channel import ChannelContext
from ....core import ResolveInfo
@@ -29,7 +31,9 @@ from ...utils import (
convert_migrated_sale_predicate_to_catalogue_info,
create_catalogue_predicate,
get_products_for_rule,
+ get_variants_for_predicate,
)
+from ..utils import update_variants_for_promotion
from .sale_create import SaleInput
@@ -186,14 +190,15 @@ class SaleUpdate(ModelMutation):
field in input.keys()
for field in [*CATALOGUE_FIELDS, "start_date", "end_date", "type"]
):
- products = get_products_for_rule(rule)
- if (
- product_ids := set(products.values_list("id", flat=True))
- | previous_product_ids
- ):
- update_products_discounted_prices_for_promotion_task.delay(
- list(product_ids)
- )
+ variants = get_variants_for_predicate(current_predicate)
+ product_ids = set(
+ product_models.Product.objects.filter(
+ Exists(variants.filter(product_id=OuterRef("id")))
+ ).values_list("id", flat=True)
+ )
+ update_variants_for_promotion(variants, promotion)
+ if product_ids | previous_product_ids:
+ update_discounted_prices_task.delay(list(product_ids))
@classmethod
def send_sale_notifications(
diff --git a/saleor/graphql/discount/mutations/utils.py b/saleor/graphql/discount/mutations/utils.py
index f345f1fade..d6920aa8fc 100644
--- a/saleor/graphql/discount/mutations/utils.py
+++ b/saleor/graphql/discount/mutations/utils.py
@@ -1,9 +1,12 @@
from collections import defaultdict
import graphene
+from django.db import transaction
+from django.db.models import Exists, OuterRef, QuerySet
-from ....discount.models import Promotion
+from ....discount.models import Promotion, PromotionRule
from ....discount.utils import CatalogueInfo
+from ....product.models import ProductVariant
CATALOGUE_FIELD_TO_TYPE_NAME = {
"categories": "Category",
@@ -32,3 +35,28 @@ def clear_promotion_old_sale_id(promotion: Promotion, *, save=False):
promotion.old_sale_id = None
if save:
promotion.save(update_fields=["old_sale_id"])
+
+
+def update_variants_for_promotion(
+ variants: QuerySet["ProductVariant"], promotion: "Promotion"
+):
+ PromotionRuleVariant = PromotionRule.variants.through
+ rules = PromotionRule.objects.filter(promotion_id=promotion.id)
+ promotion_rule_variants = []
+ for rule_id in promotion.rules.values_list("id", flat=True):
+ promotion_rule_variants.extend(
+ [
+ PromotionRuleVariant(
+ promotionrule_id=rule_id, productvariant_id=variant.pk
+ )
+ for variant in variants
+ ]
+ )
+ with transaction.atomic():
+ # Clear existing variants assigned to promotion rules
+ PromotionRuleVariant.objects.filter(
+ Exists(rules.filter(id=OuterRef("promotionrule_id")))
+ ).delete()
+ PromotionRuleVariant.objects.bulk_create(
+ promotion_rule_variants, ignore_conflicts=True
+ )
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_bulk_delete.py b/saleor/graphql/discount/tests/mutations/test_promotion_bulk_delete.py
index f054ed2804..a7e5e63a25 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_bulk_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_bulk_delete.py
@@ -77,11 +77,9 @@ def test_delete_promotions_by_app(
@mock.patch("saleor.plugins.manager.PluginsManager.promotion_deleted")
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
[email protected]("saleor.product.tasks.update_discounted_prices_task.delay")
def test_delete_promotions_trigger_webhooks(
- update_products_discounted_prices_for_promotion_task,
+ update_discounted_prices_task,
deleted_webhook_mock,
staff_api_client,
promotion_list,
@@ -103,5 +101,5 @@ def test_delete_promotions_trigger_webhooks(
)
# then
- update_products_discounted_prices_for_promotion_task.called_once()
+ update_discounted_prices_task.called_once()
assert deleted_webhook_mock.call_count == len(promotion_list)
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_delete.py b/saleor/graphql/discount/tests/mutations/test_promotion_delete.py
index 6e7a5da675..e64f81f4dc 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_delete.py
@@ -22,13 +22,11 @@ PROMOTION_DELETE_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_deleted")
def test_promotion_delete_by_staff_user(
promotion_deleted_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
permission_group_manage_discounts,
promotion,
@@ -50,16 +48,14 @@ def test_promotion_delete_by_staff_user(
with pytest.raises(promotion._meta.model.DoesNotExist):
promotion.refresh_from_db()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_deleted")
def test_promotion_delete_by_staff_app(
promotion_deleted_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
promotion,
@@ -81,16 +77,14 @@ def test_promotion_delete_by_staff_app(
with pytest.raises(promotion._meta.model.DoesNotExist):
promotion.refresh_from_db()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_deleted")
def test_promotion_delete_by_customer(
promotion_deleted_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
api_client,
promotion,
):
@@ -104,4 +98,4 @@ def test_promotion_delete_by_customer(
assert_no_permission(response)
promotion_deleted_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py b/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py
index 61117f4c50..fd643fc318 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py
@@ -45,11 +45,9 @@ PROMOTION_RULE_CREATE_MUTATION = """
@patch("saleor.plugins.manager.PluginsManager.promotion_rule_created")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_by_staff_user(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
promotion_rule_created_mock,
staff_api_client,
permission_group_manage_discounts,
@@ -128,18 +126,14 @@ def test_promotion_rule_create_by_staff_user(
assert rule_data["rewardValue"] == reward_value
assert rule_data["promotion"]["id"] == promotion_id
assert promotion.rules.count() == rules_count + 1
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ update_discounted_prices_task_mock.assert_called_once_with([product.id])
rule = promotion.rules.last()
promotion_rule_created_mock.assert_called_once_with(rule)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_by_app(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
description_json,
@@ -203,16 +197,14 @@ def test_promotion_rule_create_by_app(
assert rule_data["rewardValue"] == reward_value
assert rule_data["promotion"]["id"] == promotion_id
assert promotion.rules.count() == rules_count + 1
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
+ update_discounted_prices_task_mock.assert_called_once_with(
[category.products.first().id]
)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_by_customer(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
api_client,
description_json,
channel_USD,
@@ -256,7 +248,7 @@ def test_promotion_rule_create_by_customer(
# when
response = api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
assert_no_permission(response)
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
def test_promotion_rule_create_missing_catalogue_predicate(
@@ -783,11 +775,9 @@ def test_promotion_rule_create_percentage_value_above_100(
assert promotion.rules.count() == rules_count
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_clears_old_sale_id(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
permission_group_manage_discounts,
description_json,
@@ -850,9 +840,7 @@ def test_promotion_rule_create_clears_old_sale_id(
assert rule_data["rewardValue"] == reward_value
assert rule_data["promotion"]["id"] == promotion_id
assert promotion.rules.count() == rules_count + 1
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ update_discounted_prices_task_mock.assert_called_once_with([product.id])
promotion.refresh_from_db()
assert promotion.old_sale_id is None
@@ -910,11 +898,9 @@ def test_promotion_rule_create_events(
@patch("saleor.plugins.manager.PluginsManager.promotion_rule_created")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_serializable_decimal_in_predicate(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
promotion_rule_created_mock,
staff_api_client,
permission_group_manage_discounts,
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py b/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py
index 5e8fc42899..8b051b05e2 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py
@@ -35,11 +35,9 @@ PROMOTION_RULE_DELETE_MUTATION = """
@patch("saleor.plugins.manager.PluginsManager.promotion_rule_deleted")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_delete_by_staff_user(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
promotion_rule_deleted_mock,
staff_api_client,
permission_group_manage_discounts,
@@ -61,17 +59,13 @@ def test_promotion_rule_delete_by_staff_user(
with pytest.raises(rule._meta.model.DoesNotExist):
rule.refresh_from_db()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ update_discounted_prices_task_mock.assert_called_once_with([product.id])
promotion_rule_deleted_mock.assert_called_once_with(rule)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_delete_by_staff_app(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
promotion,
@@ -95,16 +89,12 @@ def test_promotion_rule_delete_by_staff_app(
with pytest.raises(rule._meta.model.DoesNotExist):
rule.refresh_from_db()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ update_discounted_prices_task_mock.assert_called_once_with([product.id])
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_delete_by_customer(
- update_products_discounted_prices_for_promotion_task_mock, api_client, promotion
+ update_discounted_prices_task_mock, api_client, promotion
):
# given
rule = promotion.rules.first()
@@ -115,14 +105,12 @@ def test_promotion_rule_delete_by_customer(
# then
assert_no_permission(response)
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_delete_clears_old_sale_id(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
permission_group_manage_discounts,
promotion_converted_from_sale,
@@ -147,9 +135,7 @@ def test_promotion_delete_clears_old_sale_id(
with pytest.raises(rule._meta.model.DoesNotExist):
rule.refresh_from_db()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ update_discounted_prices_task_mock.assert_called_once_with([product.id])
promotion.refresh_from_db()
assert promotion.old_sale_id is None
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py b/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py
index 9730187877..634f142db2 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py
@@ -45,11 +45,9 @@ PROMOTION_RULE_UPDATE_MUTATION = """
@patch("saleor.plugins.manager.PluginsManager.promotion_rule_updated")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_update_by_staff_user(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
promotion_rule_updated_mock,
staff_api_client,
permission_group_manage_discounts,
@@ -131,17 +129,15 @@ def test_promotion_rule_update_by_staff_user(
assert rule_data["rewardValue"] == reward_value
assert rule_data["promotion"]["id"] == promotion_id
assert promotion.rules.count() == rules_count
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
- args, _kwargs = update_products_discounted_prices_for_promotion_task_mock.call_args
+ update_discounted_prices_task_mock.assert_called_once()
+ args, _kwargs = update_discounted_prices_task_mock.call_args
assert set(args[0]) == {product_list[1].id, product_list[2].id}
promotion_rule_updated_mock.assert_called_once_with(rule)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_update_by_app(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
channel_USD,
@@ -192,16 +188,12 @@ def test_promotion_rule_update_by_app(
assert rule_data["rewardValue"] == reward_value
assert rule_data["promotion"]["id"] == promotion_id
assert promotion.rules.count() == rules_count
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ update_discounted_prices_task_mock.assert_called_once_with([product.id])
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_update_by_customer(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
api_client,
channel_USD,
channel_PLN,
@@ -231,7 +223,7 @@ def test_promotion_rule_update_by_customer(
# then
assert_no_permission(response)
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
def test_promotion_rule_update_duplicates_channels_in_add_and_remove_field(
@@ -647,11 +639,9 @@ def test_promotion_rule_update_reward_value_invalid_percentage_value(
assert errors[0]["field"] == "rewardValue"
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_update_clears_old_sale_id(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
permission_group_manage_discounts,
channel_USD,
@@ -734,8 +724,8 @@ def test_promotion_rule_update_clears_old_sale_id(
assert rule_data["rewardValue"] == reward_value
assert rule_data["promotion"]["id"] == promotion_id
assert promotion.rules.count() == rules_count
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
- args, _kwargs = update_products_discounted_prices_for_promotion_task_mock.call_args
+ update_discounted_prices_task_mock.assert_called_once()
+ args, _kwargs = update_discounted_prices_task_mock.call_args
assert set(args[0]) == {product_list[1].id, product_list[2].id}
promotion.refresh_from_db()
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py
index 9794967014..48a5056865 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py
@@ -22,13 +22,11 @@ SALE_CATALOGUES_ADD_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_sale_add_catalogues(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
category,
@@ -80,16 +78,14 @@ def test_sale_add_catalogues(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_sale_add_catalogues_no_changes_in_catalogue(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -139,16 +135,14 @@ def test_sale_add_catalogues_no_changes_in_catalogue(
assert current_catalogue == previous_catalogue
updated_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_sale_add_empty_catalogues(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -189,16 +183,14 @@ def test_sale_add_empty_catalogues(
assert variant_id in current_catalogue["variants"]
updated_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_sale_add_empty_catalogues_to_sale_with_empty_catalogues(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
permission_manage_discounts,
@@ -230,16 +222,14 @@ def test_sale_add_empty_catalogues_to_sale_with_empty_catalogues(
assert not current_catalogue["variants"]
updated_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_sale_add_catalogues_no_product_ids_change(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -283,14 +273,12 @@ def test_sale_add_catalogues_no_product_ids_change(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_sale_add_catalogues_with_product_without_variants(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -327,7 +315,7 @@ def test_sale_add_catalogues_with_product_without_variants(
assert error["code"] == DiscountErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT.name
assert error["message"] == "Cannot manage products without variants."
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
def test_sale_add_catalogues_with_promotion_id(
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py
index 5005a31ae0..17e274bc03 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py
@@ -22,13 +22,11 @@ SALE_CATALOGUES_REMOVE_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_sale_remove_catalogues(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -95,16 +93,14 @@ def test_sale_remove_catalogues(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_sale_remove_empty_catalogues(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -160,16 +156,14 @@ def test_sale_remove_empty_catalogues(
assert variant_id in current_catalogue["variants"]
updated_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_sale_remove_empty_catalogues_from_sale_with_empty_catalogues(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
permission_manage_discounts,
@@ -207,16 +201,14 @@ def test_sale_remove_empty_catalogues_from_sale_with_empty_catalogues(
assert not current_catalogue["variants"]
updated_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_sale_remove_catalogues_no_product_changes(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -257,7 +249,7 @@ def test_sale_remove_catalogues_no_product_changes(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
def test_sale_remove_catalogues_with_promotion_id(
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_delete.py b/saleor/graphql/discount/tests/mutations/test_sale_delete.py
index 16eadd3e52..582abad692 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_delete.py
@@ -25,13 +25,11 @@ SALE_DELETE_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_deleted")
def test_sale_delete_mutation(
deleted_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -63,16 +61,14 @@ def test_sale_delete_mutation(
promotion.refresh_from_db()
deleted_webhook_mock.assert_called_once_with(promotion, previous_catalogue)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_deleted")
def test_sale_delete_mutation_with_promotion_id(
deleted_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -100,7 +96,7 @@ def test_sale_delete_mutation_with_promotion_id(
)
deleted_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
def test_sale_delete_not_found_error(staff_api_client, permission_manage_discounts):
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_update.py b/saleor/graphql/discount/tests/mutations/test_sale_update.py
index cf061e0837..2e2548176a 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_update.py
@@ -30,13 +30,11 @@ SALE_UPDATE_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -88,16 +86,14 @@ def test_update_sale(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_name(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -138,19 +134,17 @@ def test_update_sale_name(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
@freeze_time("2020-03-18 12:00:00")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_start_date_after_current_date_notification_not_sent(
updated_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -193,19 +187,17 @@ def test_update_sale_start_date_after_current_date_notification_not_sent(
promotion, previous_catalogue, current_catalogue
)
sale_toggle_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
@freeze_time("2020-03-18 12:00:00")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_start_date_before_current_date_notification_already_sent(
updated_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -252,19 +244,17 @@ def test_update_sale_start_date_before_current_date_notification_already_sent(
promotion, previous_catalogue, current_catalogue
)
sale_toggle_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
@freeze_time("2020-03-18 12:00:00")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_start_date_before_current_date_notification_sent(
updated_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -308,19 +298,17 @@ def test_update_sale_start_date_before_current_date_notification_sent(
)
sale_toggle_mock.assert_called_once_with(promotion, current_catalogue)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
@freeze_time("2020-03-18 12:00:00")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_end_date_after_current_date_notification_not_sent(
updated_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -364,19 +352,17 @@ def test_update_sale_end_date_after_current_date_notification_not_sent(
promotion, previous_catalogue, current_catalogue
)
sale_toggle_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
@freeze_time("2020-03-18 12:00:00")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_end_date_before_current_date_notification_already_sent(
updated_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -422,19 +408,17 @@ def test_update_sale_end_date_before_current_date_notification_already_sent(
promotion, previous_catalogue, current_catalogue
)
sale_toggle_mock.assert_called_once_with(promotion, current_catalogue)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
@freeze_time("2020-03-18 12:00:00")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_end_date_before_current_date_notification_sent(
updated_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -478,16 +462,14 @@ def test_update_sale_end_date_before_current_date_notification_sent(
promotion, previous_catalogue, current_catalogue
)
sale_toggle_mock.assert_called_once_with(promotion, current_catalogue)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_categories(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -527,16 +509,14 @@ def test_update_sale_categories(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_collections(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -578,16 +558,14 @@ def test_update_sale_collections(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_variants(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -629,16 +607,14 @@ def test_update_sale_variants(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_products(
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -678,19 +654,17 @@ def test_update_sale_products(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
+ update_discounted_prices_task_mock.assert_called_once()
@freeze_time("2020-03-18 12:00:00")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_end_date_before_start_date(
updated_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -722,7 +696,7 @@ def test_update_sale_end_date_before_start_date(
assert errors[0]["code"] == DiscountErrorCode.INVALID.name
updated_webhook_mock.assert_not_called()
sale_toggle_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
@freeze_time("2020-03-18 12:00:00")
@@ -781,15 +755,13 @@ def test_update_sale_with_none_values(
assert not rule.catalogue_predicate
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale_with_promotion_id(
updated_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -822,7 +794,7 @@ def test_update_sale_with_promotion_id(
)
updated_webhook_mock.assert_not_called()
sale_toggle_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ update_discounted_prices_task_mock.assert_not_called()
def test_update_sale_not_found_error(staff_api_client, permission_manage_discounts):
diff --git a/saleor/graphql/discount/utils.py b/saleor/graphql/discount/utils.py
index 2b712f9515..1961e555d9 100644
--- a/saleor/graphql/discount/utils.py
+++ b/saleor/graphql/discount/utils.py
@@ -4,6 +4,7 @@ from enum import Enum
from typing import Optional, Union, cast
import graphene
+from django.db import transaction
from django.db.models import Exists, OuterRef, QuerySet
from graphene.utils.str_converters import to_camel_case
@@ -48,23 +49,53 @@ def clean_predicate(predicate: Union[dict[str, Union[dict, list]], list]):
}
-def get_products_for_promotion(promotion: Promotion) -> ProductsQueryset:
+def get_products_for_promotion(
+ promotion: Promotion, *, update_rule_variants=False
+) -> ProductsQueryset:
"""Get products that are included in the promotion based on catalogue predicate."""
- variants = get_variants_for_promotion(promotion)
+ variants = get_variants_for_promotion(
+ promotion, update_rule_variants=update_rule_variants
+ )
return Product.objects.filter(Exists(variants.filter(product_id=OuterRef("id"))))
-def get_products_for_rule(rule: PromotionRule) -> ProductsQueryset:
+def get_products_for_rule(
+ rule: PromotionRule, *, update_rule_variants=False
+) -> ProductsQueryset:
"""Get products that are included in the rule based on catalogue predicate."""
variants = get_variants_for_predicate(deepcopy(rule.catalogue_predicate))
+ if update_rule_variants:
+ rule.variants.set(variants)
return Product.objects.filter(Exists(variants.filter(product_id=OuterRef("id"))))
-def get_variants_for_promotion(promotion: Promotion) -> ProductVariantQueryset:
+def get_variants_for_promotion(
+ promotion: Promotion, *, update_rule_variants=False
+) -> ProductVariantQueryset:
"""Get variants that are included in the promotion based on catalogue predicate."""
queryset = ProductVariant.objects.none()
- for rule in promotion.rules.iterator():
- queryset |= get_variants_for_predicate(rule.catalogue_predicate)
+ promotion_rule_variants = []
+ PromotionRuleVariant = PromotionRule.variants.through
+ rules = promotion.rules
+ for rule in list(rules.iterator()):
+ variants = get_variants_for_predicate(rule.catalogue_predicate)
+ queryset |= variants
+ if update_rule_variants:
+ promotion_rule_variants.extend(
+ [
+ PromotionRuleVariant(
+ promotionrule_id=rule.pk, productvariant_id=variant.pk
+ )
+ for variant in variants
+ ]
+ )
+ if promotion_rule_variants:
+ with transaction.atomic():
+ # Clear existing variants assigned to promotion rules
+ PromotionRuleVariant.objects.filter(
+ Exists(rules.filter(pk=OuterRef("promotionrule_id")))
+ ).delete()
+ PromotionRuleVariant.objects.bulk_create(promotion_rule_variants)
return queryset
@@ -295,14 +326,6 @@ def get_categories_from_predicate(catalogue_predicate) -> QuerySet:
).all()
-def get_product_ids_for_predicate(predicate: dict) -> set[int]:
- variants = get_variants_for_predicate(predicate)
- products = Product.objects.filter(
- Exists(variants.filter(product_id=OuterRef("id")))
- )
- return set(products.values_list("id", flat=True))
-
-
def merge_catalogues_info(
catalogue_1: CatalogueInfo, catalogue_2: CatalogueInfo
) -> CatalogueInfo:
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index 1576c7355a..1281ae7daa 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -19,7 +19,7 @@ from ....product.models import (
)
from ....product.models import Product as ProductModel
from ....product.models import ProductVariant as ProductVariantModel
-from ....product.tasks import update_products_discounted_prices_for_promotion_task
+from ....product.tasks import update_discounted_prices_task
from ...channel import ChannelContext
from ...channel.mutations import BaseChannelListingMutation
from ...channel.types import Channel
@@ -356,7 +356,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
cls.update_channels(product, cleaned_input.get("update_channels", []))
cls.remove_channels(product, cleaned_input.get("remove_channels", []))
product = ProductModel.objects.prefetched_for_webhook().get(pk=product.pk)
- update_products_discounted_prices_for_promotion_task.delay([product.id])
+ update_discounted_prices_task.delay([product.id])
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.product_updated, product)
@@ -541,9 +541,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
channel=channel,
defaults=defaults,
)
- update_products_discounted_prices_for_promotion_task.delay(
- [variant.product_id]
- )
+ update_discounted_prices_task.delay([variant.product_id])
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.product_variant_updated, variant)
diff --git a/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py b/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py
index 64823cdad3..f700e91e13 100644
--- a/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py
+++ b/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py
@@ -60,11 +60,9 @@ mutation UpdateProductChannelListing(
@freeze_time("2023-11-13T14:53:59.655366")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_product_channel_listing_update_as_staff_user(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
product,
permission_manage_products,
@@ -139,9 +137,7 @@ def test_product_channel_listing_update_as_staff_user(
product_data["channelListings"][1]["availableForPurchase"]
== available_for_purchase_date.isoformat()
)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ update_discounted_prices_task_mock.assert_called_once_with([product.id])
@freeze_time("2023-11-13T14:53:59.655366")
diff --git a/saleor/graphql/product/tests/test_product_discounted_price.py b/saleor/graphql/product/tests/test_product_discounted_price.py
index 451459764f..c58ecdcbca 100644
--- a/saleor/graphql/product/tests/test_product_discounted_price.py
+++ b/saleor/graphql/product/tests/test_product_discounted_price.py
@@ -258,10 +258,10 @@ def test_sale_create_updates_products_discounted_prices(
@patch(
"saleor.graphql.discount.mutations.sale.sale_update"
- ".update_products_discounted_prices_for_promotion_task"
+ ".update_discounted_prices_task"
)
def test_sale_update_updates_products_discounted_prices(
- mock_update_products_discounted_prices_for_promotion,
+ mock_update_discounted_prices_task,
staff_api_client,
promotion_converted_from_sale,
product,
@@ -298,16 +298,16 @@ def test_sale_update_updates_products_discounted_prices(
content = get_graphql_content(response)
assert content["data"]["saleUpdate"]["errors"] == []
- args, _ = mock_update_products_discounted_prices_for_promotion.delay.call_args
+ args, _ = mock_update_discounted_prices_task.delay.call_args
assert args[0] == [product.id]
@patch(
"saleor.graphql.discount.mutations.sale.sale_delete"
- ".update_products_discounted_prices_for_promotion_task"
+ ".update_discounted_prices_task"
)
def test_sale_delete_updates_products_discounted_prices(
- mock_update_products_discounted_prices_for_promotion,
+ mock_update_discounted_prices_task,
staff_api_client,
promotion_converted_from_sale,
product,
@@ -341,16 +341,16 @@ def test_sale_delete_updates_products_discounted_prices(
content = get_graphql_content(response)
assert content["data"]["saleDelete"]["errors"] == []
- args, _ = mock_update_products_discounted_prices_for_promotion.delay.call_args
+ args, _ = mock_update_discounted_prices_task.delay.call_args
assert args[0] == [product.id]
@patch(
"saleor.graphql.discount.mutations.sale.sale_base_catalogue"
- ".update_products_discounted_prices_for_promotion_task"
+ ".update_discounted_prices_task"
)
def test_sale_add_catalogues_updates_products_discounted_prices(
- mock_update_products_discounted_prices_for_promotion,
+ mock_update_discounted_prices_task,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
product_list,
@@ -396,16 +396,16 @@ def test_sale_add_catalogues_updates_products_discounted_prices(
content = get_graphql_content(response)
assert not content["data"]["saleCataloguesAdd"]["errors"]
- args, _ = mock_update_products_discounted_prices_for_promotion.delay.call_args
+ args, _ = mock_update_discounted_prices_task.delay.call_args
assert set(args[0]) == {product.id for product in product_list[1:]}
@patch(
"saleor.graphql.discount.mutations.sale.sale_base_catalogue"
- ".update_products_discounted_prices_for_promotion_task"
+ ".update_discounted_prices_task"
)
def test_sale_remove_catalogues_updates_products_discounted_prices(
- mock_update_products_discounted_prices_for_promotion,
+ mock_update_discounted_prices_task,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
product_list,
@@ -453,6 +453,4 @@ def test_sale_remove_catalogues_updates_products_discounted_prices(
content = get_graphql_content(response)
assert not content["data"]["saleCataloguesRemove"]["errors"]
- mock_update_products_discounted_prices_for_promotion.delay.called_once_with(
- product_id
- )
+ mock_update_discounted_prices_task.delay.called_once_with(product_id)
diff --git a/saleor/graphql/product/tests/test_variant_channel_listing_update.py b/saleor/graphql/product/tests/test_variant_channel_listing_update.py
index 18ae906c57..108ea42ade 100644
--- a/saleor/graphql/product/tests/test_variant_channel_listing_update.py
+++ b/saleor/graphql/product/tests/test_variant_channel_listing_update.py
@@ -182,11 +182,9 @@ def test_variant_channel_listing_update_with_too_many_decimal_places_in_price(
assert error["code"] == ProductErrorCode.INVALID.name
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_variant_channel_listing_update_as_staff_user(
- update_products_discounted_prices_for_promotion_task_mock,
+ update_discounted_prices_task_mock,
staff_api_client,
product,
permission_manage_products,
@@ -252,9 +250,7 @@ def test_variant_channel_listing_update_as_staff_user(
pln_channel_listing = variant.channel_listings.get(channel=channel_PLN)
assert usd_channel_listing.discounted_price_amount == price
assert pln_channel_listing.discounted_price_amount == second_price
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ update_discounted_prices_task_mock.assert_called_once_with([product.id])
def test_variant_channel_listing_update_by_sku(
@@ -477,11 +473,9 @@ def test_variant_channel_listing_update_as_anonymous(
assert_no_permission(response)
-@patch(
- "saleor.graphql.product.mutations.channels.update_products_discounted_prices_for_promotion_task"
-)
+@patch("saleor.graphql.product.mutations.channels.update_discounted_prices_task")
def test_product_variant_channel_listing_update_updates_discounted_price(
- mock_update_products_discounted_prices_for_promotion_task,
+ mock_update_discounted_prices_task,
staff_api_client,
product,
permission_manage_products,
@@ -505,9 +499,7 @@ def test_product_variant_channel_listing_update_updates_discounted_price(
data = content["data"]["productVariantChannelListingUpdate"]
assert data["errors"] == []
- mock_update_products_discounted_prices_for_promotion_task.delay.assert_called_once_with(
- [product.pk]
- )
+ mock_update_discounted_prices_task.delay.assert_called_once_with([product.pk])
def test_product_variant_channel_listing_update_remove_cost_price(
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 3370db17b7..64968fa66c 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -35,7 +35,6 @@ from ..core.utils.editorjs import clean_editor_js
from ..core.utils.translations import Translation, get_translation
from ..core.weight import zero_weight
from ..discount.models import PromotionRule
-from ..discount.utils import calculate_discounted_price_for_rules
from ..permission.enums import (
DiscountPermissions,
OrderPermissions,
@@ -392,6 +391,8 @@ class ProductVariant(SortableModel, ModelWithMetadata, ModelWithExternalReferenc
If a custom price is provided, return the price with applied discounts from
valid promotion rules for this variant.
"""
+ from ..discount.utils import calculate_discounted_price_for_rules
+
if price_override is None:
return channel_listing.discounted_price or channel_listing.price
price: "Money" = self.get_base_price(channel_listing, price_override)
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index a313edbaef..2faf185a53 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -1,28 +1,36 @@
import logging
from collections.abc import Iterable
+from typing import Optional
from uuid import UUID
from celery.utils.log import get_task_logger
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
+from django.db.models import Exists, OuterRef
from django.utils import timezone
from ..attribute.models import Attribute
from ..celeryconf import app
from ..core.exceptions import PreorderAllocationError
-from ..discount.models import Promotion
+from ..discount.models import Promotion, PromotionRule
+from ..discount.utils import get_current_products_for_rules
from ..warehouse.management import deactivate_preorder_for_variant
from .models import Product, ProductType, ProductVariant
from .search import PRODUCTS_BATCH_SIZE, update_products_search_vector
from .utils.variant_prices import update_discounted_prices_for_promotion
-from .utils.variants import generate_and_set_variant_name
+from .utils.variants import (
+ fetch_variants_for_promotion_rules,
+ generate_and_set_variant_name,
+)
logger = logging.getLogger(__name__)
task_logger = get_task_logger(__name__)
VARIANTS_UPDATE_BATCH = 500
-# Results in update time ~2s for 500 promotions
-DISCOUNTED_PRODUCT_BATCH = 500
+# Results in update time ~0.2s
+DISCOUNTED_PRODUCT_BATCH = 2000
+# Results in update time ~1.5s
+PROMOTION_RULE_BATCH_SIZE = 250
def _variants_in_batches(variants_qs):
@@ -83,21 +91,58 @@ def update_products_discounted_prices_of_promotion_task(promotion_pk: UUID):
except ObjectDoesNotExist:
logging.warning(f"Cannot find promotion with id: {promotion_pk}.")
return
- products = get_products_for_promotion(promotion)
- update_products_discounted_prices_for_promotion_task.delay(
- list(products.values_list("id", flat=True))
+ previous_products = get_current_products_for_rules(promotion.rules.all())
+ products = get_products_for_promotion(promotion, update_rule_variants=True)
+ products |= previous_products
+ update_discounted_prices_task.delay(list(products.values_list("id", flat=True)))
+
+
+def update_products_discounted_prices_for_promotion_task(
+ product_ids: Iterable[int],
+ start_id: Optional[UUID] = None,
+ *,
+ rule_ids: Optional[list[UUID]] = None,
+):
+ """Update the product discounted prices for given product ids.
+
+ Firstly the promotion rule variants are recalculated, then the products discounted
+ prices are calculated.
+ """
+ promotions = Promotion.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).active()
+ kwargs = {"id__gt": start_id} if start_id else {}
+ if rule_ids:
+ kwargs["id__in"] = rule_ids # type: ignore[assignment]
+ rules = (
+ PromotionRule.objects.order_by("id")
+ .using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(Exists(promotions.filter(id=OuterRef("promotion_id"))), **kwargs)[
+ :PROMOTION_RULE_BATCH_SIZE
+ ]
)
+ if ids := list(rules.values_list("pk", flat=True)):
+ qs = PromotionRule.objects.filter(pk__in=ids)
+ fetch_variants_for_promotion_rules(rules=qs)
+ update_products_discounted_prices_for_promotion_task.delay(
+ product_ids, ids[-1], rule_ids=rule_ids
+ )
+ else:
+ # when all promotion rules variants are up to date, call discounted prices
+ # recalculation for products
+ update_discounted_prices_task.delay(product_ids)
@app.task
-def update_products_discounted_prices_for_promotion_task(product_ids: Iterable[int]):
+def update_discounted_prices_task(product_ids: Iterable[int]):
"""Update the product discounted prices for given product ids."""
ids = sorted(product_ids)[:DISCOUNTED_PRODUCT_BATCH]
qs = Product.objects.filter(pk__in=ids)
if ids:
update_discounted_prices_for_promotion(qs)
remaining_ids = list(set(product_ids) - set(ids))
- update_products_discounted_prices_for_promotion_task.delay(remaining_ids)
+ update_discounted_prices_task.delay(remaining_ids)
@app.task
diff --git a/saleor/product/tests/test_fetch_variants_for_promotion_rules.py b/saleor/product/tests/test_fetch_variants_for_promotion_rules.py
new file mode 100644
index 0000000000..74039b7d65
--- /dev/null
+++ b/saleor/product/tests/test_fetch_variants_for_promotion_rules.py
@@ -0,0 +1,83 @@
+from decimal import Decimal
+
+import graphene
+
+from ...discount import RewardValueType
+from ...discount.models import PromotionRule
+from ..utils.variants import fetch_variants_for_promotion_rules
+
+
+def test_fetch_variants_for_promotion_rules_discount(
+ promotion_without_rules, product, product_with_two_variants, channel_USD
+):
+ # given
+ variant = product.variants.first()
+ promotion = promotion_without_rules
+
+ percentage_reward_value = Decimal("10")
+ reward_value = Decimal("2")
+ rule_1 = promotion.rules.create(
+ name="Percentage promotion rule",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=percentage_reward_value,
+ )
+ rule_2 = promotion.rules.create(
+ name="Fixed promotion rule",
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [
+ graphene.Node.to_global_id("Product", product_with_two_variants.id)
+ ]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule_1.channels.add(channel_USD)
+ rule_2.channels.add(channel_USD)
+
+ # when
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+
+ # then
+ rule_1.refresh_from_db()
+ assert rule_1.variants.count() == 1
+ assert rule_1.variants.first() == variant
+
+ rule_2.refresh_from_db()
+ assert rule_2.variants.count() == product_with_two_variants.variants.count()
+ assert list(rule_2.variants.values_list("id", flat=True)) == list(
+ product_with_two_variants.variants.values_list("id", flat=True)
+ )
+
+
+def test_fetch_variants_for_promotion_rules_no_applicable_variants(
+ promotion_without_rules, category, channel_USD
+):
+ # given
+ category.products.clear()
+
+ reward_value = Decimal("2")
+ rule = promotion_without_rules.rules.create(
+ name="Percentage promotion rule",
+ catalogue_predicate={
+ "categoryPredicate": {
+ "ids": [graphene.Node.to_global_id("Category", category.id)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel_USD)
+
+ # when
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+
+ # then
+ rule.refresh_from_db()
+ assert rule.variants.count() == 0
diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.py
index 85cde01738..1bf0f2050f 100644
--- a/saleor/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/product/tests/test_product_minimal_variant_price.py
@@ -62,6 +62,7 @@ def test_update_discounted_price_for_promotion_discount_on_variant(
reward_value=reward_value,
)
rule.channels.add(variant_channel_listing.channel)
+ rule.variants.add(variant)
# when
update_discounted_prices_for_promotion(Product.objects.filter(id__in=[product.id]))
@@ -109,6 +110,7 @@ def test_update_discounted_price_for_promotion_discount_on_product(
reward_value=reward_value,
)
rule.channels.add(variant_channel_listing.channel)
+ rule.variants.set(product.variants.all())
# when
update_discounted_prices_for_promotion(Product.objects.filter(id__in=[product.id]))
@@ -170,6 +172,8 @@ def test_update_discounted_price_for_promotion_discount_multiple_applicable_rule
)
rule_1.channels.add(variant_channel_listing.channel)
rule_2.channels.add(variant_channel_listing.channel)
+ rule_1.variants.add(variant)
+ rule_2.variants.set(product.variants.all())
# when
update_discounted_prices_for_promotion(Product.objects.filter(id__in=[product.id]))
@@ -234,6 +238,7 @@ def test_update_discounted_price_for_promotion_1_cent_variant_on_10_percentage_d
reward_value=reward_value,
)
rule.channels.add(variant_channel_listing.channel)
+ rule.variants.add(variant)
# when
update_discounted_prices_for_promotion(Product.objects.filter(id__in=[product.id]))
@@ -281,6 +286,7 @@ def test_update_discounted_price_for_promotion_promotion_not_applicable_for_chan
reward_value=reward_value,
)
rule.channels.add(channel_PLN)
+ rule.variants.add(variant)
# when
update_discounted_prices_for_promotion(Product.objects.filter(id__in=[product.id]))
@@ -321,6 +327,7 @@ def test_update_discounted_price_for_promotion_discount_updated(product, channel
reward_value=reward_value,
)
rule.channels.add(variant_channel_listing.channel)
+ rule.variants.add(variant)
listing_promotion_rule = VariantChannelListingPromotionRule.objects.create(
variant_channel_listing=variant_channel_listing,
@@ -430,6 +437,7 @@ def test_update_discounted_price_for_promotion_discount_one_rule_not_valid_anymo
)
rule_1.channels.add(variant_channel_listing.channel)
rule_2.channels.add(variant_channel_listing.channel)
+ rule_2.variants.set(product.variants.all())
listing_promotion_rules = VariantChannelListingPromotionRule.objects.bulk_create(
[
@@ -517,6 +525,7 @@ def test_update_discounted_price_for_promotion_promotion_rule_deleted_in_meantim
reward_value=reward_value,
)
rule.channels.add(variant_channel_listing.channel)
+ rule.variants.add(variant)
def delete_promotion_rule(*args, **kwargs):
PromotionRule.objects.all().delete()
@@ -570,6 +579,7 @@ def test_update_discounted_price_rule_deleted_in_meantime_promotion_listing_exis
reward_value=reward_value,
)
rule.channels.add(variant_channel_listing.channel)
+ rule.variants.add(variant)
listing_promotion_rule = VariantChannelListingPromotionRule.objects.create(
variant_channel_listing=variant_channel_listing,
diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.py
index de68b4d2a4..a434caf7ea 100644
--- a/saleor/product/tests/test_tasks.py
+++ b/saleor/product/tests/test_tasks.py
@@ -9,9 +9,11 @@ import pytest
from django.utils import timezone
from ...discount import RewardValueType
-from ...discount.models import Promotion
+from ...discount.models import Promotion, PromotionRule
+from ..models import ProductChannelListing, ProductVariantChannelListing
from ..tasks import (
_get_preorder_variants_to_clean,
+ update_discounted_prices_task,
update_products_discounted_prices_for_promotion_task,
update_products_discounted_prices_of_promotion_task,
update_products_search_vector_task,
@@ -19,11 +21,9 @@ from ..tasks import (
)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_update_products_discounted_prices_of_promotion_task(
- update_products_discounted_prices_mock,
+ update_discounted_prices_task_mock,
product,
):
# given
@@ -46,8 +46,8 @@ def test_update_products_discounted_prices_of_promotion_task(
update_products_discounted_prices_of_promotion_task(promotion.id)
# then
- update_products_discounted_prices_mock.assert_called_once()
- args, kwargs = update_products_discounted_prices_mock.call_args
+ update_discounted_prices_task_mock.assert_called_once()
+ args, kwargs = update_discounted_prices_task_mock.call_args
assert len(args[0]) == 1
assert {id for id in args[0]} == {product.id}
@@ -71,20 +71,81 @@ def test_update_products_discounted_prices_of_promotion_task_discount_does_not_e
assert f"Cannot find promotion with id: {promotion_id}" in caplog.text
-@patch("saleor.product.tasks.DISCOUNTED_PRODUCT_BATCH", 1)
-@patch("saleor.product.utils.variant_prices.update_discounted_prices_for_promotion")
+@patch("saleor.product.tasks.PROMOTION_RULE_BATCH_SIZE", 1)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_update_products_discounted_prices_for_promotion_task(
- update_products_discounted_prices_mock,
+ update_discounted_prices_task_mock,
+ promotion_list,
+ product_list,
+ collection,
+):
+ # given
+ Promotion.objects.update(start_date=timezone.now() - timedelta(days=1))
+ product_ids = [product.id for product in product_list]
+ PromotionRuleVariant = PromotionRule.variants.through
+ PromotionRuleVariant.objects.all().delete()
+
+ collection.products.add(*product_list[1:])
+
+ # when
+ update_products_discounted_prices_for_promotion_task(product_ids)
+
+ # then
+ update_discounted_prices_task_mock.assert_called_once_with(product_ids)
+ assert set(
+ PromotionRuleVariant.objects.values_list("promotionrule_id", flat=True)
+ ) == set(PromotionRule.objects.values_list("id", flat=True))
+
+
+@patch("saleor.product.tasks.PROMOTION_RULE_BATCH_SIZE", 1)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
+@patch("saleor.product.utils.variants.fetch_variants_for_promotion_rules")
+def test_update_products_discounted_prices_for_promotion_task_with_rules_id(
+ fetch_variants_for_promotion_rules_mock,
+ update_discounted_prices_task_mock,
+ promotion_list,
+ collection,
+ product_list,
+):
+ # given
+ Promotion.objects.update(start_date=timezone.now() - timedelta(days=1))
+ PromotionRuleVariant = PromotionRule.variants.through
+ PromotionRuleVariant.objects.all().delete()
+
+ collection.products.add(*product_list[1:])
+
+ rule_id = PromotionRule.objects.first().id
+ product_ids = [product.id for product in product_list]
+
+ # when
+ update_products_discounted_prices_for_promotion_task(
+ product_ids, rule_ids=[rule_id]
+ )
+
+ # then
+ update_discounted_prices_task_mock.assert_called_once_with(product_ids)
+ assert set(
+ PromotionRuleVariant.objects.values_list("promotionrule_id", flat=True)
+ ) == {rule_id}
+
+
+@patch("saleor.product.tasks.DISCOUNTED_PRODUCT_BATCH", 1)
+def test_update_discounted_prices_task(
product_list,
):
# given
ids = [product.id for product in product_list]
+ ProductChannelListing.objects.update(discounted_price_amount=0)
+ ProductVariantChannelListing.objects.update(discounted_price_amount=0)
# when
- update_products_discounted_prices_for_promotion_task(ids)
+ update_discounted_prices_task(ids)
# then
- update_products_discounted_prices_mock.call_count == len(ids)
+ assert not ProductChannelListing.objects.filter(discounted_price_amount=0).exists()
+ assert not ProductVariantChannelListing.objects.filter(
+ discounted_price_amount=0
+ ).exists()
@patch("saleor.product.tasks._update_variants_names")
diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.py
index 8732d2b53e..03ebbb68ae 100644
--- a/saleor/product/utils/variant_prices.py
+++ b/saleor/product/utils/variant_prices.py
@@ -1,6 +1,5 @@
from collections import defaultdict
from decimal import Decimal
-from typing import Optional
from uuid import UUID
from django.db import transaction
@@ -13,7 +12,7 @@ from ...discount import PromotionRuleInfo
from ...discount.models import PromotionRule
from ...discount.utils import (
calculate_discounted_price_for_promotions,
- fetch_active_promotion_rules,
+ get_variants_to_promotions_map,
)
from ..managers import ProductsQueryset, ProductVariantQueryset
from ..models import (
@@ -24,9 +23,7 @@ from ..models import (
)
-def update_discounted_prices_for_promotion(
- products: ProductsQueryset, rules_info: Optional[list[PromotionRuleInfo]] = None
-):
+def update_discounted_prices_for_promotion(products: ProductsQueryset):
"""Update Products and ProductVariants discounted prices.
The discounted price is the minimal price of the product/variant based on active
@@ -38,8 +35,7 @@ def update_discounted_prices_for_promotion(
variant_qs = ProductVariant.objects.filter(
Exists(products.filter(id=OuterRef("product_id")))
)
- if rules_info is None:
- rules_info_per_promotion_id = fetch_active_promotion_rules(variant_qs)
+ rules_info_per_variant_and_promotion_id = get_variants_to_promotions_map(variant_qs)
product_to_variant_listings_per_channel_map = (
_get_product_to_variant_channel_listings_per_channel_map(variant_qs)
)
@@ -71,7 +67,7 @@ def update_discounted_prices_for_promotion(
variant_listing_promotion_rule_to_update,
) = _get_discounted_variants_prices_for_promotions(
variant_listings,
- rules_info_per_promotion_id,
+ rules_info_per_variant_and_promotion_id,
product_channel_listing.channel,
variant_listing_to_listing_rule_per_rule_map,
)
@@ -222,7 +218,9 @@ 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_promotion_id: dict[UUID, list[PromotionRuleInfo]],
+ rules_info_per_variant_and_promotion_id: dict[
+ int, dict[UUID, list[PromotionRuleInfo]]
+ ],
channel: Channel,
variant_listing_to_listing_rule_per_rule_map: dict,
) -> tuple[
@@ -242,7 +240,9 @@ def _get_discounted_variants_prices_for_promotions(
for variant_listing in variant_listings:
applied_discounts = calculate_discounted_price_for_promotions(
price=variant_listing.price,
- rules_info_per_promotion_id=rules_info_per_promotion_id,
+ rules_info_per_variant_and_promotion_id=(
+ rules_info_per_variant_and_promotion_id
+ ),
channel=channel,
variant_id=variant_listing.variant_id,
)
@@ -271,7 +271,7 @@ def _get_discounted_variants_prices_for_promotions(
variant_listing.discounted_price_amount = discounted_variant_price.amount
variants_listings_to_update.append(variant_listing)
- # delete variant listing - promotion rules relationd that are not valid
+ # delete variant listing - promotion rules relations that are not valid
# anymore
VariantChannelListingPromotionRule.objects.filter(
variant_channel_listing_id=variant_listing.id
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index f46b24fff4..b063692ed5 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -1,11 +1,15 @@
from collections.abc import Iterable
from typing import TYPE_CHECKING, Optional
+from django.db import transaction
+from django.db.models import Exists, OuterRef, QuerySet
+
from ...attribute import AttributeType
+from ...discount.models import PromotionRule
+from ..models import ProductVariant
if TYPE_CHECKING:
from ...attribute.models import AssignedVariantAttribute, Attribute
- from ..models import ProductVariant
def generate_and_set_variant_name(
@@ -46,3 +50,29 @@ def get_variant_selection_attributes(
for attribute, variant_selection in attributes
if variant_selection and attribute.type == AttributeType.PRODUCT_TYPE
]
+
+
+def fetch_variants_for_promotion_rules(
+ rules: QuerySet[PromotionRule],
+):
+ from ...graphql.discount.utils import get_variants_for_predicate
+
+ PromotionRuleVariant = PromotionRule.variants.through
+ promotion_rule_variants = []
+ for rule in list(rules.iterator()):
+ variants = get_variants_for_predicate(rule.catalogue_predicate)
+ promotion_rule_variants.extend(
+ [
+ PromotionRuleVariant(
+ promotionrule_id=rule.pk, productvariant_id=variant.pk
+ )
+ for variant in variants
+ ]
+ )
+
+ with transaction.atomic():
+ # Clear existing variants assigned to promotion rules
+ PromotionRuleVariant.objects.filter(
+ Exists(rules.filter(pk=OuterRef("promotionrule_id")))
+ ).delete()
+ PromotionRuleVariant.objects.bulk_create(promotion_rule_variants)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 1346ef78f1..a3e681bd75 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -126,6 +126,7 @@ from ..product.models import (
)
from ..product.search import prepare_product_search_vector_value
from ..product.tests.utils import create_image
+from ..product.utils.variants import fetch_variants_for_promotion_rules
from ..shipping.models import (
ShippingMethod,
ShippingMethodChannelListing,
@@ -5568,6 +5569,7 @@ def promotion(channel_USD, product, collection):
)
for rule in rules:
rule.channels.add(channel_USD)
+ fetch_variants_for_promotion_rules(promotion.rules.all())
return promotion
@@ -5597,6 +5599,7 @@ def promotion_with_single_rule(catalogue_predicate, channel_USD):
@pytest.fixture
def promotion_list(channel_USD, product, collection):
+ collection.products.add(product)
promotions = Promotion.objects.bulk_create(
[
Promotion(
@@ -5681,6 +5684,7 @@ def promotion_list(channel_USD, product, collection):
)
for rule in rules:
rule.channels.add(channel_USD)
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
return promotions
@@ -5755,6 +5759,7 @@ def promotion_converted_from_sale(catalogue_predicate, channel_USD):
old_channel_listing_id=PromotionRule.get_old_channel_listing_ids(1)[0][0],
)
rule.channels.add(channel_USD)
+ fetch_variants_for_promotion_rules(promotion.rules.all())
return promotion
@@ -5772,6 +5777,7 @@ def promotion_converted_from_sale_with_many_channels(
old_channel_listing_id=PromotionRule.get_old_channel_listing_ids(1)[0][0],
)
rule.channels.add(channel_PLN)
+ fetch_variants_for_promotion_rules(promotion.rules.all())
return promotion
diff --git a/saleor/webhook/tests/test_webhook_serializers.py b/saleor/webhook/tests/test_webhook_serializers.py
index 604667b2c6..a42f0c6e91 100644
--- a/saleor/webhook/tests/test_webhook_serializers.py
+++ b/saleor/webhook/tests/test_webhook_serializers.py
@@ -10,12 +10,14 @@ from ...checkout import base_calculations
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...core.prices import quantize_price
from ...discount import DiscountType
+from ...discount.models import PromotionRule
from ...discount.utils import (
create_or_update_discount_objects_from_promotion_for_checkout,
)
from ...plugins.manager import get_plugins_manager
from ...product.models import Product
from ...product.utils.variant_prices import update_discounted_prices_for_promotion
+from ...product.utils.variants import fetch_variants_for_promotion_rules
from ..serializers import (
serialize_checkout_lines,
serialize_checkout_lines_for_tax_calculation,
@@ -343,6 +345,7 @@ def test_serialize_checkout_lines_for_tax_calculation_with_promotion(
}
promotion_rule.save(update_fields=["catalogue_predicate"])
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
update_discounted_prices_for_promotion(Product.objects.all())
lines, _ = fetch_checkout_lines(checkout)