Skip to content

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

Recalculate prices with celery beat (#15051)

Arturf69a0c596053
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 992b6367c7..ef4927ff30 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -87,7 +87,10 @@ from ...product.models import (
VariantMedia,
)
from ...product.search import update_products_search_vector
-from ...product.tasks import update_products_discounted_prices_of_promotion_task
+from ...product.tasks import (
+ recalculate_discounted_price_for_products_task,
+ update_variant_relations_for_active_promotion_rules_task,
+)
from ...shipping.models import (
ShippingMethod,
ShippingMethodChannelListing,
@@ -839,6 +842,7 @@ def create_fake_catalogue_promotion():
promotion=promotion,
reward_value_type=RewardValueType.PERCENTAGE,
reward_value=random.choice([10, 20, 30, 40, 50]),
+ variants_dirty=True,
catalogue_predicate={
"productPredicate": {
"ids": [
@@ -852,6 +856,7 @@ def create_fake_catalogue_promotion():
promotion=promotion,
reward_value_type=RewardValueType.PERCENTAGE,
reward_value=random.choice([10, 20, 30, 40, 50]),
+ variants_dirty=True,
catalogue_predicate={
"variantPredicate": {
"ids": [
@@ -1014,8 +1019,11 @@ def create_orders(how_many=10):
def create_catalogue_promotions(how_many=5):
for _ in range(how_many):
promotion = create_fake_catalogue_promotion()
- update_products_discounted_prices_of_promotion_task.delay(promotion.pk)
yield f"Promotion: {promotion}"
+ # recalculation is handled by celery beat, so we trigger it manually, to receive the
+ # correct amounts in random data created by saleor.
+ update_variant_relations_for_active_promotion_rules_task()
+ recalculate_discounted_price_for_products_task()
def create_order_promotions(how_many=5):
diff --git a/saleor/discount/migrations/0076_promotionrule_variants_dirty.py b/saleor/discount/migrations/0076_promotionrule_variants_dirty.py
new file mode 100644
index 0000000000..a0cafc6ad1
--- /dev/null
+++ b/saleor/discount/migrations/0076_promotionrule_variants_dirty.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.23 on 2024-01-09 08:41
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("discount", "0075_promotionrule_gifts"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="promotionrule",
+ name="variants_dirty",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE discount_promotionrule
+ ALTER COLUMN variants_dirty
+ SET DEFAULT false;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 00458206b3..a749db67cd 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -400,6 +400,7 @@ class PromotionRule(models.Model):
"product.ProductVariant", blank=True, related_name="+"
)
old_channel_listing_id = models.IntegerField(blank=True, null=True, unique=True)
+ variants_dirty = models.BooleanField(default=False)
class Meta:
ordering = ("name", "pk")
diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.py
index 6f62184fd6..448e8c9148 100644
--- a/saleor/discount/tasks.py
+++ b/saleor/discount/tasks.py
@@ -19,7 +19,7 @@ from ..product.models import (
ProductVariantChannelListing,
VariantChannelListingPromotionRule,
)
-from ..product.tasks import update_products_discounted_prices_for_promotion_task
+from ..product.utils.product import mark_products_in_channels_as_dirty_based_on_rules
from ..product.utils.variant_prices import update_discounted_prices_for_promotion
from ..webhook.event_types import WebhookEventAsyncType
from ..webhook.utils import get_webhooks_for_event
@@ -31,6 +31,7 @@ from .models import (
PromotionRule,
VoucherCode,
)
+from .utils import mark_catalogue_promotion_rules_as_dirty
if TYPE_CHECKING:
from uuid import UUID
@@ -95,16 +96,9 @@ def handle_promotion_toggle():
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)
+ mark_catalogue_promotion_rules_as_dirty(
+ set(promotions.values_list("id", flat=True))
)
- if product_ids:
- # Recalculate discounts of affected products
- update_products_discounted_prices_for_promotion_task.delay(
- product_ids, rule_ids=rule_ids
- )
starting_promotion_ids = ", ".join(
[str(staring_promo.id) for staring_promo in starting_promotions]
@@ -211,6 +205,7 @@ def clear_promotion_rule_variants_task():
.values_list("pk", flat=True)
)
if rule_variants_id:
+ mark_products_in_channels_as_dirty_based_on_rules(rules, allow_replica=True)
PromotionRuleVariant.objects.filter(pk__in=rule_variants_id).delete()
clear_promotion_rule_variants_task.delay()
@@ -308,7 +303,6 @@ def update_discounted_prices_task():
if products_ids:
products = Product.objects.filter(id__in=products_ids)
update_discounted_prices_for_promotion(products)
- update_discounted_prices_task.delay()
@app.task(
diff --git a/saleor/discount/tests/test_tasks.py b/saleor/discount/tests/test_tasks.py
index 63c541221c..5232c95cef 100644
--- a/saleor/discount/tests/test_tasks.py
+++ b/saleor/discount/tests/test_tasks.py
@@ -9,6 +9,7 @@ from django.utils import timezone
from freezegun import freeze_time
from ...order.models import Order
+from ...product.models import ProductChannelListing, ProductVariant
from .. import DiscountType, RewardValueType
from ..models import OrderDiscount, OrderLineDiscount, Promotion, PromotionRule
from ..tasks import (
@@ -19,6 +20,7 @@ from ..tasks import (
handle_promotion_toggle,
set_promotion_rule_variants_task,
)
+from ..utils import mark_catalogue_promotion_rules_as_dirty
def test_fetch_promotion_variants_and_product_ids(
@@ -59,7 +61,8 @@ 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"
+ "saleor.discount.tasks.mark_catalogue_promotion_rules_as_dirty",
+ wraps=mark_catalogue_promotion_rules_as_dirty,
)
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.promotion_ended")
@@ -68,7 +71,7 @@ def test_handle_promotion_toggle(
promotion_started_mock,
promotion_ended_mock,
sale_toggle_mock,
- mock_update_products_discounted_prices_for_promotion_task,
+ mock_mark_catalogue_promotion_rules_as_dirty,
mock_clear_promotion_rule_variants_task,
product_list,
):
@@ -182,18 +185,11 @@ def test_handle_promotion_toggle(
promotions[index].refresh_from_db()
assert promotions[index].last_notification_scheduled_at == now
- mock_update_products_discounted_prices_for_promotion_task.assert_called_once()
- args, kwargs = mock_update_products_discounted_prices_for_promotion_task.call_args
- # get ids of instances assigned to promotions that toggle
- assert {product_id for product_id in args[0]} == {
- product_list[0].id,
- product_list[2].id,
- }
+ assert PromotionRule.objects.filter(variants_dirty=True).count() == 2
- assert {rule_id for rule_id in kwargs["rule_ids"]} == {
- rules[0].id,
- rules[2].id,
- }
+ mock_mark_catalogue_promotion_rules_as_dirty.assert_called_once_with(
+ set([promotions[index].id for index in indexes_of_toggle_sales])
+ )
mock_clear_promotion_rule_variants_task.assert_called_once()
@@ -223,6 +219,33 @@ def test_clear_promotion_rule_variants_task(promotion_list):
)
+def test_clear_promotion_rule_variants_task_marks_products_as_dirty(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)
+ assert not ProductChannelListing.objects.filter(discounted_price_dirty=True)
+
+ # when
+ clear_promotion_rule_variants_task()
+
+ # then
+ rule_variants = PromotionRuleVariant.objects.filter(
+ Exists(expired_rules.filter(pk=OuterRef("promotionrule_id")))
+ )
+ variant_to_product_qs = ProductVariant.objects.filter(
+ Exists(rule_variants.filter(productvariant_id=OuterRef("id")))
+ ).values_list("id", "product_id")
+ assert not ProductChannelListing.objects.filter(
+ product_id__in=[product_id for _, product_id in variant_to_product_qs],
+ discounted_price_dirty=False,
+ )
+
+
def test_set_promotion_rule_variants_task(promotion_list):
# given
Promotion.objects.update(start_date=timezone.now() - timedelta(days=5))
diff --git a/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py b/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py
new file mode 100644
index 0000000000..8c4a6a445d
--- /dev/null
+++ b/saleor/discount/tests/test_utils/test_mark_active_promotion_rules_as_dirty.py
@@ -0,0 +1,136 @@
+from datetime import datetime, timedelta
+from decimal import Decimal
+from unittest.mock import patch
+
+import graphene
+import pytz
+
+from ... import RewardValueType
+from ...models import Promotion, PromotionRule
+from ...utils import mark_active_catalogue_promotion_rules_as_dirty
+
+
+@patch("saleor.discount.utils.PromotionRule.channels.through.objects.filter")
+def test_mark_active_catalogue_promotion_rules_as_dirty_with_empty_channel_list(
+ mocked_promotion_channel_filter,
+):
+ # when
+ mark_active_catalogue_promotion_rules_as_dirty([])
+
+ # then
+ assert not mocked_promotion_channel_filter.called
+
+
+def test_mark_active_catalogue_promotion_rules_as_dirty_with_single_channel(
+ catalogue_promotion, channel_PLN
+):
+ # given
+ rules = catalogue_promotion.rules.all()
+ first_rule = rules.first()
+
+ first_rule.channels.add(channel_PLN)
+ assert rules.count() > 1
+
+ # when
+ mark_active_catalogue_promotion_rules_as_dirty([channel_PLN.id])
+
+ # then
+ first_rule.refresh_from_db()
+ assert first_rule.variants_dirty
+ assert rules.filter(variants_dirty=True).count() == 1
+
+
+def test_mark_active_catalogue_promotion_rules_as_dirty_with_multiple_channels(
+ product, catalogue_promotion, channel_PLN, channel_JPY, channel_USD
+):
+ # given
+ second_promotion = Promotion.objects.create(
+ name="Promotion",
+ end_date=datetime.now(tz=pytz.UTC) + timedelta(days=30),
+ )
+ rule_for_second_promotion = PromotionRule.objects.create(
+ name="Percentage promotion rule",
+ promotion=second_promotion,
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [graphene.Node.to_global_id("Product", product.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("10"),
+ variants_dirty=False,
+ )
+
+ rule_for_second_promotion.channels.add(channel_JPY)
+
+ rules = catalogue_promotion.rules.all()
+ first_rule = rules.first()
+
+ first_rule.channels.set([channel_PLN, channel_JPY])
+
+ # when
+ mark_active_catalogue_promotion_rules_as_dirty([channel_USD.id, channel_PLN.id])
+
+ # then
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_relations = PromotionRuleChannel.objects.filter(
+ channel_id__in=[channel_USD.id, channel_PLN.id]
+ )
+ assert (
+ PromotionRule.objects.filter(
+ id__in=channel_relations.values_list("promotionrule_id", flat=True),
+ variants_dirty=False,
+ ).count()
+ == 0
+ )
+
+ rule_for_second_promotion.refresh_from_db()
+ assert not rule_for_second_promotion.variants_dirty
+
+
+def test_mark_active_promotion_rules_as_dirty_with_multiple_promotions_and_channels(
+ product, catalogue_promotion, channel_PLN, channel_JPY, channel_USD
+):
+ # given
+ second_promotion = Promotion.objects.create(
+ name="Promotion",
+ end_date=datetime.now(tz=pytz.UTC) + timedelta(days=30),
+ )
+ rule_for_second_promotion = PromotionRule.objects.create(
+ name="Percentage promotion rule",
+ promotion=second_promotion,
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [graphene.Node.to_global_id("Product", product.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("10"),
+ variants_dirty=False,
+ )
+
+ rule_for_second_promotion.channels.add(channel_PLN, channel_JPY)
+
+ rules = catalogue_promotion.rules.all()
+ first_rule = rules.first()
+
+ first_rule.channels.set([channel_PLN, channel_JPY])
+
+ # when
+ mark_active_catalogue_promotion_rules_as_dirty([channel_USD.id, channel_PLN.id])
+
+ # then
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_relations = PromotionRuleChannel.objects.filter(
+ channel_id__in=[channel_USD.id, channel_PLN.id]
+ )
+ assert (
+ PromotionRule.objects.filter(
+ id__in=channel_relations.values_list("promotionrule_id", flat=True),
+ variants_dirty=False,
+ ).count()
+ == 0
+ )
+
+ rule_for_second_promotion.refresh_from_db()
+ assert rule_for_second_promotion.variants_dirty
diff --git a/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py b/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py
new file mode 100644
index 0000000000..ef581fbb5a
--- /dev/null
+++ b/saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py
@@ -0,0 +1,94 @@
+from datetime import datetime, timedelta
+from decimal import Decimal
+from unittest.mock import patch
+
+import graphene
+import pytz
+
+from ... import RewardValueType
+from ...models import Promotion, PromotionRule
+from ...utils import mark_catalogue_promotion_rules_as_dirty
+
+
+@patch("saleor.discount.utils.PromotionRule.objects.filter")
+def test_mark_catalogue_promotion_rules_as_dirty_with_empty_list_as_input(
+ mocked_promotion_rule_filter,
+):
+ # when
+ mark_catalogue_promotion_rules_as_dirty([])
+
+ # then
+ assert not mocked_promotion_rule_filter.called
+
+
+def test_mark_catalogue_promotion_rules_as_dirty_single_promotion(
+ catalogue_promotion, product
+):
+ # given
+ promotion = catalogue_promotion
+ second_promotion = Promotion.objects.create(
+ name="Promotion",
+ end_date=datetime.now(tz=pytz.UTC) + timedelta(days=30),
+ )
+ PromotionRule.objects.create(
+ name="Percentage promotion rule",
+ promotion=second_promotion,
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [graphene.Node.to_global_id("Product", product.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("10"),
+ variants_dirty=False,
+ )
+
+ rule = promotion.rules.first()
+ rule.variants_dirty = False
+ rule.save(update_fields=["variants_dirty"])
+
+ # when
+ mark_catalogue_promotion_rules_as_dirty([promotion])
+
+ # then
+ assert not PromotionRule.objects.filter(
+ promotion_id=promotion.id, variants_dirty=False
+ )
+ assert not PromotionRule.objects.filter(
+ promotion_id=second_promotion.id, variants_dirty=True
+ )
+
+
+def test_mark_catalogue_promotion_rules_as_dirty_multiple_promotion(
+ catalogue_promotion, product
+):
+ # given
+ promotion = catalogue_promotion
+ second_promotion = Promotion.objects.create(
+ name="Promotion",
+ end_date=datetime.now(tz=pytz.UTC) + timedelta(days=30),
+ )
+ PromotionRule.objects.create(
+ name="Percentage promotion rule",
+ promotion=second_promotion,
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [graphene.Node.to_global_id("Product", product.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("10"),
+ variants_dirty=False,
+ )
+
+ rule = promotion.rules.first()
+ rule.variants_dirty = False
+ rule.save(update_fields=["variants_dirty"])
+
+ # when
+ mark_catalogue_promotion_rules_as_dirty([promotion, second_promotion])
+
+ # then
+ assert not PromotionRule.objects.filter(
+ promotion_id__in=[promotion.id, second_promotion.id], variants_dirty=False
+ )
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 61658d95ac..174042908f 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -8,6 +8,7 @@ from uuid import UUID
import graphene
import pytz
+from django.conf import settings
from django.db import transaction
from django.db.models import Exists, F, OuterRef, QuerySet
from django.utils import timezone
@@ -29,7 +30,13 @@ from ..product.models import (
ProductVariant,
ProductVariantChannelListing,
)
-from . import DiscountType, PromotionRuleInfo, RewardType, RewardValueType
+from . import (
+ DiscountType,
+ PromotionRuleInfo,
+ PromotionType,
+ RewardType,
+ RewardValueType,
+)
from .interface import VariantPromotionRuleInfo, get_rule_translations
from .models import (
CheckoutDiscount,
@@ -49,9 +56,7 @@ if TYPE_CHECKING:
from ..order.models import Order
from ..plugins.manager import PluginsManager
from ..product.managers import ProductVariantQueryset
- from ..product.models import (
- VariantChannelListingPromotionRule,
- )
+ from ..product.models import VariantChannelListingPromotionRule
CatalogueInfo = defaultdict[str, set[Union[int, str]]]
CATALOGUE_FIELDS = ["categories", "collections", "products", "variants"]
@@ -948,15 +953,17 @@ def get_variants_to_promotion_rules_map(
promotions = Promotion.objects.active()
PromotionRuleVariant = PromotionRule.variants.through
- promotion_rule_variants = PromotionRuleVariant.objects.filter(
- Exists(variant_qs.filter(id=OuterRef("productvariant_id")))
- )
+ promotion_rule_variants = PromotionRuleVariant.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(Exists(variant_qs.filter(id=OuterRef("productvariant_id"))))
# fetch rules only for active promotions
- rules = PromotionRule.objects.filter(
+ rules = PromotionRule.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(
Exists(promotions.filter(id=OuterRef("promotion_id"))),
Exists(promotion_rule_variants.filter(promotionrule_id=OuterRef("pk"))),
- ).prefetch_related("channels")
+ )
rule_to_channel_ids_map = _get_rule_to_channel_ids_map(rules)
rules_in_bulk = rules.in_bulk()
@@ -1011,9 +1018,9 @@ def fetch_promotion_rules_for_checkout(
def _get_rule_to_channel_ids_map(rules: QuerySet):
rule_to_channel_ids_map = defaultdict(list)
PromotionRuleChannel = PromotionRule.channels.through
- promotion_rule_channels = PromotionRuleChannel.objects.filter(
- Exists(rules.filter(id=OuterRef("promotionrule_id")))
- )
+ promotion_rule_channels = PromotionRuleChannel.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(Exists(rules.filter(id=OuterRef("promotionrule_id"))))
for promotion_rule_channel in promotion_rule_channels:
rule_id = promotion_rule_channel.promotionrule_id
channel_id = promotion_rule_channel.channel_id
@@ -1076,3 +1083,53 @@ def update_rule_variant_relation(
PromotionRuleVariant.objects.bulk_create(
rules_variants_to_add, ignore_conflicts=True
)
+
+
+def get_active_catalogue_promotion_rules(
+ allow_replica: bool = False,
+) -> "QuerySet[PromotionRule]":
+ promotions = Promotion.objects.active().filter(type=PromotionType.CATALOGUE)
+ if allow_replica:
+ promotions = promotions.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ rules = (
+ PromotionRule.objects.order_by("id")
+ .filter(
+ Exists(promotions.filter(id=OuterRef("promotion_id"))),
+ )
+ .exclude(catalogue_predicate={})
+ )
+ if allow_replica:
+ rules = rules.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ return rules
+
+
+def mark_active_catalogue_promotion_rules_as_dirty(channel_ids: Iterable[int]):
+ """Force promotion rule to recalculate.
+
+ The rules which are marked as dirty, will be recalculated in background.
+ Products related to these rules will be recalculated as well.
+ """
+
+ if not channel_ids:
+ return
+
+ rules = get_active_catalogue_promotion_rules()
+ PromotionRuleChannel = PromotionRule.channels.through
+ promotion_rules = PromotionRuleChannel.objects.filter(channel_id__in=channel_ids)
+ rules = rules.filter(
+ Exists(promotion_rules.filter(promotionrule_id=OuterRef("id")))
+ )
+ rules.update(variants_dirty=True)
+
+
+def mark_catalogue_promotion_rules_as_dirty(promotion_pks: Iterable[UUID]):
+ """Mark rules for promotions as dirty.
+
+ The rules which are marked as dirty, will be recalculated in background.
+ Products related to these rules will be recalculated as well.
+ """
+ if not promotion_pks:
+ return
+ PromotionRule.objects.filter(promotion_id__in=promotion_pks).update(
+ variants_dirty=True
+ )
diff --git a/saleor/graphql/discount/mutations/bulk_mutations.py b/saleor/graphql/discount/mutations/bulk_mutations.py
index 6074283f47..ae977c041d 100644
--- a/saleor/graphql/discount/mutations/bulk_mutations.py
+++ b/saleor/graphql/discount/mutations/bulk_mutations.py
@@ -6,9 +6,11 @@ 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.tasks import update_discounted_prices_task
+from ....product.utils.product import (
+ get_channel_to_products_map_from_rules,
+ mark_products_in_channels_as_dirty,
+)
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...core import ResolveInfo
@@ -87,7 +89,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_for_promotions(queryset)
+ channel_to_products_map = cls.get_channel_to_products_map(queryset)
queryset.delete()
@@ -97,7 +99,8 @@ class SaleBulkDelete(ModelBulkDeleteMutation):
cls.call_event(
manager.sale_deleted, sale, catalogue_info, webhooks=webhooks
)
- update_discounted_prices_task.delay(list(product_ids))
+ if channel_to_products_map:
+ cls.call_event(mark_products_in_channels_as_dirty, channel_to_products_map)
@classmethod
def get_sale_and_rules(cls, qs: QuerySet[models.Promotion]):
@@ -114,11 +117,11 @@ class SaleBulkDelete(ModelBulkDeleteMutation):
)
@classmethod
- def get_product_ids_for_promotions(cls, qs: QuerySet[models.Promotion]):
+ def get_channel_to_products_map(cls, qs: QuerySet[models.Promotion]):
rules = models.PromotionRule.objects.filter(
Exists(qs.filter(id=OuterRef("promotion_id")))
)
- return set(get_current_products_for_rules(rules).values_list("id", flat=True))
+ return get_channel_to_products_map_from_rules(rules)
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 149aabb4e0..a4d43ec015 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_bulk_delete.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_bulk_delete.py
@@ -2,9 +2,11 @@ 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.tasks import update_discounted_prices_task
+from .....product.utils.product import (
+ get_channel_to_products_map_from_rules,
+ mark_products_in_channels_as_dirty,
+)
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.utils import get_webhooks_for_event
from ....core import ResolveInfo
@@ -39,20 +41,21 @@ class PromotionBulkDelete(ModelBulkDeleteMutation):
@classmethod
def bulk_action(cls, info: ResolveInfo, queryset, /):
- product_ids = cls.get_product_ids(queryset)
+ channel_to_products_map = cls.get_product_and_channel_map(queryset)
promotions = [promotion for promotion in queryset]
queryset.delete()
manager = get_plugin_manager_promise(info.context).get()
webhooks = get_webhooks_for_event(WebhookEventAsyncType.PROMOTION_DELETED)
for promotion in promotions:
cls.call_event(manager.promotion_deleted, promotion, webhooks=webhooks)
-
- update_discounted_prices_task.delay(list(product_ids))
+ if channel_to_products_map:
+ cls.call_event(mark_products_in_channels_as_dirty, channel_to_products_map)
@classmethod
- def get_product_ids(cls, qs: QuerySet[models.Promotion]):
+ def get_product_and_channel_map(cls, qs: QuerySet[models.Promotion]):
rules = models.PromotionRule.objects.filter(
Exists(qs.filter(id=OuterRef("promotion_id")))
)
- products = get_current_products_for_rules(rules)
- return set(products.values_list("id", flat=True))
+ channel_to_products_map = get_channel_to_products_map_from_rules(rules)
+
+ return channel_to_products_map
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_create.py b/saleor/graphql/discount/mutations/promotion/promotion_create.py
index 5f96b4f69c..effdec139a 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_create.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_create.py
@@ -13,7 +13,6 @@ from .....channel import models as channel_models
from .....discount import PromotionType, events, models
from .....permission.enums import DiscountPermissions
from .....plugins.manager import PluginsManager
-from .....product.tasks import update_products_discounted_prices_of_promotion_task
from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....channel.types import Channel
@@ -30,6 +29,7 @@ from ....utils import get_nodes
from ...enums import PromotionCreateErrorCode, PromotionTypeEnum
from ...inputs import PromotionRuleBaseInput
from ...types import Promotion
+from ..utils import promotion_rule_should_be_marked_with_dirty_variants
from .validators import clean_promotion_rule
@@ -238,6 +238,10 @@ class PromotionCreate(ModelMutation):
channels = rule_data.pop("channels", None)
gifts = rule_data.pop("gifts", None)
rule = models.PromotionRule(promotion=instance, **rule_data)
+ if promotion_rule_should_be_marked_with_dirty_variants(
+ rule, instance.type, channels
+ ):
+ rule.variants_dirty = True
if gifts:
rule.gifts.set(gifts)
if channels:
@@ -263,9 +267,6 @@ class PromotionCreate(ModelMutation):
cls.call_event(manager.promotion_created, instance)
if has_started:
cls.send_promotion_started_webhook(manager, instance)
- cls.call_event(
- update_products_discounted_prices_of_promotion_task.delay, instance.pk
- )
@classmethod
def has_started(cls, instance: models.Promotion) -> bool:
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_delete.py b/saleor/graphql/discount/mutations/promotion/promotion_delete.py
index bfd8f067fb..d375ac910a 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_delete.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_delete.py
@@ -2,10 +2,12 @@ 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_discounted_prices_task
+from .....product.utils.product import (
+ get_channel_to_products_map_from_rules,
+ mark_products_in_channels_as_dirty,
+)
from .....webhook.event_types import WebhookEventAsyncType
from ....core import ResolveInfo
from ....core.descriptions import ADDED_IN_317, PREVIEW_FEATURE
@@ -47,16 +49,15 @@ 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_current_products_for_rules(instance.rules.all()).values_list(
- "id", flat=True
- )
- )
+ rules = instance.rules.all()
+ channel_to_products_map = get_channel_to_products_map_from_rules(rules)
+
promotion_id = instance.id
with transaction.atomic():
response = super().perform_mutation(root, info, id=id)
instance.id = promotion_id
cls.call_event(manager.promotion_deleted, instance)
- update_discounted_prices_task.delay(product_ids)
+ if channel_to_products_map:
+ cls.call_event(mark_products_in_channels_as_dirty, channel_to_products_map)
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 38e95e022e..5d678ca431 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_discounted_prices_task
+from .....product.utils.product import mark_products_in_channels_as_dirty
from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
@@ -18,7 +18,10 @@ from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import PromotionRuleCreateErrorCode
from ...types import PromotionRule
from ...utils import get_products_for_rule
-from ..utils import clear_promotion_old_sale_id
+from ..utils import (
+ clear_promotion_old_sale_id,
+ promotion_rule_should_be_marked_with_dirty_variants,
+)
from .promotion_create import PromotionRuleInput
from .validators import clean_promotion_rule
@@ -93,10 +96,18 @@ class PromotionRuleCreate(ModelMutation):
@classmethod
def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
products = get_products_for_rule(instance, update_rule_variants=True)
- if products:
- update_discounted_prices_task.delay(
- list(products.values_list("id", flat=True))
- )
+ promotion = cleaned_input["promotion"]
+ channel_ids = instance.channels.values_list("id", flat=True)
+
+ if promotion_rule_should_be_marked_with_dirty_variants(
+ instance, promotion.type, channel_ids
+ ):
+ if product_ids := set(products.values_list("id", flat=True)):
+ cls.call_event(
+ mark_products_in_channels_as_dirty,
+ {channel_id: product_ids for channel_id in channel_ids},
+ )
+
clear_promotion_old_sale_id(instance.promotion, save=True)
app = get_app_promise(info.context).get()
events.rule_created_event(info.context.user, app, [instance])
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_delete.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_delete.py
index 450d96d327..7e5f26f8a2 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_delete.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_delete.py
@@ -1,10 +1,12 @@
import graphene
-from .....discount import events, models
-from .....discount.utils import get_current_products_for_rules
+from .....discount import PromotionType, events, models
from .....graphql.core.mutations import ModelDeleteMutation
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_discounted_prices_task
+from .....product.utils.product import (
+ get_channel_to_products_map_from_rules,
+ mark_products_in_channels_as_dirty,
+)
from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
@@ -49,12 +51,11 @@ class PromotionRuleDelete(ModelDeleteMutation):
"""Perform a mutation that deletes a model instance."""
instance = cls.get_instance(info, external_reference=external_reference, id=id)
cls.clean_instance(info, instance)
-
- products = get_current_products_for_rules(
- models.PromotionRule.objects.filter(id=instance.id)
- )
- product_ids = list(products.values_list("id", flat=True))
-
+ channel_to_products_map = {}
+ if instance.promotion.type == PromotionType.CATALOGUE:
+ channel_to_products_map = get_channel_to_products_map_from_rules(
+ models.PromotionRule.objects.filter(id=instance.id)
+ )
db_id = instance.id
promotion = instance.promotion
instance.delete()
@@ -65,8 +66,8 @@ class PromotionRuleDelete(ModelDeleteMutation):
# ID so that the success response contains ID of the deleted object.
instance.id = db_id
- if product_ids:
- update_discounted_prices_task.delay(product_ids)
+ if channel_to_products_map:
+ cls.call_event(mark_products_in_channels_as_dirty, channel_to_products_map)
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 2e0266193f..67451e3056 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py
@@ -4,10 +4,10 @@ import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
-from .....discount import events, models
+from .....discount import PromotionType, events, models
from .....discount.utils import get_current_products_for_rules
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_discounted_prices_task
+from .....product.utils.product import mark_products_in_channels_as_dirty
from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
@@ -23,9 +23,7 @@ from ...inputs import PromotionRuleBaseInput
from ...types import PromotionRule
from ...utils import get_products_for_rule
from ..utils import clear_promotion_old_sale_id
-from .validators import (
- clean_promotion_rule,
-)
+from .validators import clean_promotion_rule
class PromotionRuleUpdateError(Error):
@@ -101,15 +99,23 @@ class PromotionRuleUpdate(ModelMutation):
data = data.get("input")
cleaned_input = cls.clean_input(info, instance, data)
instance = cls.construct_instance(instance, cleaned_input)
+ promotion_type = instance.promotion.type
+
+ previous_product_ids = set()
+ removed_channel_ids = []
+ if promotion_type == PromotionType.CATALOGUE:
+ 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))
+ removed_channel_ids = [
+ channel.id for channel in cleaned_input.get("remove_channels", [])
+ ]
- 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)
cls._save_m2m(info, instance, cleaned_input)
- cls.post_save_actions(info, instance, previous_product_ids)
+ cls.post_save_actions(info, instance, previous_product_ids, removed_channel_ids)
return cls.success_response(instance)
@@ -157,11 +163,25 @@ class PromotionRuleUpdate(ModelMutation):
instance.gifts.add(*add_gifts)
@classmethod
- def post_save_actions(cls, info: ResolveInfo, instance, previous_product_ids):
- 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_discounted_prices_task.delay(list(product_ids))
+ def post_save_actions(
+ cls, info: ResolveInfo, instance, previous_product_ids, removed_channel_ids
+ ):
+ if instance.promotion.type == PromotionType.CATALOGUE:
+ # no need to trigger the logic to recalculate the prices if the promotion
+ # type is different from CATALOGUE
+ products = get_products_for_rule(instance, update_rule_variants=True)
+ product_ids = (
+ set(products.values_list("id", flat=True)) | previous_product_ids
+ )
+ channel_ids_to_update = (
+ list(instance.channels.values_list("id", flat=True))
+ + removed_channel_ids
+ )
+ if product_ids:
+ cls.call_event(
+ mark_products_in_channels_as_dirty,
+ {channel_id: product_ids for channel_id in channel_ids_to_update},
+ )
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/promotion/promotion_update.py b/saleor/graphql/discount/mutations/promotion/promotion_update.py
index 9f36d08d2d..63d8db9b41 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_update.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_update.py
@@ -6,10 +6,10 @@ import pytz
from django.core.exceptions import ValidationError
from django.db import transaction
-from .....discount import events, models
+from .....discount import PromotionType, events, models
+from .....discount.utils import mark_catalogue_promotion_rules_as_dirty
from .....permission.enums import DiscountPermissions
from .....plugins.manager import PluginsManager
-from .....product.tasks import update_products_discounted_prices_of_promotion_task
from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
@@ -108,10 +108,10 @@ class PromotionUpdate(ModelMutation):
# update the product undiscounted prices for promotion only when
# start or end date has changed
- if "start_date" in cleaned_input or "end_date" in cleaned_input:
- cls.call_event(
- update_products_discounted_prices_of_promotion_task.delay, instance.pk
- )
+ if instance.type == PromotionType.CATALOGUE and (
+ "start_date" in cleaned_input or "end_date" in cleaned_input
+ ):
+ cls.call_event(mark_catalogue_promotion_rules_as_dirty, [instance.pk])
@classmethod
def get_toggle_type(cls, instance, clean_input, previous_end_date) -> Optional[str]:
diff --git a/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py b/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
index 451acca49a..1b7c501b34 100644
--- a/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
+++ b/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
@@ -7,8 +7,8 @@ from django.db.models import Exists, OuterRef
from .....discount.error_codes import DiscountErrorCode
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 .....product.utils.product import mark_products_in_channels_as_dirty
from ....core import ResolveInfo
from ....core.mutations import BaseMutation
from ....plugins.dataloaders import get_plugin_manager_promise
@@ -69,7 +69,16 @@ class SaleBaseCatalogueMutation(BaseMutation):
product_ids = new_product_ids - previous_product_ids
else:
product_ids = previous_product_ids - new_product_ids
- update_discounted_prices_task.delay(list(product_ids))
+
+ rules = promotion.rules.all()
+ PromotionRuleChannel = rules.model.channels.through
+ channel_ids = PromotionRuleChannel.objects.filter(
+ Exists(rules.filter(id=OuterRef("promotionrule_id")))
+ ).values_list("channel_id", flat=True)
+ cls.call_event(
+ mark_products_in_channels_as_dirty,
+ {channel_id: product_ids for channel_id in channel_ids},
+ )
@classmethod
def get_product_ids_for_predicate(cls, predicate: dict) -> set[int]:
diff --git a/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py b/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
index 22c677b219..27cab4bf37 100644
--- a/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
+++ b/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
@@ -10,8 +10,8 @@ from .....core.tracing import traced_atomic_transaction
from .....discount import DiscountValueType
from .....discount.error_codes import DiscountErrorCode
from .....discount.models import Promotion, PromotionRule
+from .....discount.utils import mark_catalogue_promotion_rules_as_dirty
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_products_discounted_prices_of_promotion_task
from ....channel import ChannelContext
from ....channel.mutations import BaseChannelListingMutation
from ....core import ResolveInfo
@@ -223,9 +223,7 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):
with traced_atomic_transaction():
cls.add_channels(promotion, rule, cleaned_input.get("add_channels", []))
cls.remove_channels(promotion, cleaned_input.get("remove_channels", []))
- cls.call_event(
- update_products_discounted_prices_of_promotion_task.delay, promotion.pk
- )
+ cls.call_event(mark_catalogue_promotion_rules_as_dirty, [promotion.pk])
@classmethod
def get_instance(cls, id):
diff --git a/saleor/graphql/discount/mutations/sale/sale_create.py b/saleor/graphql/discount/mutations/sale/sale_create.py
index 19a5279df2..3361bba7fc 100644
--- a/saleor/graphql/discount/mutations/sale/sale_create.py
+++ b/saleor/graphql/discount/mutations/sale/sale_create.py
@@ -8,8 +8,8 @@ from .....core.tracing import traced_atomic_transaction
from .....discount import PromotionType, models
from .....discount.error_codes import DiscountErrorCode
from .....discount.models import Promotion
+from .....discount.utils import mark_catalogue_promotion_rules_as_dirty
from .....permission.enums import DiscountPermissions
-from .....product.tasks import update_products_discounted_prices_of_promotion_task
from .....webhook.event_types import WebhookEventAsyncType
from ....channel import ChannelContext
from ....core import ResolveInfo
@@ -132,9 +132,7 @@ class SaleCreate(ModelMutation):
)
manager = get_plugin_manager_promise(info.context).get()
cls.send_sale_notifications(manager, promotion, predicate)
- cls.call_event(
- update_products_discounted_prices_of_promotion_task.delay, promotion.pk
- )
+ cls.call_event(mark_catalogue_promotion_rules_as_dirty, [promotion.pk])
return response
@classmethod
diff --git a/saleor/graphql/discount/mutations/sale/sale_delete.py b/saleor/graphql/discount/mutations/sale/sale_delete.py
index 8b937d3387..a387ea2392 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_discounted_prices_task
+from .....product.utils.product import mark_products_in_channels_as_dirty
from .....webhook.event_types import WebhookEventAsyncType
from ....channel import ChannelContext
from ....core import ResolveInfo
@@ -57,6 +57,7 @@ class SaleDelete(ModelDeleteMutation):
old_sale_id = promotion.old_sale_id
promotion_id = promotion.id
rule = promotion.rules.first()
+ channels_ids = rule.channels.values_list("id", flat=True)
previous_catalogue = cls.get_catalogue_info(rule)
product_ids = cls.get_product_ids(rule)
with traced_atomic_transaction():
@@ -68,7 +69,10 @@ class SaleDelete(ModelDeleteMutation):
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.sale_deleted, promotion, previous_catalogue)
- update_discounted_prices_task.delay(list(product_ids))
+ cls.call_event(
+ mark_products_in_channels_as_dirty,
+ {channel_id: product_ids for channel_id in channels_ids},
+ )
return response
diff --git a/saleor/graphql/discount/mutations/sale/sale_update.py b/saleor/graphql/discount/mutations/sale/sale_update.py
index 76e115008c..fffa4c6458 100644
--- a/saleor/graphql/discount/mutations/sale/sale_update.py
+++ b/saleor/graphql/discount/mutations/sale/sale_update.py
@@ -11,7 +11,7 @@ from .....discount.error_codes import DiscountErrorCode
from .....discount.utils import CATALOGUE_FIELDS
from .....permission.enums import DiscountPermissions
from .....product import models as product_models
-from .....product.tasks import update_discounted_prices_task
+from .....product.utils.product import mark_products_in_channels_as_dirty
from .....webhook.event_types import WebhookEventAsyncType
from ....channel import ChannelContext
from ....core import ResolveInfo
@@ -172,6 +172,7 @@ class SaleUpdate(ModelMutation):
previous_product_ids,
):
rule = promotion.rules.first()
+ channel_ids = rule.channels.values_list("id", flat=True)
current_predicate = rule.catalogue_predicate
current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(
current_predicate
@@ -185,7 +186,6 @@ class SaleUpdate(ModelMutation):
current_catalogue,
previous_end_date,
)
-
if any(
field in input.keys()
for field in [*CATALOGUE_FIELDS, "start_date", "end_date", "type"]
@@ -198,7 +198,11 @@ class SaleUpdate(ModelMutation):
)
update_variants_for_promotion(variants, promotion)
if product_ids | previous_product_ids:
- update_discounted_prices_task.delay(list(product_ids))
+ product_ids_to_update = product_ids | previous_product_ids
+ cls.call_event(
+ mark_products_in_channels_as_dirty,
+ {channel_id: product_ids_to_update for channel_id in channel_ids},
+ )
@classmethod
def send_sale_notifications(
diff --git a/saleor/graphql/discount/mutations/utils.py b/saleor/graphql/discount/mutations/utils.py
index c6d0ed2e18..ed69f6dc36 100644
--- a/saleor/graphql/discount/mutations/utils.py
+++ b/saleor/graphql/discount/mutations/utils.py
@@ -3,6 +3,7 @@ from collections import defaultdict
import graphene
from django.db.models import QuerySet
+from ....discount import PromotionType
from ....discount.models import Promotion, PromotionRule
from ....discount.utils import CatalogueInfo, update_rule_variant_relation
from ....product.models import ProductVariant
@@ -52,3 +53,28 @@ def update_variants_for_promotion(
]
)
update_rule_variant_relation(rules, promotion_rule_variants)
+
+
+def promotion_rule_should_be_marked_with_dirty_variants(
+ rule: PromotionRule, promotion_type: str, channels: list
+):
+ """Check if the promotion rule should be marked as the one with dirty variants.
+
+ There are no need to always mark rule as dirty. First, we should validate that
+ the rule has all details required to calculate the discount.
+ Keep in mind that in case of update applied on rule, this function should not be
+ called, previous version of rule could have an impact on products.
+ """
+ if promotion_type != PromotionType.CATALOGUE:
+ return False
+ if rule.reward_value is None:
+ return False
+ if rule.reward_value <= 0:
+ return False
+ if rule.catalogue_predicate == {}:
+ return False
+ if rule.reward_value_type is None:
+ return False
+ if not channels:
+ return False
+ return True
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py b/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
index 8ecf280276..6f7d0bcaa4 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
@@ -196,7 +196,7 @@ def test_promotion_create_order_promotion(
}
# when
- with django_assert_num_queries(40):
+ with django_assert_num_queries(37):
response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)
# then
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py b/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py
index bc10dc0604..b16ff78476 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py
@@ -50,7 +50,7 @@ def test_gift_promotion_delete(
}
# when
- with django_assert_num_queries(23):
+ with django_assert_num_queries(25):
content = get_graphql_content(
staff_api_client.post_graphql(PROMOTION_DELETE_MUTATION, variables)
)
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 a7e5e63a25..6a5290a686 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_bulk_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_bulk_delete.py
@@ -2,7 +2,8 @@ from unittest import mock
import graphene
-from .....discount.models import Promotion
+from .....discount.models import Promotion, PromotionRule
+from .....product.models import ProductChannelListing, ProductVariant
from ....tests.utils import get_graphql_content
PROMOTION_BULK_DELETE_MUTATION = """
@@ -77,9 +78,7 @@ def test_delete_promotions_by_app(
@mock.patch("saleor.plugins.manager.PluginsManager.promotion_deleted")
[email protected]("saleor.product.tasks.update_discounted_prices_task.delay")
def test_delete_promotions_trigger_webhooks(
- update_discounted_prices_task,
deleted_webhook_mock,
staff_api_client,
promotion_list,
@@ -101,5 +100,40 @@ def test_delete_promotions_trigger_webhooks(
)
# then
- update_discounted_prices_task.called_once()
assert deleted_webhook_mock.call_count == len(promotion_list)
+
+
+def test_delete_promotions_marks_product_to_recalculate(
+ staff_api_client, promotion_list, permission_manage_discounts, channel_USD
+):
+ # given
+ rules = PromotionRule.objects.filter(promotion__in=promotion_list)
+ PromotionRuleVariant = PromotionRule.variants.through
+ variant_ids = PromotionRuleVariant.objects.filter(
+ promotionrule_id__in=rules
+ ).values_list("productvariant_id", flat=True)
+ product_ids = ProductVariant.objects.filter(id__in=variant_ids).values_list(
+ "product_id", flat=True
+ )
+ assert ProductChannelListing.objects.filter(
+ product_id__in=product_ids, channel=channel_USD, discounted_price_dirty=False
+ ).exists()
+
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("Promotion", promotion.id)
+ for promotion in promotion_list
+ ]
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ PROMOTION_BULK_DELETE_MUTATION,
+ variables,
+ permissions=[permission_manage_discounts],
+ )
+
+ # then
+ assert not ProductChannelListing.objects.filter(
+ product_id__in=product_ids, channel=channel_USD, discounted_price_dirty=False
+ ).exists()
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_create.py b/saleor/graphql/discount/tests/mutations/test_promotion_create.py
index 7a58239657..aabb73d1bb 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_create.py
@@ -59,13 +59,11 @@ PROMOTION_CREATE_MUTATION = """
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_started")
@patch("saleor.plugins.manager.PluginsManager.promotion_created")
def test_promotion_create_by_staff_user(
promotion_created_mock,
promotion_started_mock,
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_group_manage_discounts,
description_json,
@@ -177,19 +175,16 @@ def test_promotion_create_by_staff_user(
promotion_created_mock.assert_called_once_with(promotion)
promotion_started_mock.assert_called_once_with(promotion)
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- promotion.id
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_started")
@patch("saleor.plugins.manager.PluginsManager.promotion_created")
def test_promotion_create_by_app(
promotion_created_mock,
promotion_started_mock,
- update_products_discounted_prices_of_promotion_task_mock,
app_api_client,
permission_manage_discounts,
description_json,
@@ -257,9 +252,8 @@ def test_promotion_create_by_app(
promotion_created_mock.assert_called_once_with(promotion)
promotion_started_mock.assert_called_once_with(promotion)
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- promotion.id
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
@freeze_time("2020-03-18 12:00:00")
@@ -591,13 +585,11 @@ def test_promotion_create_invalid_percentage_value(
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_started")
@patch("saleor.plugins.manager.PluginsManager.promotion_created")
def test_promotion_create_only_name_and_end_date(
promotion_created_mock,
promotion_started_mock,
- update_products_discounted_prices_of_promotion_task_mock,
app_api_client,
permission_manage_discounts,
description_json,
@@ -635,19 +627,16 @@ def test_promotion_create_only_name_and_end_date(
promotion_created_mock.assert_called_once_with(promotion)
promotion_started_mock.assert_called_once_with(promotion)
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- promotion.id
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_started")
@patch("saleor.plugins.manager.PluginsManager.promotion_created")
def test_promotion_create_start_date_and_end_date_after_current_date(
promotion_created_mock,
promotion_started_mock,
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_group_manage_discounts,
description_json,
@@ -759,9 +748,8 @@ def test_promotion_create_start_date_and_end_date_after_current_date(
promotion_created_mock.assert_called_once_with(promotion)
promotion_started_mock.assert_not_called()
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- promotion.id
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
@freeze_time("2020-03-18 12:00:00")
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_delete.py b/saleor/graphql/discount/tests/mutations/test_promotion_delete.py
index f318494f43..3c7b512476 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_delete.py
@@ -3,7 +3,10 @@ from unittest.mock import patch
import graphene
import pytest
+from .....discount.models import PromotionRule
+from .....product.models import ProductChannelListing
from ....tests.utils import assert_no_permission, get_graphql_content
+from ...utils import get_products_for_promotion
PROMOTION_DELETE_MUTATION = """
mutation promotionDelete($id: ID!) {
@@ -22,11 +25,9 @@ PROMOTION_DELETE_MUTATION = """
"""
-@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_discounted_prices_task_mock,
staff_api_client,
permission_group_manage_discounts,
catalogue_promotion,
@@ -35,6 +36,15 @@ def test_promotion_delete_by_staff_user(
permission_group_manage_discounts.user_set.add(staff_api_client.user)
promotion = catalogue_promotion
variables = {"id": graphene.Node.to_global_id("Promotion", promotion.id)}
+ PromotionRuleChannel = PromotionRule.channels.through
+ channels_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ products_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
# when
response = staff_api_client.post_graphql(PROMOTION_DELETE_MUTATION, variables)
@@ -49,14 +59,15 @@ def test_promotion_delete_by_staff_user(
with pytest.raises(promotion._meta.model.DoesNotExist):
promotion.refresh_from_db()
- update_discounted_prices_task_mock.assert_called_once()
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channels_ids, product_id__in=products_ids
+ ):
+ assert listing.discounted_price_dirty is True
-@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_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
catalogue_promotion,
@@ -64,6 +75,15 @@ def test_promotion_delete_by_staff_app(
# given
promotion = catalogue_promotion
variables = {"id": graphene.Node.to_global_id("Promotion", promotion.id)}
+ PromotionRuleChannel = PromotionRule.channels.through
+ channels_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ products_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
# when
response = app_api_client.post_graphql(
@@ -79,19 +99,31 @@ def test_promotion_delete_by_staff_app(
with pytest.raises(promotion._meta.model.DoesNotExist):
promotion.refresh_from_db()
- update_discounted_prices_task_mock.assert_called_once()
+
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channels_ids, product_id__in=products_ids
+ ):
+ assert listing.discounted_price_dirty is True
-@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_discounted_prices_task_mock,
api_client,
catalogue_promotion,
):
# given
- variables = {"id": graphene.Node.to_global_id("Promotion", catalogue_promotion.id)}
+ promotion = catalogue_promotion
+ variables = {"id": graphene.Node.to_global_id("Promotion", promotion.id)}
+ PromotionRuleChannel = PromotionRule.channels.through
+ channels_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ products_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
# when
response = api_client.post_graphql(PROMOTION_DELETE_MUTATION, variables)
@@ -100,4 +132,7 @@ def test_promotion_delete_by_customer(
assert_no_permission(response)
promotion_deleted_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_not_called()
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channels_ids, product_id__in=products_ids
+ ):
+ assert listing.discounted_price_dirty is False
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 4490ff3a46..11c0bd17ee 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py
@@ -7,6 +7,7 @@ from django.test import override_settings
from .....discount import PromotionEvents
from .....discount.error_codes import PromotionRuleCreateErrorCode
from .....discount.models import PromotionEvent
+from .....product.models import ProductChannelListing
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import RewardTypeEnum, RewardValueTypeEnum
@@ -54,9 +55,7 @@ PROMOTION_RULE_CREATE_MUTATION = """
@patch("saleor.plugins.manager.PluginsManager.promotion_rule_created")
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_by_staff_user(
- update_discounted_prices_task_mock,
promotion_rule_created_mock,
staff_api_client,
permission_group_manage_discounts,
@@ -127,6 +126,10 @@ def test_promotion_rule_create_by_staff_user(
content = get_graphql_content(response)
data = content["data"]["promotionRuleCreate"]
rule_data = data["promotionRule"]
+ product.refresh_from_db()
+ listings = ProductChannelListing.objects.filter(
+ channel__in=[channel_USD, channel_PLN], product=product
+ )
assert not data["errors"]
assert rule_data["name"] == name
@@ -138,14 +141,13 @@ 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_discounted_prices_task_mock.assert_called_once_with([product.id])
rule = promotion.rules.last()
promotion_rule_created_mock.assert_called_once_with(rule)
+ for listing in listings:
+ assert listing.discounted_price_dirty is True
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_by_app(
- update_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
description_json,
@@ -211,14 +213,9 @@ 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_discounted_prices_task_mock.assert_called_once_with(
- [category.products.first().id]
- )
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_by_customer(
- update_discounted_prices_task_mock,
api_client,
description_json,
channel_USD,
@@ -263,7 +260,11 @@ def test_promotion_rule_create_by_customer(
# when
response = api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
assert_no_permission(response)
- update_discounted_prices_task_mock.assert_not_called()
+
+ # then
+ product = category.products.first()
+ listing = ProductChannelListing.objects.get(channel=channel_USD, product=product)
+ assert listing.discounted_price_dirty is False
def test_promotion_rule_create_missing_predicate(
@@ -876,9 +877,7 @@ def test_promotion_rule_create_percentage_value_above_100(
assert promotion.rules.count() == rules_count
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_clears_old_sale_id(
- update_discounted_prices_task_mock,
staff_api_client,
permission_group_manage_discounts,
description_json,
@@ -931,7 +930,10 @@ def test_promotion_rule_create_clears_old_sale_id(
content = get_graphql_content(response)
data = content["data"]["promotionRuleCreate"]
rule_data = data["promotionRule"]
-
+ product.refresh_from_db()
+ listings = ProductChannelListing.objects.filter(
+ channel__in=[channel_USD, channel_PLN], product=product
+ )
assert not data["errors"]
assert rule_data["name"] == name
assert rule_data["description"] == description_json
@@ -942,7 +944,9 @@ 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_discounted_prices_task_mock.assert_called_once_with([product.id])
+
+ for listing in listings:
+ assert listing.discounted_price_dirty is True
promotion.refresh_from_db()
assert promotion.old_sale_id is None
@@ -1001,9 +1005,7 @@ def test_promotion_rule_create_events(
@patch("saleor.plugins.manager.PluginsManager.promotion_rule_created")
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_create_serializable_decimal_in_predicate(
- update_discounted_prices_task_mock,
promotion_rule_created_mock,
staff_api_client,
permission_group_manage_discounts,
@@ -1302,11 +1304,7 @@ def test_promotion_rule_create_reward_type_with_catalogue_predicate(
@patch("saleor.plugins.manager.PluginsManager.promotion_rule_created")
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_promotion_rule_create_order_predicate(
- update_products_discounted_prices_for_promotion_task_mock,
promotion_rule_created_mock,
staff_api_client,
permission_group_manage_discounts,
@@ -1362,6 +1360,7 @@ def test_promotion_rule_create_order_predicate(
assert rule_data["promotion"]["id"] == promotion_id
assert promotion.rules.count() == rules_count + 1
rule = promotion.rules.last()
+ assert not rule.variants_dirty
promotion_rule_created_mock.assert_called_once_with(rule)
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 bcf82218bc..ae0d580eb6 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py
@@ -1,11 +1,11 @@
-from unittest.mock import patch
-
import graphene
import pytest
from .....discount import PromotionEvents
from .....discount.models import PromotionEvent
+from .....product.models import ProductChannelListing
from ....tests.utils import assert_no_permission, get_graphql_content
+from ...utils import get_products_for_promotion
PROMOTION_RULE_DELETE_MUTATION = """
mutation promotionRuleDelete($id: ID!) {
@@ -34,21 +34,18 @@ PROMOTION_RULE_DELETE_MUTATION = """
"""
-@patch("saleor.plugins.manager.PluginsManager.promotion_rule_deleted")
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_delete_by_staff_user(
- update_discounted_prices_task_mock,
- promotion_rule_deleted_mock,
staff_api_client,
permission_group_manage_discounts,
catalogue_promotion,
product,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- rule = catalogue_promotion.rules.get(name="Percentage promotion rule")
+ rule = promotion.rules.get(name="Percentage promotion rule")
variables = {"id": graphene.Node.to_global_id("PromotionRule", rule.id)}
-
+ channels_ids = set(rule.channels.values_list("id", flat=True))
# when
response = staff_api_client.post_graphql(PROMOTION_RULE_DELETE_MUTATION, variables)
@@ -59,21 +56,24 @@ def test_promotion_rule_delete_by_staff_user(
with pytest.raises(rule._meta.model.DoesNotExist):
rule.refresh_from_db()
- update_discounted_prices_task_mock.assert_called_once_with([product.id])
- promotion_rule_deleted_mock.assert_called_once_with(rule)
+ listings = ProductChannelListing.objects.filter(
+ channel__in=channels_ids, product=product
+ )
+ for listing in listings:
+ assert listing.discounted_price_dirty is True
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_delete_by_staff_app(
- update_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
catalogue_promotion,
product,
):
# given
- rule = catalogue_promotion.rules.get(name="Percentage promotion rule")
+ promotion = catalogue_promotion
+ rule = promotion.rules.get(name="Percentage promotion rule")
variables = {"id": graphene.Node.to_global_id("PromotionRule", rule.id)}
+ channels_ids = set(rule.channels.values_list("id", flat=True))
# when
response = app_api_client.post_graphql(
@@ -89,28 +89,34 @@ def test_promotion_rule_delete_by_staff_app(
with pytest.raises(rule._meta.model.DoesNotExist):
rule.refresh_from_db()
- update_discounted_prices_task_mock.assert_called_once_with([product.id])
+ listings = ProductChannelListing.objects.filter(
+ channel__in=channels_ids, product=product
+ )
+ for listing in listings:
+ assert listing.discounted_price_dirty is True
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
-def test_promotion_rule_delete_by_customer(
- update_discounted_prices_task_mock, api_client, catalogue_promotion
-):
+def test_promotion_rule_delete_by_customer(api_client, catalogue_promotion):
# given
- rule = catalogue_promotion.rules.first()
+ promotion = catalogue_promotion
+ rule = promotion.rules.first()
variables = {"id": graphene.Node.to_global_id("PromotionRule", rule.id)}
+ products = get_products_for_promotion(promotion)
+ channels_ids = set(rule.channels.values_list("id", flat=True))
# when
response = api_client.post_graphql(PROMOTION_RULE_DELETE_MUTATION, variables)
# then
assert_no_permission(response)
- update_discounted_prices_task_mock.assert_not_called()
+ listings = ProductChannelListing.objects.filter(
+ channel__in=channels_ids, product__in=products
+ )
+ for listing in listings:
+ assert listing.discounted_price_dirty is False
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_delete_clears_old_sale_id(
- update_discounted_prices_task_mock,
staff_api_client,
permission_group_manage_discounts,
promotion_converted_from_sale,
@@ -120,6 +126,7 @@ def test_promotion_delete_clears_old_sale_id(
permission_group_manage_discounts.user_set.add(staff_api_client.user)
promotion = promotion_converted_from_sale
rule = promotion.rules.first()
+ channels_ids = set(rule.channels.values_list("id", flat=True))
assert promotion.old_sale_id
@@ -129,17 +136,21 @@ def test_promotion_delete_clears_old_sale_id(
response = staff_api_client.post_graphql(PROMOTION_RULE_DELETE_MUTATION, variables)
# then
+ listings = ProductChannelListing.objects.filter(
+ channel__in=channels_ids, product=product
+ )
content = get_graphql_content(response)
data = content["data"]["promotionRuleDelete"]
assert data["promotionRule"]["name"] == rule.name
with pytest.raises(rule._meta.model.DoesNotExist):
rule.refresh_from_db()
- update_discounted_prices_task_mock.assert_called_once_with([product.id])
-
promotion.refresh_from_db()
assert promotion.old_sale_id is None
+ for listing in listings:
+ assert listing.discounted_price_dirty is True
+
def test_promotion_rule_delete_events(
staff_api_client, permission_group_manage_discounts, catalogue_promotion
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 e962b0a7da..dbf0d75d47 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py
@@ -7,8 +7,10 @@ from django.test import override_settings
from .....discount import PromotionEvents, RewardValueType
from .....discount.error_codes import PromotionRuleUpdateErrorCode
from .....discount.models import PromotionEvent
+from .....product.models import ProductChannelListing
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import RewardTypeEnum, RewardValueTypeEnum
+from ...utils import get_variants_for_catalogue_predicate
PROMOTION_RULE_UPDATE_MUTATION = """
mutation promotionRuleUpdate($id: ID!, $input: PromotionRuleUpdateInput!) {
@@ -51,9 +53,7 @@ PROMOTION_RULE_UPDATE_MUTATION = """
@patch("saleor.plugins.manager.PluginsManager.promotion_rule_updated")
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_update_by_staff_user(
- update_discounted_prices_task_mock,
promotion_rule_updated_mock,
staff_api_client,
permission_group_manage_discounts,
@@ -125,6 +125,7 @@ def test_promotion_rule_update_by_staff_user(
content = get_graphql_content(response)
data = content["data"]["promotionRuleUpdate"]
rule_data = data["promotionRule"]
+ rule.refresh_from_db()
assert not data["errors"]
assert rule_data["name"] == rule.name
@@ -136,15 +137,14 @@ 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_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)
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product__in=[product_list[1], product_list[2]]
+ ):
+ assert listing.discounted_price_dirty is True
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_update_by_app(
- update_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
channel_USD,
@@ -182,9 +182,11 @@ def test_promotion_rule_update_by_app(
)
# then
+ product.refresh_from_db()
content = get_graphql_content(response)
data = content["data"]["promotionRuleUpdate"]
rule_data = data["promotionRule"]
+ rule.refresh_from_db()
assert not data["errors"]
assert rule_data["name"] == rule.name
@@ -196,12 +198,13 @@ 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_discounted_prices_task_mock.assert_called_once_with([product.id])
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product=product
+ ):
+ assert listing.discounted_price_dirty is True
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_update_by_customer(
- update_discounted_prices_task_mock,
api_client,
channel_USD,
channel_PLN,
@@ -232,7 +235,8 @@ def test_promotion_rule_update_by_customer(
# then
assert_no_permission(response)
- update_discounted_prices_task_mock.assert_not_called()
+ for variant in get_variants_for_catalogue_predicate(rule.catalogue_predicate):
+ assert variant.product.discounted_price_dirty is True
def test_promotion_rule_update_duplicates_channels_in_add_and_remove_field(
@@ -661,9 +665,7 @@ def test_promotion_rule_update_reward_value_invalid_percentage_value(
assert errors[0]["field"] == "rewardValue"
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_update_clears_old_sale_id(
- update_discounted_prices_task_mock,
staff_api_client,
permission_group_manage_discounts,
channel_USD,
@@ -736,6 +738,7 @@ def test_promotion_rule_update_clears_old_sale_id(
content = get_graphql_content(response)
data = content["data"]["promotionRuleUpdate"]
rule_data = data["promotionRule"]
+ rule.refresh_from_db()
assert not data["errors"]
assert rule_data["name"] == rule.name
@@ -746,13 +749,15 @@ 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_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()
assert promotion.old_sale_id is None
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product__in=[product_list[1], product_list[2]]
+ ):
+ assert listing.discounted_price_dirty is True
+
def test_promotion_rule_update_events(
staff_api_client,
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_update.py b/saleor/graphql/discount/tests/mutations/test_promotion_update.py
index d1b7f1c9f5..362ac6cfe9 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_update.py
@@ -38,13 +38,11 @@ PROMOTION_UPDATE_MUTATION = """
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_started")
@patch("saleor.plugins.manager.PluginsManager.promotion_updated")
def test_promotion_update_by_staff_user(
promotion_updated_mock,
promotion_started_mock,
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_group_manage_discounts,
catalogue_promotion,
@@ -89,19 +87,16 @@ def test_promotion_update_by_staff_user(
promotion_updated_mock.assert_called_once_with(promotion)
promotion_started_mock.assert_called_once_with(promotion)
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- promotion.id
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_ended")
@patch("saleor.plugins.manager.PluginsManager.promotion_updated")
def test_promotion_update_by_app(
promotion_updated_mock,
promotion_ended_mock,
- update_products_discounted_prices_of_promotion_task_mock,
app_api_client,
permission_manage_discounts,
catalogue_promotion,
@@ -145,13 +140,11 @@ def test_promotion_update_by_app(
promotion_updated_mock.assert_called_once_with(promotion)
promotion_ended_mock.assert_not_called()
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- promotion.id
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_started")
@patch("saleor.plugins.manager.PluginsManager.promotion_ended")
@patch("saleor.plugins.manager.PluginsManager.promotion_updated")
@@ -159,7 +152,6 @@ def test_promotion_update_dates_dont_change(
promotion_updated_mock,
promotion_started_mock,
promotion_ended_mock,
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_group_manage_discounts,
catalogue_promotion,
@@ -207,11 +199,11 @@ def test_promotion_update_dates_dont_change(
promotion_updated_mock.assert_called_once_with(promotion)
promotion_started_mock.assert_not_called()
promotion_ended_mock.assert_not_called()
- update_products_discounted_prices_of_promotion_task_mock.assert_not_called()
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is False
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_started")
@patch("saleor.plugins.manager.PluginsManager.promotion_ended")
@patch("saleor.plugins.manager.PluginsManager.promotion_updated")
@@ -219,7 +211,6 @@ def test_promotion_update_by_customer(
promotion_updated_mock,
promotion_started_mock,
promotion_ended_mock,
- update_products_discounted_prices_of_promotion_task_mock,
api_client,
catalogue_promotion,
):
@@ -247,7 +238,8 @@ def test_promotion_update_by_customer(
promotion_updated_mock.assert_not_called()
promotion_started_mock.assert_not_called()
promotion_ended_mock.assert_not_called()
- update_products_discounted_prices_of_promotion_task_mock.assert_not_called()
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is False
@freeze_time("2020-03-18 12:00:00")
@@ -287,13 +279,11 @@ def test_promotion_update_end_date_before_start_date(
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_started")
@patch("saleor.plugins.manager.PluginsManager.promotion_updated")
def test_promotion_update_clears_old_sale_id(
promotion_updated_mock,
promotion_started_mock,
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_group_manage_discounts,
promotion_converted_from_sale,
@@ -337,9 +327,8 @@ def test_promotion_update_clears_old_sale_id(
promotion_updated_mock.assert_called_once_with(promotion)
promotion_started_mock.assert_called_once_with(promotion)
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- promotion.id
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
def test_promotion_update_events(
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py b/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py
index 750c57d628..fc8e3705b3 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py
@@ -7,6 +7,7 @@ import pytest
from .....discount import RewardValueType
from .....discount.error_codes import DiscountErrorCode
from .....discount.models import Promotion, PromotionRule
+from .....product.models import ProductChannelListing, ProductVariant
from ....tests.utils import get_graphql_content
@@ -75,11 +76,7 @@ SALE_BULK_DELETE_MUTATION = """
@mock.patch("saleor.graphql.discount.mutations.bulk_mutations.get_webhooks_for_event")
@mock.patch("saleor.plugins.manager.PluginsManager.sale_deleted")
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_delete_sales(
- update_products_discounted_prices_for_promotion_task,
deleted_webhook_mock,
mocked_get_webhooks_for_event,
staff_api_client,
@@ -89,6 +86,18 @@ def test_delete_sales(
settings,
):
# given
+ rules_to_delete = PromotionRule.objects.filter(
+ promotion_id__in=[
+ promotion.id for promotion in promotion_converted_from_sale_list
+ ]
+ )
+ variant_ids = PromotionRule.variants.through.objects.filter(
+ promotionrule_id__in=rules_to_delete
+ ).values_list("productvariant_id", flat=True)
+ product_ids = ProductVariant.objects.filter(id__in=variant_ids).values_list(
+ "product_id", flat=True
+ )
+
promotion_list = promotion_converted_from_sale_list
mocked_get_webhooks_for_event.return_value = [any_webhook]
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
@@ -111,7 +120,11 @@ def test_delete_sales(
assert not Promotion.objects.filter(
id__in=[promotion.id for promotion in promotion_list]
).exists()
- update_products_discounted_prices_for_promotion_task.called_once()
+
+ assert not ProductChannelListing.objects.filter(
+ product_id__in=product_ids, discounted_price_dirty=False
+ ).exists()
+
assert deleted_webhook_mock.call_count == len(promotion_list)
@@ -211,11 +224,7 @@ def test_delete_sales_with_variants_triggers_webhook(
@mock.patch("saleor.graphql.discount.mutations.bulk_mutations.get_webhooks_for_event")
@mock.patch("saleor.plugins.manager.PluginsManager.sale_deleted")
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_delete_sales_with_promotion_ids(
- update_products_discounted_prices_for_promotion_task,
deleted_webhook_mock,
mocked_get_webhooks_for_event,
staff_api_client,
@@ -225,6 +234,18 @@ def test_delete_sales_with_promotion_ids(
settings,
):
# given
+ rules_to_delete = PromotionRule.objects.filter(
+ promotion_id__in=[
+ promotion.id for promotion in promotion_converted_from_sale_list
+ ]
+ )
+ variant_ids = PromotionRule.variants.through.objects.filter(
+ promotionrule_id__in=rules_to_delete
+ ).values_list("productvariant_id", flat=True)
+ product_ids = ProductVariant.objects.filter(id__in=variant_ids).values_list(
+ "product_id", flat=True
+ )
+
mocked_get_webhooks_for_event.return_value = [any_webhook]
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
variables = {
@@ -249,4 +270,6 @@ def test_delete_sales_with_promotion_ids(
assert errors[0]["code"] == DiscountErrorCode.INVALID.name
deleted_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task.assert_not_called()
+ assert not ProductChannelListing.objects.filter(
+ product_id__in=product_ids, discounted_price_dirty=True
+ ).exists()
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 48a5056865..ee74cebf85 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py
@@ -3,6 +3,7 @@ from unittest.mock import patch
import graphene
from .....discount.error_codes import DiscountErrorCode
+from .....product.models import ProductChannelListing
from ....tests.utils import get_graphql_content
from ...utils import convert_migrated_sale_predicate_to_catalogue_info
@@ -22,11 +23,9 @@ SALE_CATALOGUES_ADD_MUTATION = """
"""
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
category,
@@ -67,7 +66,8 @@ def test_sale_add_catalogues(
assert not content["data"]["saleCataloguesAdd"]["errors"]
assert content["data"]["saleCataloguesAdd"]["sale"]["name"] == promotion.name
promotion.refresh_from_db()
- predicate = promotion.rules.first().catalogue_predicate
+ rule = promotion.rules.first()
+ predicate = rule.catalogue_predicate
current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)
assert collection_id in current_catalogue["collections"]
@@ -78,14 +78,15 @@ def test_sale_add_catalogues(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_called_once()
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product=product
+ ):
+ assert listing.discounted_price_dirty is True
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -125,7 +126,8 @@ def test_sale_add_catalogues_no_changes_in_catalogue(
content = get_graphql_content(response)
assert not content["data"]["saleCataloguesAdd"]["errors"]
promotion.refresh_from_db()
- predicate = promotion.rules.first().catalogue_predicate
+ rule = promotion.rules.first()
+ predicate = rule.catalogue_predicate
current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)
assert collection_id in current_catalogue["collections"]
@@ -135,14 +137,15 @@ def test_sale_add_catalogues_no_changes_in_catalogue(
assert current_catalogue == previous_catalogue
updated_webhook_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_not_called()
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product=product
+ ):
+ assert listing.discounted_price_dirty is False
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -174,7 +177,8 @@ def test_sale_add_empty_catalogues(
content = get_graphql_content(response)
assert not content["data"]["saleCataloguesAdd"]["errors"]
promotion.refresh_from_db()
- predicate = promotion.rules.first().catalogue_predicate
+ rule = promotion.rules.first()
+ predicate = rule.catalogue_predicate
current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)
assert collection_id in current_catalogue["collections"]
@@ -183,14 +187,15 @@ def test_sale_add_empty_catalogues(
assert variant_id in current_catalogue["variants"]
updated_webhook_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_not_called()
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product=product
+ ):
+ assert listing.discounted_price_dirty is False
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
permission_manage_discounts,
@@ -222,14 +227,11 @@ def test_sale_add_empty_catalogues_to_sale_with_empty_catalogues(
assert not current_catalogue["variants"]
updated_webhook_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_not_called()
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -267,18 +269,20 @@ def test_sale_add_catalogues_no_product_ids_change(
content = get_graphql_content(response)
assert not content["data"]["saleCataloguesAdd"]["errors"]
promotion.refresh_from_db()
- predicate = promotion.rules.first().catalogue_predicate
+ rule = promotion.rules.first()
+ predicate = rule.catalogue_predicate
current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_not_called()
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product=product
+ ):
+ assert listing.discounted_price_dirty is False
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_sale_add_catalogues_with_product_without_variants(
- update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -290,6 +294,7 @@ def test_sale_add_catalogues_with_product_without_variants(
# given
query = SALE_CATALOGUES_ADD_MUTATION
promotion = promotion_converted_from_sale
+ rule = promotion.rules.first()
product.variants.all().delete()
product_id = graphene.Node.to_global_id("Product", product.id)
collection_id = graphene.Node.to_global_id("Collection", collection.id)
@@ -315,7 +320,10 @@ 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_discounted_prices_task_mock.assert_not_called()
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product=product
+ ):
+ assert listing.discounted_price_dirty is False
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 17e274bc03..2e70fad449 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py
@@ -3,6 +3,7 @@ from unittest.mock import patch
import graphene
from .....discount.error_codes import DiscountErrorCode
+from .....product.models import ProductChannelListing
from ....tests.utils import get_graphql_content
from ...utils import convert_migrated_sale_predicate_to_catalogue_info
@@ -22,11 +23,9 @@ SALE_CATALOGUES_REMOVE_MUTATION = """
"""
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -80,7 +79,8 @@ def test_sale_remove_catalogues(
assert not content["data"]["saleCataloguesRemove"]["errors"]
assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == promotion.name
promotion.refresh_from_db()
- predicate = promotion.rules.first().catalogue_predicate
+ rule = promotion.rules.first()
+ predicate = rule.catalogue_predicate
current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)
assert collection_id not in current_catalogue["collections"]
@@ -93,14 +93,15 @@ def test_sale_remove_catalogues(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_called_once()
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product=product
+ ):
+ assert listing.discounted_price_dirty is True
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -146,7 +147,8 @@ def test_sale_remove_empty_catalogues(
assert not content["data"]["saleCataloguesRemove"]["errors"]
assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == promotion.name
promotion.refresh_from_db()
- predicate = promotion.rules.first().catalogue_predicate
+ rule = promotion.rules.first()
+ predicate = rule.catalogue_predicate
current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)
assert current_catalogue == previous_catalogue
@@ -156,14 +158,15 @@ def test_sale_remove_empty_catalogues(
assert variant_id in current_catalogue["variants"]
updated_webhook_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_not_called()
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product=product
+ ):
+ assert listing.discounted_price_dirty is False
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
permission_manage_discounts,
@@ -201,14 +204,11 @@ def test_sale_remove_empty_catalogues_from_sale_with_empty_catalogues(
assert not current_catalogue["variants"]
updated_webhook_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_not_called()
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -241,7 +241,8 @@ def test_sale_remove_catalogues_no_product_changes(
assert not content["data"]["saleCataloguesRemove"]["errors"]
assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == promotion.name
promotion.refresh_from_db()
- predicate = promotion.rules.first().catalogue_predicate
+ rule = promotion.rules.first()
+ predicate = rule.catalogue_predicate
current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)
assert variant_id not in current_catalogue["variants"]
@@ -249,7 +250,10 @@ def test_sale_remove_catalogues_no_product_changes(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_not_called()
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=rule.channels.all(), product=variant.product
+ ):
+ assert listing.discounted_price_dirty is False
def test_sale_remove_catalogues_with_promotion_id(
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_channel_listing_update.py b/saleor/graphql/discount/tests/mutations/test_sale_channel_listing_update.py
index 9c3d7b72e9..4a92244054 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_channel_listing_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_channel_listing_update.py
@@ -1,5 +1,3 @@
-from unittest.mock import patch
-
import graphene
from .....discount import RewardValueType
@@ -32,12 +30,7 @@ mutation UpdateSaleChannelListing(
"""
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_add_channels(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -84,17 +77,11 @@ def test_sale_channel_listing_add_channels(
)
assert all([rule.old_channel_listing_id for rule in rules])
- mock_update_products_discounted_prices_of_promotion_task.delay.assert_called_once_with(
- promotion.pk
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_add_multiple_channels(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -145,17 +132,11 @@ def test_sale_channel_listing_add_multiple_channels(
assert all(old_channel_listing_ids)
assert len(set(old_channel_listing_ids)) == 3
- mock_update_products_discounted_prices_of_promotion_task.delay.assert_called_once_with(
- promotion.pk
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_update_channels(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -196,17 +177,11 @@ def test_sale_channel_listing_update_channels(
rules = promotion.rules.all()
assert len(rules) == 1
- mock_update_products_discounted_prices_of_promotion_task.delay.assert_called_once_with(
- promotion.pk
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_remove_channels(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale_with_many_channels,
permission_manage_discounts,
@@ -244,17 +219,11 @@ def test_sale_channel_listing_remove_channels(
rules = promotion.rules.all()
assert len(rules) == 1
- mock_update_products_discounted_prices_of_promotion_task.delay.assert_called_once_with(
- promotion.pk
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_remove_all_channels(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale_with_many_channels,
permission_manage_discounts,
@@ -300,17 +269,11 @@ def test_sale_channel_listing_remove_all_channels(
assert rules[0].reward_value_type == reward_value_type
assert rules[0].catalogue_predicate == predicate
- mock_update_products_discounted_prices_of_promotion_task.delay.assert_called_once_with(
- promotion.pk
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_add_update_remove_channels(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale_with_many_channels,
permission_manage_discounts,
@@ -365,9 +328,8 @@ def test_sale_channel_listing_add_update_remove_channels(
for rule in rules:
assert len(rule.channels.all()) == 1
- mock_update_products_discounted_prices_of_promotion_task.delay.assert_called_once_with(
- promotion.pk
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
def test_sale_channel_listing_update_with_negative_discounted_value(
@@ -402,12 +364,7 @@ def test_sale_channel_listing_update_with_negative_discounted_value(
assert_negative_positive_decimal_value(response)
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_update_duplicated_ids_in_add_and_remove(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -441,15 +398,12 @@ def test_sale_channel_listing_update_duplicated_ids_in_add_and_remove(
assert errors[0]["field"] == "input"
assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.name
assert errors[0]["channels"] == [channel_id]
- mock_update_products_discounted_prices_of_promotion_task.assert_not_called()
+
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is False
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_update_duplicated_channel_in_add(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -485,15 +439,11 @@ def test_sale_channel_listing_update_duplicated_channel_in_add(
assert errors[0]["field"] == "addChannels"
assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.name
assert errors[0]["channels"] == [channel_id]
- mock_update_products_discounted_prices_of_promotion_task.assert_not_called()
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is False
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_update_duplicated_channel_in_remove(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -523,15 +473,11 @@ def test_sale_channel_listing_update_duplicated_channel_in_remove(
assert errors[0]["field"] == "removeChannels"
assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.name
assert errors[0]["channels"] == [channel_id]
- mock_update_products_discounted_prices_of_promotion_task.assert_not_called()
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is False
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_update_with_invalid_decimal_places(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -564,15 +510,11 @@ def test_sale_channel_listing_update_with_invalid_decimal_places(
assert errors[0]["code"] == DiscountErrorCode.INVALID.name
assert errors[0]["field"] == "input"
assert errors[0]["channels"] == [channel_id]
- mock_update_products_discounted_prices_of_promotion_task.assert_not_called()
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is False
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_update_with_invalid_percentage_value(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -608,7 +550,8 @@ def test_sale_channel_listing_update_with_invalid_percentage_value(
assert errors[0]["code"] == DiscountErrorCode.INVALID.name
assert errors[0]["field"] == "input"
assert errors[0]["channels"] == [channel_id]
- mock_update_products_discounted_prices_of_promotion_task.assert_not_called()
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is False
SALE_AND_SALE_CHANNEL_LISTING_UPDATE_MUTATION = """
@@ -644,12 +587,7 @@ mutation UpdateSaleChannelListing(
"""
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_invalidate_data_sale_channel_listings_update(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -706,17 +644,11 @@ def test_invalidate_data_sale_channel_listings_update(
# response from the second mutation contains data
assert channel_listings_data["channelListings"][0]["channel"]["id"] == channel_id
- mock_update_products_discounted_prices_of_promotion_task.delay.assert_called_once_with(
- promotion.pk,
- )
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_channel_listing_update"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_channel_listing_remove_all_channels_multiple_times(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -736,7 +668,6 @@ def test_sale_channel_listing_remove_all_channels_multiple_times(
discounted = 2
staff_api_client.user.user_permissions.add(permission_manage_discounts)
query = SALE_CHANNEL_LISTING_UPDATE_MUTATION
- mock_update_products_discounted_prices_of_promotion_task.return_value = None
variables_add = {
"id": sale_id,
@@ -764,6 +695,9 @@ def test_sale_channel_listing_remove_all_channels_multiple_times(
assert len(rules) == 1
assert not rules[0].channels.first()
+ for rule in promotion.rules.all():
+ assert rule.variants_dirty is True
+
def test_sale_channel_listing_update_not_found_error(
staff_api_client,
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_create.py b/saleor/graphql/discount/tests/mutations/test_sale_create.py
index 0b37554043..895a1f280e 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_create.py
@@ -40,13 +40,11 @@ SALE_CREATE_MUTATION = """
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_created")
def test_create_sale(
created_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_manage_discounts,
product_list,
@@ -100,19 +98,17 @@ def test_create_sale(
)
created_webhook_mock.assert_called_once_with(sale, current_catalogue)
sale_toggle_mock.assert_called_once_with(sale, current_catalogue)
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- sale.id
- )
+
+ for rule in sale.rules.all():
+ assert rule.variants_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_created")
def test_create_sale_only_start_date(
created_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_manage_discounts,
product_list,
@@ -154,14 +150,11 @@ def test_create_sale_only_start_date(
)
created_webhook_mock.assert_called_once_with(sale, current_catalogue)
sale_toggle_mock.assert_called_once_with(sale, current_catalogue)
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- sale.id
- )
+ for rule in sale.rules.all():
+ assert rule.variants_dirty is True
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
def test_create_sale_with_end_date_before_startdate(
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_manage_discounts,
):
@@ -190,16 +183,13 @@ def test_create_sale_with_end_date_before_startdate(
assert len(errors) == 1
assert errors[0]["field"] == "endDate"
assert errors[0]["code"] == DiscountErrorCode.INVALID.name
- update_products_discounted_prices_of_promotion_task_mock.assert_not_called()
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_created")
def test_create_sale_start_date_and_end_date_before_current_date(
created_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_manage_discounts,
product_list,
@@ -243,18 +233,15 @@ def test_create_sale_start_date_and_end_date_before_current_date(
)
created_webhook_mock.assert_called_once_with(sale, current_catalogue)
sale_toggle_mock.assert_not_called()
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- sale.id
- )
+ for rule in sale.rules.all():
+ assert rule.variants_dirty is True
-@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
@patch("saleor.plugins.manager.PluginsManager.sale_created")
def test_create_sale_start_date_and_end_date_after_current_date(
created_webhook_mock,
sale_toggle_mock,
- update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_manage_discounts,
product_list,
@@ -298,9 +285,8 @@ def test_create_sale_start_date_and_end_date_after_current_date(
)
created_webhook_mock.assert_called_once_with(sale, current_catalogue)
sale_toggle_mock.assert_not_called()
- update_products_discounted_prices_of_promotion_task_mock.assert_called_once_with(
- sale.id
- )
+ for rule in sale.rules.all():
+ assert rule.variants_dirty is True
@freeze_time("2020-03-18 12:00:00")
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_delete.py b/saleor/graphql/discount/tests/mutations/test_sale_delete.py
index 582abad692..d893cd8b86 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_delete.py
@@ -5,8 +5,12 @@ import pytest
from .....discount.error_codes import DiscountErrorCode
from .....discount.models import Promotion, PromotionRule
+from .....product.models import ProductChannelListing
from ....tests.utils import get_graphql_content
-from ...utils import convert_migrated_sale_predicate_to_catalogue_info
+from ...utils import (
+ convert_migrated_sale_predicate_to_catalogue_info,
+ get_variants_for_promotion,
+)
SALE_DELETE_MUTATION = """
mutation DeleteSale($id: ID!) {
@@ -25,11 +29,9 @@ SALE_DELETE_MUTATION = """
"""
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -38,10 +40,14 @@ def test_sale_delete_mutation(
# given
query = SALE_DELETE_MUTATION
promotion = promotion_converted_from_sale
+ channels = (
+ PromotionRule.objects.filter(promotion_id=promotion.id).first().channels.all()
+ )
previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(
catalogue_predicate
)
variables = {"id": graphene.Node.to_global_id("Sale", promotion.old_sale_id)}
+ variants = get_variants_for_promotion(promotion)
# when
response = staff_api_client.post_graphql(
@@ -61,7 +67,12 @@ def test_sale_delete_mutation(
promotion.refresh_from_db()
deleted_webhook_mock.assert_called_once_with(promotion, previous_catalogue)
- update_discounted_prices_task_mock.assert_called_once()
+
+ for listing in ProductChannelListing.objects.filter(
+ channel__in=channels,
+ product__in=[variant.product for variant in variants.select_related("product")],
+ ):
+ assert listing.discounted_price_dirty is True
@patch("saleor.product.tasks.update_discounted_prices_task.delay")
diff --git a/saleor/graphql/discount/tests/mutations/test_sale_update.py b/saleor/graphql/discount/tests/mutations/test_sale_update.py
index 2e2548176a..2d2c6d2632 100644
--- a/saleor/graphql/discount/tests/mutations/test_sale_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_sale_update.py
@@ -5,11 +5,16 @@ import graphene
from django.utils import timezone
from freezegun import freeze_time
-from .....discount import RewardValueType
from .....discount.error_codes import DiscountErrorCode
+from .....discount.models import PromotionRule, RewardValueType
+from .....product.models import ProductChannelListing
from ....tests.utils import get_graphql_content
from ...enums import DiscountValueTypeEnum
-from ...utils import convert_migrated_sale_predicate_to_catalogue_info
+from ...utils import (
+ convert_migrated_sale_predicate_to_catalogue_info,
+ get_products_for_promotion,
+ get_variants_for_catalogue_predicate,
+)
SALE_UPDATE_MUTATION = """
mutation saleUpdate($id: ID!, $input: SaleInput!) {
@@ -30,11 +35,9 @@ SALE_UPDATE_MUTATION = """
"""
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.plugins.manager.PluginsManager.sale_updated")
def test_update_sale(
updated_webhook_mock,
- update_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -86,14 +89,25 @@ def test_update_sale(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_called_once()
+ variants = get_variants_for_catalogue_predicate(
+ rule.catalogue_predicate
+ ).select_related("product")
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids,
+ product__in=[variant.product for variant in variants],
+ ):
+ assert listing.discounted_price_dirty is True
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -134,17 +148,27 @@ def test_update_sale_name(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_not_called()
+ product_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=product_ids
+ ):
+ assert listing.discounted_price_dirty is False
@freeze_time("2020-03-18 12:00:00")
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -187,17 +211,27 @@ def test_update_sale_start_date_after_current_date_notification_not_sent(
promotion, previous_catalogue, current_catalogue
)
sale_toggle_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_called_once()
+ product_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=product_ids
+ ):
+ assert listing.discounted_price_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -244,17 +278,27 @@ def test_update_sale_start_date_before_current_date_notification_already_sent(
promotion, previous_catalogue, current_catalogue
)
sale_toggle_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_called_once()
+ product_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=product_ids
+ ):
+ assert listing.discounted_price_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -298,17 +342,27 @@ def test_update_sale_start_date_before_current_date_notification_sent(
)
sale_toggle_mock.assert_called_once_with(promotion, current_catalogue)
- update_discounted_prices_task_mock.assert_called_once()
+ product_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=product_ids
+ ):
+ assert listing.discounted_price_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -352,17 +406,27 @@ def test_update_sale_end_date_after_current_date_notification_not_sent(
promotion, previous_catalogue, current_catalogue
)
sale_toggle_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_called_once()
+ product_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=product_ids
+ ):
+ assert listing.discounted_price_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -408,17 +472,27 @@ 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_discounted_prices_task_mock.assert_called_once()
+ product_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=product_ids
+ ):
+ assert listing.discounted_price_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -462,14 +536,24 @@ 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_discounted_prices_task_mock.assert_called_once()
+ products_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=products_ids
+ ):
+ assert listing.discounted_price_dirty is True
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -509,14 +593,13 @@ def test_update_sale_categories(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_called_once()
+ for product in get_products_for_promotion(promotion):
+ assert product.discounted_price_dirty is True
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -558,14 +641,13 @@ def test_update_sale_collections(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_called_once()
+ for product in get_products_for_promotion(promotion):
+ assert product.discounted_price_dirty is True
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -607,14 +689,24 @@ def test_update_sale_variants(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_called_once()
+ products_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=products_ids
+ ):
+ assert listing.discounted_price_dirty is True
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
catalogue_predicate,
@@ -654,17 +746,27 @@ def test_update_sale_products(
updated_webhook_mock.assert_called_once_with(
promotion, previous_catalogue, current_catalogue
)
- update_discounted_prices_task_mock.assert_called_once()
+ products_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=products_ids
+ ):
+ assert listing.discounted_price_dirty is True
@freeze_time("2020-03-18 12:00:00")
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -696,7 +798,20 @@ 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_discounted_prices_task_mock.assert_not_called()
+
+ products_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=products_ids
+ ):
+ assert listing.discounted_price_dirty is False
@freeze_time("2020-03-18 12:00:00")
@@ -755,13 +870,11 @@ def test_update_sale_with_none_values(
assert not rule.catalogue_predicate
-@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_discounted_prices_task_mock,
staff_api_client,
promotion_converted_from_sale,
permission_manage_discounts,
@@ -794,7 +907,20 @@ def test_update_sale_with_promotion_id(
)
updated_webhook_mock.assert_not_called()
sale_toggle_mock.assert_not_called()
- update_discounted_prices_task_mock.assert_not_called()
+
+ products_ids = list(
+ get_products_for_promotion(promotion).values_list("id", flat=True)
+ )
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ channel_id__in=channel_ids, product_id__in=products_ids
+ ):
+ assert listing.discounted_price_dirty is False
def test_update_sale_not_found_error(staff_api_client, permission_manage_discounts):
diff --git a/saleor/graphql/discount/tests/test_utils.py b/saleor/graphql/discount/tests/test_utils.py
index 851aeef70d..ec19355a16 100644
--- a/saleor/graphql/discount/tests/test_utils.py
+++ b/saleor/graphql/discount/tests/test_utils.py
@@ -1,9 +1,11 @@
from decimal import Decimal
import graphene
+import pytest
-from ....discount import RewardValueType
+from ....discount import PromotionType, RewardValueType
from ....discount.models import Promotion, PromotionRule
+from ..mutations.utils import promotion_rule_should_be_marked_with_dirty_variants
from ..utils import (
_predicate_to_snake_case,
convert_migrated_sale_predicate_to_catalogue_info,
@@ -422,3 +424,59 @@ def test_predicate_to_snake_case():
},
]
}
+
+
+ ("field", "field_value", "expected_result"),
+ [
+ ("reward_value", None, False),
+ ("reward_value", 0, False),
+ ("reward_value", 1, True),
+ ("catalogue_predicate", {}, False),
+ ("reward_value_type", None, False),
+ ("reward_value_type", "fixed", True),
+ ],
+)
+def test_promotion_rule_should_be_marked_with_dirty_variants(
+ field, field_value, expected_result, promotion_rule
+):
+ # given
+ setattr(promotion_rule, field, field_value)
+
+ # when
+ result = promotion_rule_should_be_marked_with_dirty_variants(
+ promotion_rule, PromotionType.CATALOGUE, promotion_rule.channels.all()
+ )
+
+ # then
+ assert result == expected_result
+
+
+def test_promotion_rule_should_be_marked_with_dirty_variants_incorrect_promotion_type(
+ promotion_rule,
+):
+ # given
+ promotion_type = PromotionType.ORDER
+
+ # when
+ result = promotion_rule_should_be_marked_with_dirty_variants(
+ promotion_rule, promotion_type, promotion_rule.channels.all()
+ )
+
+ # then
+ assert not result
+
+
+def test_promotion_rule_should_be_marked_with_dirty_variants_missing_channels(
+ promotion_rule,
+):
+ # given
+ promotion_rule.channels.set([])
+
+ # when
+ result = promotion_rule_should_be_marked_with_dirty_variants(
+ promotion_rule, PromotionType.CATALOGUE, promotion_rule.channels.all()
+ )
+
+ # then
+ assert not result
diff --git a/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py b/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py
index 8b2f02d12c..679530702e 100644
--- a/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py
+++ b/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py
@@ -1,9 +1,10 @@
import graphene
from django.db.models import Exists, OuterRef
+from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from ....permission.enums import ProductPermissions
from ....product import models
-from ....product.tasks import update_products_discounted_prices_for_promotion_task
+from ....product.models import ProductChannelListing
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...core.mutations import ModelBulkDeleteMutation
@@ -47,6 +48,9 @@ class CollectionBulkDelete(ModelBulkDeleteMutation):
for product in products:
cls.call_event(manager.product_updated, product, webhooks=webhooks)
- update_products_discounted_prices_for_promotion_task.delay(
- [product.id for product in products]
+ channel_ids = set(
+ ProductChannelListing.objects.filter(
+ Exists(collection_products.filter(product_id=OuterRef("product_id")))
+ ).values_list("channel_id", flat=True)
)
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index 2824504bfb..2b802cea62 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -15,11 +15,11 @@ from ....core.tracing import traced_atomic_transaction
from ....core.utils import prepare_unique_slug
from ....core.utils.editorjs import clean_editor_js
from ....core.utils.validators import get_oembed_data
+from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from ....permission.enums import ProductPermissions
from ....product import ProductMediaTypes, models
from ....product.error_codes import ProductBulkCreateErrorCode
from ....product.models import CollectionProduct
-from ....product.tasks import update_products_discounted_prices_for_promotion_task
from ....thumbnail.utils import get_filename_from_url
from ....warehouse.models import Warehouse
from ....webhook.event_types import WebhookEventAsyncType
@@ -879,13 +879,9 @@ class ProductBulkCreate(BaseMutation):
for variant in variants:
cls.call_event(manager.product_variant_created, variant, webhooks=webhooks)
- webhooks = get_webhooks_for_event(WebhookEventAsyncType.CHANNEL_UPDATED)
- for channel in channels:
- cls.call_event(manager.channel_updated, channel, webhooks=webhooks)
-
- cls.call_event(
- update_products_discounted_prices_for_promotion_task.delay, product_ids
- )
+ if products:
+ channel_ids = set([channel.id for channel in channels])
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
@classmethod
@traced_atomic_transaction()
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
index 7a23310a26..7059127152 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
@@ -9,10 +9,10 @@ from graphene.utils.str_converters import to_camel_case
from ....attribute import AttributeType
from ....core.tracing import traced_atomic_transaction
+from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from ....permission.enums import ProductPermissions
from ....product import models
from ....product.error_codes import ProductVariantBulkErrorCode
-from ....product.tasks import update_products_discounted_prices_for_promotion_task
from ....warehouse import models as warehouse_models
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
@@ -917,10 +917,15 @@ class ProductVariantBulkCreate(BaseMutation):
@classmethod
def post_save_actions(cls, info, instances, product):
- # Recalculate the "discounted price" for the parent product
- cls.call_event(
- update_products_discounted_prices_for_promotion_task.delay, [product.pk]
+ variant_ids = set([instance.node.id for instance in instances])
+ channel_ids = set(
+ models.ProductVariantChannelListing.objects.filter(
+ variant_id__in=variant_ids
+ ).values_list("channel_id", flat=True)
)
+ # This will finally recalculate discounted prices for products.
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
+
product.search_index_dirty = True
product.save(update_fields=["search_index_dirty"])
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
index df97c139ce..60a3e434f0 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
@@ -10,13 +10,13 @@ from ....attribute import AttributeInputType
from ....attribute import models as attribute_models
from ....core.postgres import FlatConcatSearchVector
from ....core.tracing import traced_atomic_transaction
+from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from ....order import events as order_events
from ....order import models as order_models
from ....order.tasks import recalculate_orders_task
from ....permission.enums import ProductPermissions
from ....product import models
from ....product.search import prepare_product_search_vector_value
-from ....product.tasks import update_products_discounted_prices_for_promotion_task
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...app.dataloaders import get_app_promise
@@ -51,6 +51,24 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
error_type_class = ProductError
error_type_field = "product_errors"
+ @classmethod
+ def post_save_actions(cls, info, variants):
+ impacted_channels = set()
+ for variant in variants:
+ channel_ids = [
+ listing.channel_id for listing in variant.channel_listings.all()
+ ]
+ impacted_channels.update(channel_ids)
+ # This will finally recalculate discounted prices for products.
+ cls.call_event(
+ mark_active_catalogue_promotion_rules_as_dirty, impacted_channels
+ )
+
+ manager = get_plugin_manager_promise(info.context).get()
+ webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_DELETED)
+ for variant in variants:
+ cls.call_event(manager.product_variant_deleted, variant, webhooks=webhooks)
+
@classmethod
@traced_atomic_transaction()
def perform_mutation(cls, _root, info: ResolveInfo, /, ids=None, skus=None, **data):
@@ -87,10 +105,6 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
cls.delete_assigned_attribute_values(pks)
cls.delete_product_channel_listings_without_available_variants(product_pks, pks)
response = super().perform_mutation(_root, info, ids=ids, **data)
- manager = get_plugin_manager_promise(info.context).get()
- webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_DELETED)
- for variant in variants:
- cls.call_event(manager.product_variant_deleted, variant, webhooks=webhooks)
# delete order lines for deleted variants
order_models.OrderLine.objects.filter(
@@ -125,11 +139,7 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
]
)
- # Recalculate the "discounted price" for the related products
- cls.call_event(
- update_products_discounted_prices_for_promotion_task.delay, product_pks
- )
-
+ cls.post_save_actions(info, variants)
return response
@staticmethod
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
index cd63d631a6..c527059ccc 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
@@ -8,10 +8,10 @@ from django.utils import timezone
from graphene.utils.str_converters import to_camel_case
from ....core.tracing import traced_atomic_transaction
+from ....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from ....permission.enums import ProductPermissions
from ....product import models
from ....product.error_codes import ProductErrorCode, ProductVariantBulkErrorCode
-from ....product.tasks import update_products_discounted_prices_for_promotion_task
from ....warehouse import models as warehouse_models
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
@@ -700,14 +700,20 @@ class ProductVariantBulkUpdate(BaseMutation):
@classmethod
def post_save_actions(
- cls, info, instances, product, webhooks, pre_save_payloads, request_time
+ cls,
+ info,
+ instances,
+ product,
+ webhooks,
+ pre_save_payloads,
+ request_time,
+ impacted_channel_ids,
):
+ if impacted_channel_ids:
+ cls.call_event(
+ mark_active_catalogue_promotion_rules_as_dirty, impacted_channel_ids
+ )
manager = get_plugin_manager_promise(info.context).get()
-
- # Recalculate the "discounted price" for the parent product
- cls.call_event(
- update_products_discounted_prices_for_promotion_task.delay, [product.pk]
- )
product.search_index_dirty = True
product.save(update_fields=["search_index_dirty"])
@@ -720,6 +726,42 @@ class ProductVariantBulkUpdate(BaseMutation):
request_time=request_time,
)
+ @classmethod
+ def _get_impacted_channels(cls, cleaned_inputs_map):
+ impacted_channel_ids = set()
+ channel_listing_ids_to_remove = set()
+ for cleaned_input in cleaned_inputs_map.values():
+ if not cleaned_input:
+ continue
+ if not cleaned_input.get("channel_listings"):
+ continue
+ if created_channels := cleaned_input["channel_listings"].get("create"):
+ impacted_channel_ids.update(
+ [channel["channel"].id for channel in created_channels]
+ )
+ if updated_channels := cleaned_input["channel_listings"].get("update"):
+ impacted_channel_ids.update(
+ [
+ channel["channel_listings"].channel_id
+ for channel in updated_channels
+ ]
+ )
+
+ if removed_channel_listings := cleaned_input["channel_listings"].get(
+ "remove"
+ ):
+ channel_listing_ids_to_remove.update(removed_channel_listings)
+
+ if channel_listing_ids_to_remove:
+ impacted_channel_ids.update(
+ list(
+ models.ProductVariantChannelListing.objects.filter(
+ id__in=channel_listing_ids_to_remove
+ ).values_list("channel_id", flat=True)
+ )
+ )
+ return impacted_channel_ids
+
@classmethod
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
@@ -744,6 +786,7 @@ class ProductVariantBulkUpdate(BaseMutation):
variants_global_id_to_instance_map,
index_error_map,
)
+ impacted_channel_ids = cls._get_impacted_channels(cleaned_inputs_map)
webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED)
pre_save_payloads = cls.generate_pre_save_payloads(
@@ -774,7 +817,13 @@ class ProductVariantBulkUpdate(BaseMutation):
result.product_variant for result in results if result.product_variant
]
cls.post_save_actions(
- info, instances, product, webhooks, pre_save_payloads, request_time
+ info,
+ instances,
+ product,
+ webhooks,
+ pre_save_payloads,
+ request_time,
+ impacted_channel_ids,
)
return ProductVariantBulkCreate(count=len(instances), results=results)
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 8e535e1351..8d0d0d3739 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -1339,6 +1339,9 @@ class CollectionFilter(MetadataFilterBase):
class CollectionWhere(MetadataWhereFilterBase):
ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("Collection"))
+ # Collection where filter is also used in promotion logic. In case of extending it
+ # the collection update mutation should also be modified to recalculate the prices
+ # for new added field.
class Meta:
model = Collection
@@ -1374,6 +1377,9 @@ class CategoryFilter(MetadataFilterBase):
class CategoryWhere(MetadataWhereFilterBase):
ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("Category"))
+ # Category where filter is also used in promotion logic. In case of extending it
+ # the category update mutation should also be modified to recalculate the prices
+ # for new added field.
class Meta:
model = Category
diff --git a/saleor/graphql/product/mutations/category/category_update.py b/saleor/graphql/product/mutations/category/category_update.py
index 12068bb487..7a2316d444 100644
--- a/saleor/graphql/product/mutations/category/category_update.py
+++ b/saleor/graphql/product/mutations/category/category_update.py
@@ -1,5 +1,7 @@
import graphene
+from django.db.models import Exists, OuterRef
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
from .....thumbnail import models as thumbnail_models
@@ -36,6 +38,15 @@ class CategoryUpdate(CategoryCreate):
return super().construct_instance(instance, cleaned_data)
@classmethod
- def post_save_action(cls, info: ResolveInfo, instance, _cleaned_input):
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.category_updated, instance)
+
+ if "metadata" in cleaned_input:
+ products = models.Product.objects.filter(category_id=instance.id)
+ channel_ids = set(
+ models.ProductChannelListing.objects.filter(
+ Exists(products.filter(id=OuterRef("product_id")))
+ ).values_list("channel_id", flat=True)
+ )
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index 415356e969..884125c1d0 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_discounted_prices_task
+from ....product.utils.product import mark_products_in_channels_as_dirty
from ...channel import ChannelContext
from ...channel.mutations import BaseChannelListingMutation
from ...channel.types import Channel
@@ -355,10 +355,23 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
with traced_atomic_transaction():
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_discounted_prices_task.delay([product.id])
- manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.product_updated, product)
+
+ @classmethod
+ def post_save_actions(
+ cls, info: ResolveInfo, product: "ProductModel", cleaned_input: dict
+ ):
+ modified_channel_ids = [
+ update_channel["channel"].id
+ for update_channel in cleaned_input.get("update_channels", [])
+ ]
+ modified_channel_ids.extend(cleaned_input.get("remove_channels", []))
+ cls.call_event(
+ mark_products_in_channels_as_dirty,
+ {channel_id: {product.pk} for channel_id in modified_channel_ids},
+ )
+ product = ProductModel.objects.prefetched_for_webhook().get(pk=product.pk)
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.product_updated, product)
@classmethod
def perform_mutation( # type: ignore[override]
@@ -385,6 +398,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
raise ValidationError(errors)
cls.save(info, product, cleaned_input)
+ cls.post_save_actions(info, product, cleaned_input)
return ProductChannelListingUpdate(
product=ChannelContext(node=product, channel_slug=None)
)
@@ -541,9 +555,20 @@ class ProductVariantChannelListingUpdate(BaseMutation):
channel=channel,
defaults=defaults,
)
- update_discounted_prices_task.delay([variant.product_id])
- manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.product_variant_updated, variant)
+
+ @classmethod
+ def post_save_actions(
+ cls, info, variant: "ProductVariantModel", cleaned_input: list[dict]
+ ):
+ channel_ids = [
+ channel_listing_data["channel"].id for channel_listing_data in cleaned_input
+ ]
+ cls.call_event(
+ mark_products_in_channels_as_dirty,
+ {channel_id: {variant.product_id} for channel_id in channel_ids},
+ )
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.product_variant_updated, variant)
@classmethod
def perform_mutation( # type: ignore[override]
@@ -577,7 +602,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
raise ValidationError(errors)
cls.save(info, variant, cleaned_input)
-
+ cls.post_save_actions(info, variant, cleaned_input)
return ProductVariantChannelListingUpdate(
variant=ChannelContext(node=variant, channel_slug=None)
)
diff --git a/saleor/graphql/product/mutations/collection/collection_add_products.py b/saleor/graphql/product/mutations/collection/collection_add_products.py
index eb59fc2884..81b08983a4 100644
--- a/saleor/graphql/product/mutations/collection/collection_add_products.py
+++ b/saleor/graphql/product/mutations/collection/collection_add_products.py
@@ -2,10 +2,10 @@ import graphene
from django.core.exceptions import ValidationError
from .....core.tracing import traced_atomic_transaction
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
from .....product.error_codes import CollectionErrorCode
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
from .....product.utils import get_products_ids_without_variants
from ....channel import ChannelContext
from ....core import ResolveInfo
@@ -53,14 +53,16 @@ class CollectionAddProducts(BaseMutation):
manager = get_plugin_manager_promise(info.context).get()
with traced_atomic_transaction():
collection.products.add(*products)
- # Updated the db entries, recalculating discounts of affected products
- cls.call_event(
- update_products_discounted_prices_for_promotion_task.delay,
- [pq.pk for pq in products],
- )
for product in products:
cls.call_event(manager.product_updated, product)
+ if products:
+ channel_ids = models.ProductChannelListing.objects.filter(
+ product_id__in=[product.id for product in products]
+ ).values_list("channel_id", flat=True)
+ # This will finally recalculate discounted prices for products.
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
+
return CollectionAddProducts(
collection=ChannelContext(node=collection, channel_slug=None)
)
diff --git a/saleor/graphql/product/mutations/collection/collection_create.py b/saleor/graphql/product/mutations/collection/collection_create.py
index 348229fee7..46ad21f627 100644
--- a/saleor/graphql/product/mutations/collection/collection_create.py
+++ b/saleor/graphql/product/mutations/collection/collection_create.py
@@ -5,6 +5,7 @@ import pytz
from django.core.exceptions import ValidationError
from .....core.utils.date_time import convert_to_utc_date_time
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
from .....product.error_codes import CollectionErrorCode
@@ -131,6 +132,12 @@ class CollectionCreate(ModelMutation):
for ids_batch in cls.batch_product_ids(product_ids):
collection_product_updated_task.delay(ids_batch)
+ if product_ids:
+ channel_ids = models.ProductChannelListing.objects.filter(
+ product_id__in=product_ids
+ ).values_list("channel_id", flat=True)
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
+
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **kwargs):
result = super().perform_mutation(_root, info, **kwargs)
diff --git a/saleor/graphql/product/mutations/collection/collection_delete.py b/saleor/graphql/product/mutations/collection/collection_delete.py
index f987dcda41..94244b99cd 100644
--- a/saleor/graphql/product/mutations/collection/collection_delete.py
+++ b/saleor/graphql/product/mutations/collection/collection_delete.py
@@ -1,11 +1,9 @@
import graphene
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
-from .....product.tasks import (
- collection_product_updated_task,
- update_products_discounted_prices_for_promotion_task,
-)
+from .....product.tasks import collection_product_updated_task
from ....channel import ChannelContext
from ....core import ResolveInfo
from ....core.mutations import ModelDeleteMutation
@@ -49,7 +47,14 @@ class CollectionDelete(ModelDeleteMutation):
for ids_batch in cls.batch_product_ids(product_ids):
collection_product_updated_task.delay(ids_batch)
- update_products_discounted_prices_for_promotion_task.delay(product_ids)
+
+ if product_ids:
+ channel_ids = set(
+ models.ProductChannelListing.objects.filter(
+ product_id__in=product_ids
+ ).values_list("channel_id", flat=True)
+ )
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
return CollectionDelete(
collection=ChannelContext(node=result.collection, channel_slug=None)
diff --git a/saleor/graphql/product/mutations/collection/collection_remove_products.py b/saleor/graphql/product/mutations/collection/collection_remove_products.py
index c585106541..0cc52d567c 100644
--- a/saleor/graphql/product/mutations/collection/collection_remove_products.py
+++ b/saleor/graphql/product/mutations/collection/collection_remove_products.py
@@ -1,8 +1,8 @@
import graphene
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
from ....channel import ChannelContext
from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_PRODUCTS
@@ -49,10 +49,14 @@ class CollectionRemoveProducts(BaseMutation):
manager = get_plugin_manager_promise(info.context).get()
for product in products:
cls.call_event(manager.product_updated, product)
- # Updated the db entries, recalculating discounts of affected products
- update_products_discounted_prices_for_promotion_task.delay(
- [p.pk for p in products]
- )
+
+ if products:
+ channel_ids = models.ProductChannelListing.objects.filter(
+ product__in=products
+ ).values_list("channel_id", flat=True)
+ # This will finally recalculate discounted prices for products.
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
+
return CollectionRemoveProducts(
collection=ChannelContext(node=collection, channel_slug=None)
)
diff --git a/saleor/graphql/product/mutations/collection/collection_update.py b/saleor/graphql/product/mutations/collection/collection_update.py
index 4915f8f9d7..24358ba34f 100644
--- a/saleor/graphql/product/mutations/collection/collection_update.py
+++ b/saleor/graphql/product/mutations/collection/collection_update.py
@@ -1,5 +1,7 @@
import graphene
+from django.db.models import Exists, OuterRef
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
from .....thumbnail import models as thumbnail_models
@@ -42,3 +44,16 @@ class CollectionUpdate(CollectionCreate):
"""Override this method with `pass` to avoid triggering product webhook."""
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.collection_updated, instance)
+
+ if "metadata" in cleaned_input:
+ collection_products = models.CollectionProduct.objects.filter(
+ collection_id=instance.id
+ )
+ channel_ids = set(
+ models.ProductChannelListing.objects.filter(
+ Exists(
+ collection_products.filter(product_id=OuterRef("product_id"))
+ )
+ ).values_list("channel_id", flat=True)
+ )
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
diff --git a/saleor/graphql/product/mutations/product/product_create.py b/saleor/graphql/product/mutations/product/product_create.py
index 6a360abd28..518c611fb3 100644
--- a/saleor/graphql/product/mutations/product/product_create.py
+++ b/saleor/graphql/product/mutations/product/product_create.py
@@ -7,7 +7,6 @@ from .....core.utils.editorjs import clean_editor_js
from .....permission.enums import ProductPermissions
from .....product import models
from .....product.error_codes import ProductErrorCode
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
from ....attribute.types import AttributeValueInput
from ....attribute.utils import AttrValuesInput, ProductAttributeAssignmentMixin
from ....channel import ChannelContext
@@ -220,7 +219,6 @@ class ProductCreate(ModelMutation):
@classmethod
def post_save_action(cls, info: ResolveInfo, instance, _cleaned_input):
product = models.Product.objects.prefetched_for_webhook().get(pk=instance.pk)
- update_products_discounted_prices_for_promotion_task.delay([instance.id])
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.product_created, product)
diff --git a/saleor/graphql/product/mutations/product/product_update.py b/saleor/graphql/product/mutations/product/product_update.py
index 5f74a8a90b..d53134e147 100644
--- a/saleor/graphql/product/mutations/product/product_update.py
+++ b/saleor/graphql/product/mutations/product/product_update.py
@@ -1,9 +1,9 @@
import graphene
from .....attribute import models as attribute_models
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
from ....attribute.utils import AttrValuesInput, ProductAttributeAssignmentMixin
from ....core import ResolveInfo
from ....core.descriptions import ADDED_IN_310
@@ -49,9 +49,13 @@ class ProductUpdate(ProductCreate, ModelWithExtRefMutation):
@classmethod
def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
- product = models.Product.objects.prefetched_for_webhook().get(pk=instance.pk)
- if "category" in cleaned_input or "collections" in cleaned_input:
- update_products_discounted_prices_for_promotion_task.delay([instance.id])
+ product = models.Product.objects.prefetched_for_webhook(single_object=True).get(
+ pk=instance.pk
+ )
+ listings = product.channel_listings.all()
+ channel_ids = [listing.channel_id for listing in listings]
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
+
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.product_updated, product)
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
index c8df5fb86b..6a671915f1 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
@@ -7,10 +7,10 @@ from django.utils.text import slugify
from .....attribute import AttributeInputType
from .....attribute import models as attribute_models
from .....core.tracing import traced_atomic_transaction
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
from .....product.error_codes import ProductErrorCode
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
from .....product.utils.variants import generate_and_set_variant_name
from ....attribute.types import AttributeValueInput
from ....attribute.utils import AttributeAssignmentMixin, AttrValuesInput
@@ -324,11 +324,6 @@ class ProductVariantCreate(ModelMutation):
if not instance.product.default_variant:
instance.product.default_variant = instance
instance.product.save(update_fields=["default_variant", "updated_at"])
- # Recalculate the "discounted price" for the parent product
- cls.call_event(
- update_products_discounted_prices_for_promotion_task.delay,
- [instance.product_id],
- )
stocks = cleaned_input.get("stocks")
if stocks:
cls.create_variant_stocks(instance, stocks)
@@ -349,6 +344,14 @@ class ProductVariantCreate(ModelMutation):
)
cls.call_event(event_to_call, instance)
+ @classmethod
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
+ channel_ids = models.ProductChannelListing.objects.filter(
+ product_id=instance.product_id
+ ).values_list("channel_id", flat=True)
+ # This will recalculate discounted prices for products.
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
+
@classmethod
def create_variant_stocks(cls, variant, stocks):
warehouse_ids = [stock["warehouse"] for stock in stocks]
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_delete.py b/saleor/graphql/product/mutations/product_variant/product_variant_delete.py
index f1fa9ba755..f96712502f 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_delete.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_delete.py
@@ -7,12 +7,12 @@ from django.db.models import Exists, OuterRef
from .....attribute import AttributeInputType
from .....attribute import models as attribute_models
from .....core.tracing import traced_atomic_transaction
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....order import events as order_events
from .....order import models as order_models
from .....order.tasks import recalculate_orders_task
from .....permission.enums import ProductPermissions
from .....product import models
-from .....product.tasks import update_products_discounted_prices_for_promotion_task
from ....app.dataloaders import get_app_promise
from ....channel import ChannelContext
from ....core import ResolveInfo
@@ -50,10 +50,6 @@ class ProductVariantDelete(ModelDeleteMutation, ModelWithExtRefMutation):
@classmethod
def success_response(cls, instance):
- # Update the "discounted_prices" of the parent product
- update_products_discounted_prices_for_promotion_task.delay(
- [instance.product_id]
- )
product = models.Product.objects.get(id=instance.product_id)
product.search_index_dirty = True
product.save(update_fields=["search_index_dirty"])
@@ -113,6 +109,9 @@ class ProductVariantDelete(ModelDeleteMutation, ModelWithExtRefMutation):
"channel_listings", "attributes__values", "variant_media"
)
).get(id=instance.id)
+ channel_ids = set(
+ variant.channel_listings.all().values_list("channel_id", flat=True)
+ )
with traced_atomic_transaction():
cls.delete_assigned_attribute_values(variant)
cls.delete_product_channel_listings_without_available_variants(variant)
@@ -139,6 +138,9 @@ class ProductVariantDelete(ModelDeleteMutation, ModelWithExtRefMutation):
recalculate_orders_task.delay(list(order_pks))
cls.call_event(manager.product_variant_deleted, variant)
+ # This will finally recalculate discounted prices for products.
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
+
return response
@staticmethod
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
index 53871d2714..94020d9d3c 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
@@ -6,8 +6,10 @@ from django.utils.text import slugify
from .....attribute import AttributeInputType
from .....attribute import models as attribute_models
+from .....discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
+from .....product.models import ProductChannelListing
from ....attribute.utils import AttributeAssignmentMixin, AttrValuesInput
from ....core import ResolveInfo
from ....core.descriptions import ADDED_IN_38, ADDED_IN_310
@@ -132,6 +134,14 @@ class ProductVariantUpdate(ProductVariantCreate, ModelWithExtRefMutation):
if track_inventory is not None:
instance.track_inventory = track_inventory
+ @classmethod
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
+ super().post_save_action(info, instance, cleaned_input)
+ channel_ids = ProductChannelListing.objects.filter(
+ product_id=instance.product_id
+ ).values_list("channel_id", flat=True)
+ cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
+
@classmethod
def perform_mutation( # type: ignore[override]
cls,
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 f700e91e13..fda4883229 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
@@ -6,6 +6,7 @@ import pytz
from freezegun import freeze_time
from .....product.error_codes import ProductErrorCode
+from .....product.models import ProductChannelListing
from .....product.utils.costs import get_product_costs_data
from ....tests.utils import get_graphql_content
@@ -60,9 +61,7 @@ mutation UpdateProductChannelListing(
@freeze_time("2023-11-13T14:53:59.655366")
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_product_channel_listing_update_as_staff_user(
- update_discounted_prices_task_mock,
staff_api_client,
product,
permission_manage_products,
@@ -137,7 +136,9 @@ def test_product_channel_listing_update_as_staff_user(
product_data["channelListings"][1]["availableForPurchase"]
== available_for_purchase_date.isoformat()
)
- update_discounted_prices_task_mock.assert_called_once_with([product.id])
+ assert ProductChannelListing.objects.get(
+ product=product, channel=channel_PLN
+ ).discounted_price_dirty
@freeze_time("2023-11-13T14:53:59.655366")
diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
index a96e7cfd4a..25a37dc2a6 100644
--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
@@ -12,6 +12,7 @@ from .....attribute.tests.model_helpers import (
get_product_attribute_values,
get_product_attributes,
)
+from .....discount.utils import get_active_catalogue_promotion_rules
from .....product.error_codes import ProductBulkCreateErrorCode
from .....product.models import Product
from .....product.tests.utils import create_image
@@ -83,11 +84,7 @@ PRODUCT_BULK_CREATE_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_product_bulk_create_with_base_data(
- update_products_discounted_price_task_mock,
staff_api_client,
product_type,
collection,
@@ -157,9 +154,8 @@ def test_product_bulk_create_with_base_data(
assert product.category == category
assert product.product_type == product_type
- update_products_discounted_price_task_mock.assert_called_once()
- args = set(update_products_discounted_price_task_mock.call_args.args[0])
- assert args == {product.id for product in products}
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty is True
def test_product_bulk_create_with_base_data_and_collections(
@@ -1696,9 +1692,11 @@ def test_product_bulk_create_with_variants_and_invalid_stock(
"saleor.graphql.product.bulk_mutations."
"product_bulk_create.get_webhooks_for_event"
)
-@patch("saleor.plugins.manager.PluginsManager.channel_updated")
+@patch("saleor.plugins.manager.PluginsManager.product_created")
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
def test_product_bulk_create_with_variants_and_channel_listings(
- channel_updated_webhook_mock,
+ product_variant_created_mock,
+ product_created_mock,
mocked_get_webhooks_for_event,
staff_api_client,
product_type,
@@ -1828,11 +1826,8 @@ def test_product_bulk_create_with_variants_and_channel_listings(
assert product_1_variant.channel_listings.last().channel_id == channel_USD.id
assert product_2_variant.channel_listings.last().channel_id == channel_USD.id
- # 2 product channel listing and 2 variant channel listing were created but
- # all are using same channel so only one event should be sent
- channel_updated_webhook_mock.assert_called_once_with(
- channel_USD, webhooks=[any_webhook]
- )
+ assert product_variant_created_mock.called
+ assert product_created_mock.called
def test_product_bulk_create_with_variants_and_channel_listings_with_wrong_price(
diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.py
index 63ff93a10f..747862a9ed 100644
--- a/saleor/graphql/product/tests/mutations/test_product_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_create.py
@@ -10,6 +10,7 @@ from django.utils.text import slugify
from freezegun import freeze_time
from .....core.taxes import TaxType
+from .....discount.utils import get_active_catalogue_promotion_rules
from .....graphql.core.enums import AttributeErrorCode
from .....graphql.tests.utils import (
get_graphql_content,
@@ -86,15 +87,11 @@ CREATE_PRODUCT_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_updated")
@patch("saleor.plugins.manager.PluginsManager.product_created")
def test_create_product(
created_webhook_mock,
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
product_type,
category,
@@ -189,9 +186,8 @@ def test_create_product(
created_webhook_mock.assert_called_once_with(product)
updated_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
def test_create_product_without_slug_and_not_allowed_characters_for_slug_in_name(
@@ -1089,11 +1085,7 @@ def test_create_product_no_category_id(
assert data["product"]["category"] is None
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_create_product_with_negative_weight(
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
product_type,
category,
@@ -1122,7 +1114,6 @@ def test_create_product_with_negative_weight(
error = data["errors"][0]
assert error["field"] == "weight"
assert error["code"] == ProductErrorCode.INVALID.name
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
def test_create_product_with_unicode_in_slug_and_name(
diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.py
index cc0b5fa552..dd0b477de6 100644
--- a/saleor/graphql/product/tests/mutations/test_product_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_update.py
@@ -18,10 +18,9 @@ from .....attribute.tests.model_helpers import (
get_product_attribute_values,
get_product_attributes,
)
-from .....attribute.utils import (
- associate_attribute_values_to_instance,
-)
+from .....attribute.utils import associate_attribute_values_to_instance
from .....core.taxes import TaxType
+from .....discount.utils import get_active_catalogue_promotion_rules
from .....graphql.core.enums import AttributeErrorCode
from .....graphql.tests.utils import get_graphql_content
from .....plugins.manager import PluginsManager
@@ -92,15 +91,11 @@ MUTATION_UPDATE_PRODUCT = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_updated")
@patch("saleor.plugins.manager.PluginsManager.product_created")
def test_update_product(
created_webhook_mock,
updated_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
category,
non_default_category,
@@ -194,16 +189,9 @@ def test_update_product(
updated_webhook_mock.assert_called_once_with(product)
created_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_update_and_search_product_by_description(
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
category,
non_default_category,
@@ -239,16 +227,9 @@ def test_update_and_search_product_by_description(
assert data["product"]["name"] == product_name
assert data["product"]["slug"] == product_slug
assert data["product"]["description"] == other_description_json
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_update_product_only_description(
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
product,
other_description_json,
@@ -273,14 +254,9 @@ def test_update_product_only_description(
data = content["data"]["productUpdate"]
assert not data["errors"]
assert data["product"]["description"] == other_description_json
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_update_product_only_collections(
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
product,
collection,
@@ -288,7 +264,6 @@ def test_update_product_only_collections(
permission_manage_products,
):
query = MUTATION_UPDATE_PRODUCT
- other_description_json = json.dumps(other_description_json)
product_id = graphene.Node.to_global_id("Product", product.pk)
collection_id = graphene.Node.to_global_id("Collection", collection.pk)
@@ -308,9 +283,8 @@ def test_update_product_only_collections(
assert not data["errors"]
assert len(data["product"]["collections"]) == 1
assert data["product"]["collections"][0]["name"] == collection.name
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty is True
def test_update_product_clear_description_plaintext_when_description_is_none(
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
index 58e53eb9ce..e5a2611d84 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
@@ -9,6 +9,7 @@ from django.conf import settings
from freezegun import freeze_time
from .....attribute import AttributeInputType
+from .....discount.utils import get_active_catalogue_promotion_rules
from .....product.error_codes import ProductVariantBulkErrorCode
from .....product.models import (
ProductChannelListing,
@@ -103,13 +104,9 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """
"saleor.graphql.product.bulk_mutations."
"product_variant_bulk_create.get_webhooks_for_event"
)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
def test_product_variant_bulk_create_by_name(
product_variant_created_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
mocked_get_webhooks_for_event,
staff_api_client,
product,
@@ -175,22 +172,17 @@ def test_product_variant_bulk_create_by_name(
product.refresh_from_db()
assert product.default_variant == product_variant
assert product_variant_created_webhook_mock.call_count == data["count"]
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
@patch(
"saleor.graphql.product.bulk_mutations."
"product_variant_bulk_create.get_webhooks_for_event"
)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
def test_product_variant_bulk_create_by_attribute_id(
product_variant_created_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
mocked_get_webhooks_for_event,
staff_api_client,
product,
@@ -239,9 +231,8 @@ def test_product_variant_bulk_create_by_attribute_id(
product.refresh_from_db()
assert product.default_variant == product_variant
assert product_variant_created_webhook_mock.call_count == data["count"]
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
def test_product_variant_bulk_create_by_attribute_external_ref(
@@ -2009,15 +2000,12 @@ def test_product_variant_bulk_create_without_sku(
assert ProductVariant.objects.filter(sku__isnull=True).count() == 2
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_product_variant_bulk_create_many_errors(
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
product,
size_attribute,
permission_manage_products,
+ catalogue_promotion,
):
# given
product_variant_count = ProductVariant.objects.count()
@@ -2077,7 +2065,7 @@ def test_product_variant_bulk_create_many_errors(
"channels": None,
}
assert product_variant_count == ProductVariant.objects.count()
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ assert not catalogue_promotion.rules.filter(variants_dirty=True).exists()
def test_product_variant_bulk_create_many_errors_with_ignore_failed(
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
index 568ff05a18..b08626551f 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
@@ -4,6 +4,8 @@ from unittest.mock import patch
import graphene
from django.test import override_settings
+from .....discount.models import PromotionRule
+from .....discount.utils import get_active_catalogue_promotion_rules
from .....graphql.webhook.subscription_payload import get_pre_save_payload_key
from .....product.error_codes import ProductVariantBulkErrorCode
from .....product.models import ProductChannelListing
@@ -76,13 +78,9 @@ PRODUCT_VARIANT_BULK_UPDATE_MUTATION = """
"saleor.graphql.product.bulk_mutations."
"product_variant_bulk_update.get_webhooks_for_event"
)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
def test_product_variant_bulk_update(
product_variant_created_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
mocked_get_webhooks_for_event,
staff_api_client,
product_with_single_variant,
@@ -134,20 +132,15 @@ def test_product_variant_bulk_update(
assert product_with_single_variant.variants.count() == 1
assert old_name != new_name
assert product_variant_created_webhook_mock.call_count == data["count"]
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product_with_single_variant.id]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
@patch(
"saleor.graphql.product.bulk_mutations."
"product_variant_bulk_update.get_webhooks_for_event"
)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_product_variant_bulk_update_stocks(
- update_products_discounted_prices_for_promotion_task_mock,
mocked_get_webhooks_for_event,
staff_api_client,
variant_with_many_stocks,
@@ -212,9 +205,8 @@ def test_product_variant_bulk_update_stocks(
assert stock_to_update.quantity == new_quantity
assert variant.stocks.count() == 3
assert variant.stocks.last().quantity == new_stock_quantity
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [variant.product_id]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
def test_product_variant_bulk_update_create_already_existing_stock(
@@ -305,11 +297,7 @@ def test_product_variant_bulk_update_and_remove_stock(
assert variant.stocks.count() == 1
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_product_variant_bulk_update_and_remove_stock_when_stock_not_exists(
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
variant_with_many_stocks,
warehouse,
@@ -347,7 +335,8 @@ def test_product_variant_bulk_update_and_remove_stock_when_stock_not_exists(
assert variant.stocks.count() == 2
error = data["results"][0]["errors"][0]
assert error["code"] == ProductVariantBulkErrorCode.NOT_FOUND.name
- update_products_discounted_prices_for_promotion_task_mock.assert_not_called()
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
def test_product_variant_bulk_update_stocks_with_invalid_warehouse(
@@ -406,13 +395,24 @@ def test_product_variant_bulk_update_channel_listings_input(
size_attribute,
channel_USD,
channel_PLN,
+ channel_JPY,
+ promotion_rule,
):
# given
+ promotion_rule_id = promotion_rule.id
+ second_promotion_rule = promotion_rule
+ second_promotion_rule.pk = None
+ second_promotion_rule.save()
+ second_promotion_rule.channels.add(channel_PLN)
+ promotion_rule = PromotionRule.objects.get(id=promotion_rule_id)
+
product = variant.product
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
ProductChannelListing.objects.create(product=product, channel=channel_PLN)
- existing_variant_listing = variant.channel_listings.last()
+ existing_variant_listing = variant.channel_listings.exclude(
+ channel=channel_PLN
+ ).last()
assert variant.channel_listings.count() == 1
product_id = graphene.Node.to_global_id("Product", product.pk)
@@ -450,30 +450,17 @@ def test_product_variant_bulk_update_channel_listings_input(
response = staff_api_client.post_graphql(
PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables
)
- content = get_graphql_content(response, ignore_errors=True)
- data = content["data"]["productVariantBulkUpdate"]
- existing_variant_listing.refresh_from_db()
+ get_graphql_content(response, ignore_errors=True)
+ existing_variant_listing.refresh_from_db()
# then
- assert not data["results"][0]["errors"]
- assert data["count"] == 1
- assert variant.channel_listings.count() == 2
- new_variant_channel_listing = variant.channel_listings.last()
- assert (
- new_variant_channel_listing.price_amount == not_existing_variant_listing_price
- )
- assert (
- new_variant_channel_listing.discounted_price_amount
- == not_existing_variant_listing_price
- )
- assert new_variant_channel_listing.channel == channel_PLN
- assert (
- existing_variant_listing.price_amount == new_price_for_existing_variant_listing
- )
- assert (
- existing_variant_listing.discounted_price_amount
- == new_price_for_existing_variant_listing
- )
+
+ # only promotions with created channel will be marked as dirty
+ second_promotion_rule.refresh_from_db()
+ assert second_promotion_rule.variants_dirty is True
+
+ promotion_rule.refresh_from_db()
+ assert promotion_rule.variants_dirty is True
def test_product_variant_bulk_update_and_remove_channel_listings(
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
index 56df11c2d0..c467da01a5 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
@@ -9,6 +9,7 @@ from django.conf import settings
from django.utils.text import slugify
from freezegun import freeze_time
+from .....discount.utils import get_active_catalogue_promotion_rules
from .....product.error_codes import ProductErrorCode
from .....tests.utils import dummy_editorjs, flush_post_commit_hooks
from ....core.enums import WeightUnitsEnum
@@ -76,15 +77,11 @@ CREATE_VARIANT_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
def test_create_variant_with_name(
updated_webhook_mock,
created_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
product,
product_type,
@@ -153,9 +150,8 @@ def test_create_variant_with_name(
created_webhook_mock.assert_called_once_with(product.variants.last())
updated_webhook_mock.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_delete.py b/saleor/graphql/product/tests/mutations/test_product_variant_delete.py
index c6c81e4d28..cc7da83f72 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_delete.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_delete.py
@@ -4,6 +4,7 @@ import graphene
import pytest
from prices import Money, TaxedMoney
+from .....discount.utils import get_active_catalogue_promotion_rules
from .....order import OrderEvents, OrderStatus
from .....order.models import OrderEvent, OrderLine
from .....product.models import ProductVariant
@@ -22,15 +23,11 @@ DELETE_VARIANT_BY_SKU_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_variant_by_sku(
mocked_recalculate_orders_task,
product_variant_deleted_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
product,
permission_manage_products,
@@ -56,9 +53,8 @@ def test_delete_variant_by_sku(
with pytest.raises(variant._meta.model.DoesNotExist):
variant.refresh_from_db()
mocked_recalculate_orders_task.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
DELETE_VARIANT_MUTATION = """
@@ -73,15 +69,11 @@ DELETE_VARIANT_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_variant(
mocked_recalculate_orders_task,
product_variant_deleted_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
product,
permission_manage_products,
@@ -103,9 +95,8 @@ def test_delete_variant(
with pytest.raises(variant._meta.model.DoesNotExist):
variant.refresh_from_db()
mocked_recalculate_orders_task.assert_not_called()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once_with(
- [product.id]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
def test_delete_variant_remove_checkout_lines(
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
index 9ceeefeda2..ada5896ee2 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
@@ -167,6 +167,51 @@ def test_update_product_variant_by_id(
product_variant_created_webhook_mock.assert_not_called()
+def test_update_product_variant_marks_prices_as_dirty(
+ staff_api_client,
+ product,
+ size_attribute,
+ permission_manage_products,
+ catalogue_promotion,
+):
+ # given
+ query = """
+ mutation updateVariant (
+ $id: ID!
+ $sku: String!) {
+ productVariantUpdate(
+ id: $id,
+ input: {
+ sku: $sku,
+ }) {
+ productVariant {
+ name
+ sku
+ }
+ }
+ }
+ """
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ sku = "test sku"
+
+ variables = {
+ "id": variant_id,
+ "sku": sku,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ variant.refresh_from_db()
+ get_graphql_content(response)
+ flush_post_commit_hooks()
+ assert not catalogue_promotion.rules.filter(variants_dirty=False).exists()
+
+
UPDATE_VARIANT_BY_SKU = """
mutation updateVariant (
$sku: String!,
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 3a8caf15d9..3b1b3a42da 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -10,6 +10,7 @@ from ....attribute.models import AttributeValue
from ....attribute.utils import associate_attribute_values_to_instance
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity
+from ....discount.utils import get_active_catalogue_promotion_rules
from ....order import OrderEvents, OrderStatus
from ....order.models import OrderEvent, OrderLine
from ....plugins.manager import get_plugins_manager
@@ -38,11 +39,7 @@ MUTATION_CATEGORY_BULK_DELETE = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_delete_categories(
- update_products_discounted_price_task_mock,
staff_api_client,
category_list,
product_list,
@@ -75,9 +72,38 @@ def test_delete_categories(
assert not Category.objects.filter(
id__in=[category.id for category in category_list]
).exists()
- update_products_discounted_price_task_mock.assert_called_once()
- args, kwargs = update_products_discounted_price_task_mock.call_args
- assert set(kwargs["product_ids"]) == {product.id for product in product_list}
+
+
+def test_delete_categories_invalidate_active_promotion_rules(
+ staff_api_client,
+ category_list,
+ product_list,
+ permission_manage_products,
+ catalogue_promotion,
+):
+ # given
+ for product, category in zip(product_list, category_list):
+ product.category = category
+
+ Product.objects.bulk_update(product_list, ["category"])
+
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("Category", category.id)
+ for category in category_list
+ ]
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_CATEGORY_BULK_DELETE,
+ variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ get_graphql_content(response)
+ assert not catalogue_promotion.rules.filter(variants_dirty=True).exists()
@patch("saleor.product.utils.get_webhooks_for_event")
@@ -204,9 +230,7 @@ def test_delete_categories_trigger_product_updated_webhook(
assert product_updated_mock.call_count == 2
-@patch("saleor.product.utils.update_products_discounted_prices_for_promotion_task")
def test_delete_categories_with_subcategories_and_products(
- mock_update_products_discounted_prices_for_promotion_task,
staff_api_client,
category_list,
permission_manage_products,
@@ -259,14 +283,6 @@ def test_delete_categories_with_subcategories_and_products(
id__in=[category.id for category in category_list]
).exists()
- mock_update_products_discounted_prices_for_promotion_task.delay.assert_called_once()
- (
- _call_args,
- call_kwargs,
- ) = mock_update_products_discounted_prices_for_promotion_task.delay.call_args
-
- assert set(call_kwargs["product_ids"]) == set([p.pk for p in product_list])
-
for product in product_list:
product.refresh_from_db()
assert not product.category
@@ -277,6 +293,7 @@ def test_delete_categories_with_subcategories_and_products(
for product_channel_listing in product_channel_listings:
assert product_channel_listing.is_published is False
assert not product_channel_listing.published_at
+ assert product_channel_listing.discounted_price_dirty is False
assert product_channel_listings.count() == 3
@@ -289,11 +306,7 @@ MUTATION_COLLECTION_BULK_DELETE = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_delete_collections(
- update_products_discounted_price_task_mock,
staff_api_client,
collection_list,
product_list,
@@ -324,9 +337,9 @@ def test_delete_collections(
assert not Collection.objects.filter(
id__in=[collection.id for collection in collection_list]
).exists()
- update_products_discounted_price_task_mock.assert_called_once()
- args = set(update_products_discounted_price_task_mock.call_args.args[0])
- assert args == {product.id for product in product_list}
+
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
def test_delete_collections_with_images(
@@ -995,15 +1008,11 @@ def test_delete_product_variants_by_sku(
"saleor.graphql.product.bulk_mutations."
"product_variant_bulk_delete.get_webhooks_for_event"
)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_variants_by_sku_task_for_recalculate_product_prices_called(
mocked_recalculate_orders_task,
product_variant_deleted_webhook_mock,
- update_products_discounted_price_task_mock,
mocked_get_webhooks_for_event,
staff_api_client,
product_list,
@@ -1040,9 +1049,8 @@ def test_delete_product_variants_by_sku_task_for_recalculate_product_prices_call
== content["data"]["productVariantBulkDelete"]["count"]
)
mocked_recalculate_orders_task.assert_not_called()
- update_products_discounted_price_task_mock.assert_called_once()
- args = set(update_products_discounted_price_task_mock.call_args.args[0])
- assert args == {product.id for product in product_list}
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
PRODUCT_VARIANT_BULK_DELETE_MUTATION = """
@@ -1116,15 +1124,11 @@ def test_delete_product_variants(
"saleor.graphql.product.bulk_mutations."
"product_variant_bulk_delete.get_webhooks_for_event"
)
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_variants_task_for_recalculate_product_prices_called(
mocked_recalculate_orders_task,
product_variant_deleted_webhook_mock,
- update_products_discounted_price_task_mock,
mocked_get_webhooks_for_event,
staff_api_client,
product_list,
@@ -1163,20 +1167,16 @@ def test_delete_product_variants_task_for_recalculate_product_prices_called(
== content["data"]["productVariantBulkDelete"]["count"]
)
mocked_recalculate_orders_task.assert_not_called()
- update_products_discounted_price_task_mock.assert_called_once()
- args = set(update_products_discounted_price_task_mock.call_args.args[0])
- assert args == {product.id for product in product_list}
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_delete_product_variants_invalid_object_typed_of_given_ids(
- update_products_discounted_price_task_mock,
staff_api_client,
product_variant_list,
permission_manage_products,
staff_user,
+ catalogue_promotion,
):
query = PRODUCT_VARIANT_BULK_DELETE_MUTATION
staff_user.user_permissions.add(permission_manage_products)
@@ -1195,7 +1195,7 @@ def test_delete_product_variants_invalid_object_typed_of_given_ids(
assert errors[0]["code"] == ProductErrorCode.GRAPHQL_ERROR.name
assert errors[0]["field"] == "ids"
assert data["count"] == 0
- update_products_discounted_price_task_mock.assert_not_called()
+ assert not catalogue_promotion.rules.filter(variants_dirty=True).exists()
def test_delete_product_variants_removes_checkout_lines(
diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.py
index 67b7a97e98..fd1ccbb8e9 100644
--- a/saleor/graphql/product/tests/test_category.py
+++ b/saleor/graphql/product/tests/test_category.py
@@ -12,6 +12,7 @@ from freezegun import freeze_time
from graphql_relay import to_global_id
from ....core.utils.json_serializer import CustomJsonEncoder
+from ....discount.utils import get_active_catalogue_promotion_rules
from ....product.error_codes import ProductErrorCode
from ....product.models import Category, Product, ProductChannelListing
from ....product.tests.utils import create_image, create_zip_file_with_image_ext
@@ -695,6 +696,36 @@ def test_category_update_mutation(
assert category.private_metadata == {metadata_key: metadata_value, **old_meta}
+def test_category_update_mutation_marks_prices_to_recalculate(
+ staff_api_client, category, permission_manage_products, catalogue_promotion, product
+):
+ # given
+ product.category = category
+ product.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ metadata_key = "md key"
+ metadata_value = "md value"
+
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ variables = {
+ "id": category_id,
+ "name": "Updated name",
+ "slug": "slug",
+ "metadata": [{"key": metadata_key, "value": metadata_value}],
+ }
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_CATEGORY_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ get_graphql_content(response)
+ assert not catalogue_promotion.rules.filter(variants_dirty=False).exists()
+
+
@freeze_time("2023-09-01 12:00:00")
def test_category_update_mutation_with_update_at_field(
monkeypatch, staff_api_client, category, permission_manage_products, media_root
@@ -1166,13 +1197,9 @@ MUTATION_CATEGORY_DELETE = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.core.tasks.delete_from_storage_task.delay")
def test_category_delete_mutation(
delete_from_storage_task_mock,
- update_products_discounted_price_task_mock,
staff_api_client,
category,
product_list,
@@ -1206,9 +1233,8 @@ def test_category_delete_mutation(
assert not Thumbnail.objects.filter(category_id=category_id)
assert delete_from_storage_task_mock.call_count == 2
- update_products_discounted_price_task_mock.assert_called_once()
- args, kwargs = update_products_discounted_price_task_mock.call_args
- assert set(kwargs["product_ids"]) == {product.id for product in product_list}
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty is True
@freeze_time("2022-05-12 12:00:00")
@@ -1275,9 +1301,7 @@ def test_delete_category_with_background_image(
category.refresh_from_db()
-@patch("saleor.product.utils.update_products_discounted_prices_for_promotion_task")
def test_category_delete_mutation_for_categories_tree(
- mock_update_products_discounted_prices_for_promotion_task,
staff_api_client,
categories_tree_with_published_products,
permission_manage_products,
@@ -1298,13 +1322,6 @@ def test_category_delete_mutation_for_categories_tree(
with pytest.raises(parent._meta.model.DoesNotExist):
parent.refresh_from_db()
- mock_update_products_discounted_prices_for_promotion_task.delay.assert_called_once()
- (
- _call_args,
- call_kwargs,
- ) = mock_update_products_discounted_prices_for_promotion_task.delay.call_args
- assert set(call_kwargs["product_ids"]) == set(p.pk for p in product_list)
-
product_channel_listings = ProductChannelListing.objects.filter(
product__in=product_list
)
@@ -1312,11 +1329,11 @@ def test_category_delete_mutation_for_categories_tree(
assert product_channel_listing.is_published is False
assert not product_channel_listing.published_at
assert product_channel_listings.count() == 4
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty is True
-@patch("saleor.product.utils.update_products_discounted_prices_for_promotion_task")
def test_category_delete_mutation_for_children_from_categories_tree(
- mock_update_products_discounted_prices_for_promotion_task,
staff_api_client,
categories_tree_with_published_products,
permission_manage_products,
@@ -1336,9 +1353,8 @@ def test_category_delete_mutation_for_children_from_categories_tree(
with pytest.raises(child._meta.model.DoesNotExist):
child.refresh_from_db()
- mock_update_products_discounted_prices_for_promotion_task.delay.assert_called_once_with(
- product_ids=[child_product.pk]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty is True
parent_product.refresh_from_db()
assert parent_product.category
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index c4c03d274b..19f50ea45f 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -8,6 +8,7 @@ import pytz
from django.core.files import File
from graphql_relay import to_global_id
+from ....discount.utils import get_active_catalogue_promotion_rules
from ....product.error_codes import CollectionErrorCode, ProductErrorCode
from ....product.models import Collection, CollectionChannelListing, Product
from ....product.tests.utils import create_image, create_zip_file_with_image_ext
@@ -742,6 +743,63 @@ def test_update_collection(
updated_webhook_mock.assert_called_once()
+def test_update_collection_metadata_marks_prices_to_recalculate(
+ staff_api_client,
+ collection,
+ permission_manage_products,
+ catalogue_promotion,
+ product,
+):
+ # given
+ query = """
+ mutation updateCollection(
+ $id: ID!,
+ $metadata: [MetadataInput!]
+ ) {
+
+ collectionUpdate(
+ id: $id, input: {
+ metadata: $metadata,
+ }) {
+
+ collection {
+ name
+ slug
+ description
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
+ }
+ }
+ }
+ """
+ metadata_key = "md key"
+ metadata_value = "md value"
+
+ collection.products.set([product])
+
+ variables = {
+ "id": to_global_id("Collection", collection.id),
+ "metadata": [{"key": metadata_key, "value": metadata_value}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ get_graphql_content(response)
+
+ collection.refresh_from_db()
+
+ # then
+ assert not catalogue_promotion.rules.filter(variants_dirty=False).exists()
+
+
MUTATION_UPDATE_COLLECTION_WITH_BACKGROUND_IMAGE = """
mutation updateCollection($name: String!, $slug: String!, $id: ID!,
$backgroundImage: Upload, $backgroundImageAlt: String) {
@@ -1091,13 +1149,9 @@ DELETE_COLLECTION_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
@patch("saleor.plugins.manager.PluginsManager.collection_deleted")
def test_delete_collection(
deleted_webhook_mock,
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
collection,
product_list,
@@ -1122,11 +1176,8 @@ def test_delete_collection(
collection.refresh_from_db()
deleted_webhook_mock.assert_called_once()
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
- args = set(
- update_products_discounted_prices_for_promotion_task_mock.call_args.args[0]
- )
- assert args == {product.id for product in product_list}
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty is True
@patch("saleor.core.tasks.delete_from_storage_task.delay")
@@ -1206,11 +1257,7 @@ COLLECTION_ADD_PRODUCTS_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_add_products_to_collection(
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
collection,
product_list,
@@ -1233,11 +1280,8 @@ def test_add_products_to_collection(
content = get_graphql_content(response)
data = content["data"]["collectionAddProducts"]["collection"]
assert data["products"]["totalCount"] == products_before + len(product_ids)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
- args = set(
- update_products_discounted_prices_for_promotion_task_mock.call_args.args[0]
- )
- assert args == {product.id for product in product_list}
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty is True
@patch("saleor.plugins.manager.PluginsManager.product_updated")
@@ -1312,11 +1356,7 @@ COLLECTION_REMOVE_PRODUCTS_MUTATION = """
"""
-@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
-)
def test_remove_products_from_collection(
- update_products_discounted_prices_for_promotion_task_mock,
staff_api_client,
collection,
product_list,
@@ -1339,11 +1379,8 @@ def test_remove_products_from_collection(
content = get_graphql_content(response)
data = content["data"]["collectionRemoveProducts"]["collection"]
assert data["products"]["totalCount"] == products_before - len(product_ids)
- update_products_discounted_prices_for_promotion_task_mock.assert_called_once()
- args = set(
- update_products_discounted_prices_for_promotion_task_mock.call_args.args[0]
- )
- assert args == {product.id for product in product_list}
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty is True
@patch("saleor.plugins.manager.PluginsManager.product_updated")
diff --git a/saleor/graphql/product/tests/test_product_discounted_price.py b/saleor/graphql/product/tests/test_product_discounted_price.py
index c58ecdcbca..0857dfbce7 100644
--- a/saleor/graphql/product/tests/test_product_discounted_price.py
+++ b/saleor/graphql/product/tests/test_product_discounted_price.py
@@ -3,19 +3,19 @@ from unittest.mock import patch
from freezegun import freeze_time
from graphql_relay import to_global_id
-from ....discount.models import Promotion
+from ....discount.models import Promotion, PromotionRule
+from ....discount.utils import (
+ get_active_catalogue_promotion_rules,
+ get_current_products_for_rules,
+)
+from ....product.models import ProductChannelListing
from ...discount.enums import DiscountValueTypeEnum
from ...tests.utils import get_graphql_content
-@patch(
- "saleor.graphql.product.mutations.product_variant.product_variant_delete"
- ".update_products_discounted_prices_for_promotion_task"
-)
@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_product_variant_delete_updates_discounted_price(
mocked_recalculate_orders_task,
- mock_update_products_discounted_prices_for_promotion_task,
staff_api_client,
product,
permission_manage_products,
@@ -47,16 +47,12 @@ def test_product_variant_delete_updates_discounted_price(
content = get_graphql_content(response)
data = content["data"]["productVariantDelete"]
assert data["errors"] == []
-
- mock_update_products_discounted_prices_for_promotion_task.delay.assert_called_once_with(
- [product.pk]
- )
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
mocked_recalculate_orders_task.assert_not_called()
-@patch("saleor.product.utils.update_products_discounted_prices_for_promotion_task")
def test_category_delete_updates_discounted_price(
- mock_update_products_discounted_prices_for_promotion_task,
staff_api_client,
categories_tree_with_published_products,
permission_manage_products,
@@ -92,24 +88,15 @@ def test_category_delete_updates_discounted_price(
data = content["data"]["categoryDelete"]
assert data["errors"] == []
- mock_update_products_discounted_prices_for_promotion_task.delay.assert_called_once()
- (
- _call_args,
- call_kwargs,
- ) = mock_update_products_discounted_prices_for_promotion_task.delay.call_args
- assert set(call_kwargs["product_ids"]) == set(p.pk for p in product_list)
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
for product in product_list:
product.refresh_from_db()
assert not product.category
-@patch(
- "saleor.graphql.product.mutations.collection.collection_add_products"
- ".update_products_discounted_prices_for_promotion_task.delay"
-)
-def test_collection_add_products_updates_discounted_price(
- mock_update_products_discounted_prices_for_promotion_task,
+def test_collection_add_products_updates_rule_variants_dirty(
staff_api_client,
collection,
product_list,
@@ -145,20 +132,11 @@ def test_collection_add_products_updates_discounted_price(
content = get_graphql_content(response)
data = content["data"]["collectionAddProducts"]
assert data["errors"] == []
-
- mock_update_products_discounted_prices_for_promotion_task.assert_called_once()
- args = set(
- mock_update_products_discounted_prices_for_promotion_task.call_args.args[0]
- )
- assert args == {product.id for product in product_list}
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
-@patch(
- "saleor.graphql.product.mutations.collection.collection_remove_products"
- ".update_products_discounted_prices_for_promotion_task.delay"
-)
-def test_collection_remove_products_updates_discounted_price(
- mock_update_products_discounted_prices_for_promotion_task,
+def test_collection_remove_products_updates_rule_variants_dirty(
staff_api_client,
collection,
product_list,
@@ -194,21 +172,12 @@ def test_collection_remove_products_updates_discounted_price(
content = get_graphql_content(response)
data = content["data"]["collectionRemoveProducts"]
assert data["errors"] == []
-
- mock_update_products_discounted_prices_for_promotion_task.assert_called_once()
- args = set(
- mock_update_products_discounted_prices_for_promotion_task.call_args.args[0]
- )
- assert args == {product.id for product in product_list}
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
@freeze_time("2010-05-31 12:00:01")
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_create"
- ".update_products_discounted_prices_of_promotion_task"
-)
def test_sale_create_updates_products_discounted_prices(
- mock_update_products_discounted_prices_of_promotion_task,
staff_api_client,
permission_manage_discounts,
):
@@ -251,17 +220,11 @@ def test_sale_create_updates_products_discounted_prices(
assert content["data"]["saleCreate"]["errors"] == []
sale = Promotion.objects.filter(name="Half price product").get()
- mock_update_products_discounted_prices_of_promotion_task.delay.assert_called_once_with(
- sale.id
- )
+ for rule in sale.rules.all():
+ assert rule.variants_dirty is True
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_update"
- ".update_discounted_prices_task"
-)
def test_sale_update_updates_products_discounted_prices(
- mock_update_discounted_prices_task,
staff_api_client,
promotion_converted_from_sale,
product,
@@ -297,17 +260,20 @@ def test_sale_update_updates_products_discounted_prices(
assert response.status_code == 200
content = get_graphql_content(response)
assert content["data"]["saleUpdate"]["errors"] == []
-
- args, _ = mock_update_discounted_prices_task.delay.call_args
- assert args[0] == [product.id]
+ rules = promotion.rules.all()
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
+ for listing in ProductChannelListing.objects.filter(
+ product__in=get_current_products_for_rules(rules), channel__in=channel_ids
+ ):
+ assert listing.discounted_price_dirty
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_delete"
- ".update_discounted_prices_task"
-)
def test_sale_delete_updates_products_discounted_prices(
- mock_update_discounted_prices_task,
staff_api_client,
promotion_converted_from_sale,
product,
@@ -340,17 +306,22 @@ def test_sale_delete_updates_products_discounted_prices(
content = get_graphql_content(response)
assert content["data"]["saleDelete"]["errors"] == []
+ rules = promotion.rules.all()
+ PromotionRuleChannel = PromotionRule.channels.through
+ channel_ids = set(
+ PromotionRuleChannel.objects.filter(
+ promotionrule__in=promotion.rules.all()
+ ).values_list("channel_id", flat=True)
+ )
- args, _ = mock_update_discounted_prices_task.delay.call_args
- assert args[0] == [product.id]
+ for listing in ProductChannelListing.objects.filter(
+ product__in=get_current_products_for_rules(rules),
+ channel__in=channel_ids,
+ ):
+ assert listing.discounted_price_dirty
-@patch(
- "saleor.graphql.discount.mutations.sale.sale_base_catalogue"
- ".update_discounted_prices_task"
-)
def test_sale_add_catalogues_updates_products_discounted_prices(
- mock_update_discounted_prices_task,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
product_list,
@@ -396,16 +367,8 @@ def test_sale_add_catalogues_updates_products_discounted_prices(
content = get_graphql_content(response)
assert not content["data"]["saleCataloguesAdd"]["errors"]
- 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_discounted_prices_task"
-)
def test_sale_remove_catalogues_updates_products_discounted_prices(
- mock_update_discounted_prices_task,
staff_api_client,
promotion_converted_from_sale_with_empty_predicate,
product_list,
@@ -453,4 +416,8 @@ def test_sale_remove_catalogues_updates_products_discounted_prices(
content = get_graphql_content(response)
assert not content["data"]["saleCataloguesRemove"]["errors"]
- mock_update_discounted_prices_task.delay.called_once_with(product_id)
+ for listing in ProductChannelListing.objects.filter(
+ product=product_list[-1],
+ channel__in=rule.channels.all(),
+ ):
+ assert listing.discounted_price_dirty
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 108ea42ade..2e34366238 100644
--- a/saleor/graphql/product/tests/test_variant_channel_listing_update.py
+++ b/saleor/graphql/product/tests/test_variant_channel_listing_update.py
@@ -182,9 +182,7 @@ def test_variant_channel_listing_update_with_too_many_decimal_places_in_price(
assert error["code"] == ProductErrorCode.INVALID.name
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_variant_channel_listing_update_as_staff_user(
- update_discounted_prices_task_mock,
staff_api_client,
product,
permission_manage_products,
@@ -192,7 +190,7 @@ def test_variant_channel_listing_update_as_staff_user(
channel_PLN,
):
# given
- pln_channel_listing = ProductChannelListing.objects.create(
+ product_pln_channel_listing = ProductChannelListing.objects.create(
product=product,
channel=channel_PLN,
is_published=True,
@@ -250,7 +248,8 @@ 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_discounted_prices_task_mock.assert_called_once_with([product.id])
+ product_pln_channel_listing.refresh_from_db()
+ assert product_pln_channel_listing.discounted_price_dirty
def test_variant_channel_listing_update_by_sku(
@@ -473,35 +472,6 @@ def test_variant_channel_listing_update_as_anonymous(
assert_no_permission(response)
-@patch("saleor.graphql.product.mutations.channels.update_discounted_prices_task")
-def test_product_variant_channel_listing_update_updates_discounted_price(
- mock_update_discounted_prices_task,
- staff_api_client,
- product,
- permission_manage_products,
- channel_USD,
-):
- query = PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION
- variant = product.variants.get()
- variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
-
- variables = {
- "id": variant_id,
- "input": [{"channelId": channel_id, "price": "1.99"}],
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- assert response.status_code == 200
-
- content = get_graphql_content(response)
- data = content["data"]["productVariantChannelListingUpdate"]
- assert data["errors"] == []
-
- mock_update_discounted_prices_task.delay.assert_called_once_with([product.pk])
-
-
def test_product_variant_channel_listing_update_remove_cost_price(
staff_api_client,
product,
diff --git a/saleor/product/migrations/0191_productchannellisting_discounted_price_dirty.py b/saleor/product/migrations/0191_productchannellisting_discounted_price_dirty.py
new file mode 100644
index 0000000000..ffac9c1896
--- /dev/null
+++ b/saleor/product/migrations/0191_productchannellisting_discounted_price_dirty.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.23 on 2024-01-30 10:14
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product", "0190_merge_20231221_1356"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="productchannellisting",
+ name="discounted_price_dirty",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE product_productchannellisting
+ ALTER COLUMN discounted_price_dirty
+ SET DEFAULT false;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index fe87b8d4ec..655e981b23 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -314,6 +314,7 @@ class ProductChannelListing(PublishableModel):
discounted_price = MoneyField(
amount_field="discounted_price_amount", currency_field="currency"
)
+ discounted_price_dirty = models.BooleanField(default=False)
class Meta:
unique_together = [["product", "channel"]]
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index a7e5401ac2..9a3065a98c 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -1,4 +1,5 @@
import logging
+from collections import defaultdict
from collections.abc import Iterable
from typing import Optional
from uuid import UUID
@@ -6,7 +7,7 @@ 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, Q
+from django.db.models import Exists, OuterRef, Q, QuerySet
from django.utils import timezone
from ..attribute.models import Attribute
@@ -14,13 +15,14 @@ from ..celeryconf import app
from ..core.exceptions import PreorderAllocationError
from ..discount import PromotionType
from ..discount.models import Promotion, PromotionRule
-from ..discount.utils import get_current_products_for_rules
+from ..discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from ..plugins.manager import get_plugins_manager
from ..warehouse.management import deactivate_preorder_for_variant
from ..webhook.event_types import WebhookEventAsyncType
from ..webhook.utils import get_webhooks_for_event
-from .models import Product, ProductType, ProductVariant
+from .models import Product, ProductChannelListing, ProductType, ProductVariant
from .search import PRODUCTS_BATCH_SIZE, update_products_search_vector
+from .utils.product import mark_products_in_channels_as_dirty
from .utils.variant_prices import update_discounted_prices_for_promotion
from .utils.variants import (
fetch_variants_for_promotion_rules,
@@ -88,70 +90,157 @@ def update_variants_names(product_type_pk: int, saved_attributes_ids: list[int])
@app.task
def update_products_discounted_prices_of_promotion_task(promotion_pk: UUID):
- from ..graphql.discount.utils import get_products_for_promotion
+ # FIXME: Should be removed in Saleor 3.21
- try:
- promotion = Promotion.objects.get(pk=promotion_pk)
- except ObjectDoesNotExist:
- logging.warning(f"Cannot find promotion with id: {promotion_pk}.")
- return
- 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)))
+ # In case of triggering this task by old server worker, mark promotion
+ # as dirty. The reclacultion will happen in the background
+ PromotionRule.objects.filter(promotion_id=promotion_pk).update(variants_dirty=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.
+def _get_channel_to_products_map(rule_to_variant_list):
+ variant_ids = set(
+ [rule_to_variant.productvariant_id for rule_to_variant in rule_to_variant_list]
+ )
+ variant_id_with_product_id_qs = (
+ ProductVariant.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(id__in=variant_ids)
+ .values_list("id", "product_id")
+ )
+ variant_id_to_product_id_map = {}
+ for variant_id, product_id in variant_id_with_product_id_qs:
+ variant_id_to_product_id_map[variant_id] = product_id
- Firstly the promotion rule variants are recalculated, then the products discounted
- prices are calculated.
- """
+ rule_ids = set(
+ [rule_to_variant.promotionrule_id for rule_to_variant in rule_to_variant_list]
+ )
+ PromotionChannel = PromotionRule.channels.through
+ promotion_channel_qs = PromotionChannel.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(promotionrule_id__in=rule_ids)
+ rule_to_channels_map = defaultdict(set)
+ for promotion_channel in promotion_channel_qs:
+ rule_to_channels_map[promotion_channel.promotionrule_id].add(
+ promotion_channel.channel_id
+ )
+
+ channel_to_products_map = defaultdict(set)
+ for rule_to_variant in rule_to_variant_list:
+ channel_ids = rule_to_channels_map[rule_to_variant.promotionrule_id]
+ for channel_id in channel_ids:
+ product_id = variant_id_to_product_id_map[rule_to_variant.productvariant_id]
+ channel_to_products_map[channel_id].add(product_id)
+
+ return channel_to_products_map
+
+
+def _get_existing_rule_variant_list(rules: QuerySet[PromotionRule]):
+ PromotionRuleVariant = PromotionRule.variants.through
+ existing_rules_variants = (
+ PromotionRuleVariant.objects.filter(
+ Exists(rules.filter(pk=OuterRef("promotionrule_id")))
+ )
+ .all()
+ .values_list(
+ "promotionrule_id",
+ "productvariant_id",
+ )
+ )
+ return [
+ PromotionRuleVariant(promotionrule_id=rule_id, productvariant_id=variant_id)
+ for rule_id, variant_id in existing_rules_variants
+ ]
+
+
+def update_variant_relations_for_active_promotion_rules_task():
promotions = (
Promotion.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
.active()
.filter(type=PromotionType.CATALOGUE)
)
- 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)
+ .filter(
+ Exists(promotions.filter(id=OuterRef("promotion_id"))), variants_dirty=True
+ )
.exclude(
Q(reward_value__isnull=True) | Q(reward_value=0) | Q(catalogue_predicate={})
)[:PROMOTION_RULE_BATCH_SIZE]
)
if ids := list(rules.values_list("pk", flat=True)):
- qs = PromotionRule.objects.filter(pk__in=ids).exclude(
- Q(reward_value__isnull=True) | Q(reward_value=0)
+ # fetch rules to get a qs without slicing
+ rules = PromotionRule.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(pk__in=ids)
+
+ # Fetch existing variant relations to also mark products which are no longer
+ # in the promotion as dirty
+ existing_variant_relation = _get_existing_rule_variant_list(rules)
+
+ new_rule_to_variant_list = fetch_variants_for_promotion_rules(rules=rules)
+ channel_to_product_map = _get_channel_to_products_map(
+ existing_variant_relation + new_rule_to_variant_list
)
- fetch_variants_for_promotion_rules(rules=qs)
- update_products_discounted_prices_for_promotion_task.delay(
- product_ids, ids[-1], rule_ids=rule_ids
+
+ PromotionRule.objects.filter(pk__in=ids).update(variants_dirty=False)
+ mark_products_in_channels_as_dirty(channel_to_product_map, allow_replica=True)
+ update_variant_relations_for_active_promotion_rules_task.delay()
+
+
+def update_products_discounted_prices_for_promotion_task(
+ product_ids: Iterable[int],
+ start_id: Optional[UUID] = None,
+ *,
+ rule_ids: Optional[list[UUID]] = None,
+):
+ # FIXME: Should be removed in Saleor 3.21
+
+ # In case of triggered the task by old server worker, mark all active promotions as
+ # dirty. This will make the same re-calculation as the old task.
+ from ..channel.models import Channel
+
+ mark_active_catalogue_promotion_rules_as_dirty(
+ Channel.objects.all().values_list("id", flat=True)
+ )
+
+
+def recalculate_discounted_price_for_products_task():
+ """Recalculate discounted price for products."""
+ listings = (
+ ProductChannelListing.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(discounted_price_dirty=True)
+ .order_by("id")[:DISCOUNTED_PRODUCT_BATCH]
+ )
+ listing_details = listings.values_list(
+ "id",
+ "product_id",
+ )
+ products_ids = set([product_id for _, product_id in listing_details])
+ listing_ids = set([listing_id for listing_id, _ in listing_details])
+ if products_ids:
+ products = Product.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(id__in=products_ids)
+ update_discounted_prices_for_promotion(products, only_dirty_products=True)
+ ProductChannelListing.objects.filter(id__in=listing_ids).update(
+ discounted_price_dirty=False
)
- else:
- # when all promotion rules variants are up to date, call discounted prices
- # recalculation for products
- update_discounted_prices_task.delay(product_ids)
+ recalculate_discounted_price_for_products_task.delay()
@app.task
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_discounted_prices_task.delay(remaining_ids)
+ # FIXME: Should be removed in Saleor 3.21
+
+ # in case triggering the task by old server worker, we will just mark the products
+ # as dirty. The recalculation will happen in the backgorund
+ ProductChannelListing.objects.filter(product_id__in=product_ids).update(
+ discounted_price_dirty=True
+ )
@app.task
diff --git a/saleor/product/tests/test_category.py b/saleor/product/tests/test_category.py
index 30fb81a849..909ffa270c 100644
--- a/saleor/product/tests/test_category.py
+++ b/saleor/product/tests/test_category.py
@@ -1,5 +1,6 @@
from unittest.mock import patch
+from ...discount.utils import get_active_catalogue_promotion_rules
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
from ..models import Category
@@ -19,9 +20,7 @@ def test_collect_categories_tree_products(categories_tree):
)
-@patch("saleor.product.utils.update_products_discounted_prices_for_promotion_task")
def test_delete_categories(
- mock_update_products_discounted_prices_for_promotion_task,
categories_tree_with_published_products,
):
# given
@@ -38,10 +37,6 @@ def test_delete_categories(
# then
flush_post_commit_hooks()
- calls = mock_update_products_discounted_prices_for_promotion_task.mock_calls
- assert len(calls) == 1
- call_kwargs = calls[0].kwargs
- assert set(call_kwargs["product_ids"]) == {p.pk for p in product_list}
for product in product_list:
product.refresh_from_db()
@@ -50,6 +45,9 @@ def test_delete_categories(
assert not product_channel_listing.is_published
assert not product_channel_listing.published_at
+ for rule in get_active_catalogue_promotion_rules():
+ assert rule.variants_dirty
+
@patch("saleor.product.utils.get_webhooks_for_event")
@patch("saleor.plugins.manager.PluginsManager.product_updated")
diff --git a/saleor/product/tests/test_managers.py b/saleor/product/tests/test_managers.py
index f197f996ee..3f724bb5a2 100644
--- a/saleor/product/tests/test_managers.py
+++ b/saleor/product/tests/test_managers.py
@@ -1,4 +1,4 @@
-from saleor.product.models import ProductVariant
+from ...product.models import ProductVariant
def test_available_quantity_with_no_allocations(variant, allocations):
diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.py
index 74ea971ab6..693694fc2b 100644
--- a/saleor/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/product/tests/test_product_minimal_variant_price.py
@@ -1,9 +1,11 @@
+from datetime import datetime
from decimal import Decimal
from unittest.mock import patch
import before_after
import graphene
import pytest
+import pytz
from django.core.management import call_command
from prices import Money
@@ -23,7 +25,9 @@ def test_update_discounted_price_for_promotion_no_discount(product, channel_USD)
assert product_channel_listing.discounted_price == Money("10", "USD")
# when
- update_discounted_prices_for_promotion(Product.objects.filter(id__in=[product.id]))
+ update_discounted_prices_for_promotion(
+ Product.objects.filter(id__in=[product.id]),
+ )
# then
product_channel_listing.refresh_from_db()
@@ -596,3 +600,67 @@ def test_update_discounted_price_rule_deleted_in_meantime_promotion_listing_exis
with pytest.raises(VariantChannelListingPromotionRule.DoesNotExist):
listing_promotion_rule.refresh_from_db()
assert not variant_channel_listing.variantlistingpromotionrule.exists()
+
+
+def test_update_discounted_prices_for_promotion_only_dirty_products(
+ product, channel_USD, channel_PLN
+):
+ # given
+ variant = product.variants.first()
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)
+ product_channel_listing = product.channel_listings.get(channel_id=channel_USD.id)
+ product_channel_listing.discounted_price_dirty = True
+ product_channel_listing.save()
+ second_channel_discounted_price = 123456
+ second_listing = product.channel_listings.create(
+ channel=channel_PLN,
+ discounted_price_amount=second_channel_discounted_price,
+ currency=channel_PLN.currency_code,
+ visible_in_listings=True,
+ available_for_purchase_at=(datetime(1999, 1, 1, tzinfo=pytz.UTC)),
+ discounted_price_dirty=False,
+ )
+
+ variant_price = Money("9.99", "USD")
+ variant_channel_listing.price = variant_price
+ variant_channel_listing.discounted_price = variant_price
+ variant_channel_listing.save()
+ product_channel_listing.refresh_from_db()
+
+ reward_value = Decimal("2")
+ promotion = Promotion.objects.create(
+ name="Promotion",
+ )
+ rule = promotion.rules.create(
+ name="Percentage promotion rule",
+ promotion=promotion,
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule.channels.add(variant_channel_listing.channel)
+ rule.variants.add(variant)
+
+ # when
+ update_discounted_prices_for_promotion(
+ Product.objects.filter(id__in=[product.id]), only_dirty_products=True
+ )
+
+ # then
+ expected_price_amount = variant_price.amount - reward_value
+ product_channel_listing.refresh_from_db()
+ variant_channel_listing.refresh_from_db()
+ assert product_channel_listing.discounted_price_amount == expected_price_amount
+ assert variant_channel_listing.discounted_price_amount == expected_price_amount
+ assert variant_channel_listing.promotion_rules.first() == rule
+ assert variant_channel_listing.promotion_rules.first()
+ assert (
+ variant_channel_listing.variantlistingpromotionrule.first().discount_amount
+ == reward_value
+ )
+ second_listing.refresh_from_db()
+ assert second_listing.discounted_price_amount == second_channel_discounted_price
diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.py
index a1ea0c12fd..c2bf54b993 100644
--- a/saleor/product/tests/test_tasks.py
+++ b/saleor/product/tests/test_tasks.py
@@ -1,169 +1,128 @@
import logging
-import uuid
from datetime import timedelta
from decimal import Decimal
from unittest.mock import patch
-import graphene
import pytest
from django.utils import timezone
-from ...discount import RewardValueType
+from ...discount import PromotionType, RewardValueType
from ...discount.models import Promotion, PromotionRule
-from ..models import ProductChannelListing, ProductVariantChannelListing
+from ..models import Product, 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,
+ recalculate_discounted_price_for_products_task,
update_products_search_vector_task,
+ update_variant_relations_for_active_promotion_rules_task,
update_variants_names,
)
-
-
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
-def test_update_products_discounted_prices_of_promotion_task(
- update_discounted_prices_task_mock,
- product,
-):
- # given
- promotion = Promotion.objects.create(
- name="Promotion",
- )
- promotion.rules.create(
- name="Percentage promotion rule",
- promotion=promotion,
- catalogue_predicate={
- "productPredicate": {
- "ids": [graphene.Node.to_global_id("Product", product.id)]
- }
- },
- reward_value_type=RewardValueType.PERCENTAGE,
- reward_value=Decimal("5.0"),
- )
-
- # when
- update_products_discounted_prices_of_promotion_task(promotion.id)
-
- # then
- 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}
+from ..utils.variants import fetch_variants_for_promotion_rules
@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
+ "saleor.product.tasks.update_variant_relations_for_active_promotion_rules_task."
+ "delay"
)
-def test_update_products_discounted_prices_of_promotion_task_discount_does_not_exist(
- update_product_prices_mock, caplog
-):
- # given
- caplog.set_level(logging.WARNING)
- promotion_id = uuid.uuid4()
-
- # when
- update_products_discounted_prices_of_promotion_task(promotion_id)
-
- # then
- update_product_prices_mock.assert_not_called()
- assert f"Cannot find promotion with id: {promotion_id}" in caplog.text
-
-
-@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_discounted_prices_task_mock,
+def test_update_variant_relations_for_active_promotion_rules_task(
+ update_variant_relations_for_active_promotion_rules_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]
+ PromotionRule.objects.update(variants_dirty=True)
PromotionRuleVariant = PromotionRule.variants.through
PromotionRuleVariant.objects.all().delete()
-
- collection.products.add(*product_list[1:])
+ products_with_promotions = product_list[1:]
+ collection.products.add(*products_with_promotions)
# when
- update_products_discounted_prices_for_promotion_task(product_ids)
+ update_variant_relations_for_active_promotion_rules_task()
# then
- update_discounted_prices_task_mock.assert_called_once_with(product_ids)
+ listing_marked_as_dirty = ProductChannelListing.objects.filter(
+ product__in=products_with_promotions, discounted_price_dirty=True
+ ).values_list("id", flat=True)
+ all_product_listings = ProductChannelListing.objects.filter(
+ product__in=products_with_promotions
+ ).values_list("id", flat=True)
+ assert listing_marked_as_dirty
+ assert set(listing_marked_as_dirty) == set(all_product_listings)
assert set(
PromotionRuleVariant.objects.values_list("promotionrule_id", flat=True)
) == set(PromotionRule.objects.values_list("id", flat=True))
+ assert update_variant_relations_for_active_promotion_rules_task_mock.called
@patch(
- "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
+ "saleor.product.tasks.update_variant_relations_for_active_promotion_rules_task."
+ "delay"
)
-@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_with_order_predicate(
- update_discounted_prices_task_mock,
- update_products_discounted_prices_for_promotion_task_delay_mocked,
- promotion_list,
+def test_update_variant_relations_for_active_promotion_rules_task_when_not_valid(
+ update_variant_relations_for_active_promotion_rules_task_mock,
product_list,
+ category,
+ channel_USD,
):
# given
- Promotion.objects.update(start_date=timezone.now() - timedelta(days=1))
- product_ids = [product.id for product in product_list]
- PromotionRule.objects.update(catalogue_predicate={})
- PromotionRuleVariant = PromotionRule.variants.through
+ category.metadata = {"test": "test"}
+ category.save(update_fields=["metadata"])
+
+ promotion = Promotion.objects.create(
+ name="Promotion",
+ type=PromotionType.CATALOGUE,
+ end_date=timezone.now() + timedelta(days=30),
+ )
+ rule = promotion.rules.create(
+ name="Percentage promotion rule",
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("10"),
+ catalogue_predicate={
+ "categoryPredicate": {"metadata": [{"key": "test", "value": "test"}]}
+ },
+ )
+ rule.channels.add(channel_USD)
+ fetch_variants_for_promotion_rules(promotion.rules.all())
+
+ PromotionRule.objects.update(variants_dirty=True)
+ category.metadata = {}
+ category.save(update_fields=["metadata"])
# when
- update_products_discounted_prices_for_promotion_task(product_ids)
+ update_variant_relations_for_active_promotion_rules_task()
# then
- assert not update_products_discounted_prices_for_promotion_task_delay_mocked.called
- 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))
+ product_ids_in_category = Product.objects.filter(category=category).values_list(
+ "id", flat=True
+ )
+ assert ProductChannelListing.objects.filter(
+ product_id__in=product_ids_in_category, discounted_price_dirty=True
+ ).count() == len(product_ids_in_category)
@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,
+def test_update_variant_relations_for_active_promotion_rules_task_with_order_predicate(
+ order_promotion_rule,
):
# 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]
+ PromotionRule.objects.update(catalogue_predicate={})
# when
- update_products_discounted_prices_for_promotion_task(
- product_ids, rule_ids=[rule_id]
- )
+ update_variant_relations_for_active_promotion_rules_task()
# then
- update_discounted_prices_task_mock.assert_called_once_with(product_ids)
- assert set(
- PromotionRuleVariant.objects.values_list("promotionrule_id", flat=True)
- ) == {rule_id}
+ assert PromotionRule.objects.filter(variants_dirty=True).count() == 0
@pytest.mark.parametrize("reward_value", [None, 0])
@patch("saleor.product.tasks.PROMOTION_RULE_BATCH_SIZE", 1)
-@patch("saleor.product.tasks.update_discounted_prices_task.delay")
+@patch("saleor.product.tasks.recalculate_discounted_price_for_products_task.delay")
@patch("saleor.product.utils.variants.fetch_variants_for_promotion_rules")
-def test_update_products_discounted_prices_for_promotion_task_with_empty_reward_value(
+def test_update_variant_relations_for_active_promotion_rules_with_empty_reward_value(
fetch_variants_for_promotion_rules_mock,
- update_discounted_prices_task_mock,
+ recalculate_discounted_price_for_products_task_mock,
reward_value,
promotion_list,
collection,
@@ -177,41 +136,98 @@ def test_update_products_discounted_prices_for_promotion_task_with_empty_reward_
collection.products.add(*product_list[1:])
rule = PromotionRule.objects.first()
+ rule.variants_dirty = False
rule.reward_value = reward_value
rule.save(update_fields=["reward_value"])
- 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]
- )
+ recalculate_discounted_price_for_products_task()
# then
- update_discounted_prices_task_mock.assert_called_once_with(product_ids)
- assert (
- set(PromotionRuleVariant.objects.values_list("promotionrule_id", flat=True))
- == set()
- )
+ assert not fetch_variants_for_promotion_rules_mock.called
+ assert not recalculate_discounted_price_for_products_task_mock.called
-@patch("saleor.product.tasks.DISCOUNTED_PRODUCT_BATCH", 1)
-def test_update_discounted_prices_task(
+@patch("saleor.product.tasks.recalculate_discounted_price_for_products_task.delay")
+def test_recalculate_discounted_price_for_products_task(
+ recalculate_discounted_price_for_products_task_mock,
product_list,
):
# given
- ids = [product.id for product in product_list]
- ProductChannelListing.objects.update(discounted_price_amount=0)
+ ProductChannelListing.objects.update(
+ discounted_price_amount=0, discounted_price_dirty=True
+ )
ProductVariantChannelListing.objects.update(discounted_price_amount=0)
# when
- update_discounted_prices_task(ids)
+ recalculate_discounted_price_for_products_task()
# then
assert not ProductChannelListing.objects.filter(discounted_price_amount=0).exists()
assert not ProductVariantChannelListing.objects.filter(
discounted_price_amount=0
).exists()
+ assert recalculate_discounted_price_for_products_task_mock.called
+
+
+@patch("saleor.product.tasks.update_discounted_prices_for_promotion")
+@patch("saleor.product.tasks.recalculate_discounted_price_for_products_task.delay")
+def test_recalculate_discounted_price_for_products_task_with_correct_prices(
+ recalculate_discounted_price_for_products_task_mock,
+ update_discounted_prices_for_promotion_mock,
+ product_list,
+):
+ # given
+ ProductChannelListing.objects.update(discounted_price_dirty=False)
+
+ # when
+ recalculate_discounted_price_for_products_task()
+
+ # then
+ assert not recalculate_discounted_price_for_products_task_mock.called
+ assert not update_discounted_prices_for_promotion_mock.called
+
+
+@patch("saleor.product.tasks.update_discounted_prices_for_promotion")
+@patch("saleor.product.tasks.recalculate_discounted_price_for_products_task.delay")
+def test_recalculate_discounted_price_for_products_task_updates_only_dirty_listings(
+ recalculate_discounted_price_for_products_task_mock,
+ update_discounted_prices_for_promotion_mock,
+ product_list,
+):
+ # given
+
+ listings = ProductChannelListing.objects.all()
+ assert listings.count() != 1
+
+ listing_marked_as_dirty = listings.first()
+ listing_marked_as_dirty.discounted_price_dirty = True
+ listing_marked_as_dirty.save(update_fields=["discounted_price_dirty"])
+
+ # when
+ recalculate_discounted_price_for_products_task()
+
+ # then
+ assert update_discounted_prices_for_promotion_mock.called
+ recalculate_discounted_price_for_products_task_mock.called_once_with(
+ listing_marked_as_dirty.product, only_dirty_products=True
+ )
+
+
+@patch("saleor.product.tasks.recalculate_discounted_price_for_products_task.delay")
+@patch("saleor.product.tasks.PROMOTION_RULE_BATCH_SIZE", 1)
+def test_recalculate_discounted_price_for_products_task_re_trigger_task(
+ recalculate_discounted_price_for_products_task_mock,
+ product_list,
+):
+ # given
+ ProductChannelListing.objects.update(discounted_price_dirty=True)
+
+ # when
+ recalculate_discounted_price_for_products_task()
+
+ # then
+ assert recalculate_discounted_price_for_products_task_mock.called
@patch("saleor.product.tasks._update_variants_names")
@@ -277,7 +293,7 @@ def test_update_products_search_vector_task(product):
@pytest.mark.slow
@pytest.mark.limit_memory("50 MB")
-def test_mem_usage_update_products_discounted_prices(lots_of_products_with_variants):
- update_products_discounted_prices_for_promotion_task(
- lots_of_products_with_variants.values_list("pk", flat=True)
- )
+def test_mem_usage_recalculate_discounted_price_for_products_task(
+ lots_of_products_with_variants,
+):
+ recalculate_discounted_price_for_products_task()
diff --git a/saleor/product/tests/test_utils_product.py b/saleor/product/tests/test_utils_product.py
new file mode 100644
index 0000000000..6aaf228619
--- /dev/null
+++ b/saleor/product/tests/test_utils_product.py
@@ -0,0 +1,212 @@
+from datetime import datetime
+from unittest.mock import patch
+
+import pytz
+
+from ...discount.models import PromotionRule
+from ..models import ProductChannelListing
+from ..utils.product import (
+ get_channel_to_products_map_from_rules,
+ mark_products_in_channels_as_dirty,
+)
+
+
+@patch("saleor.product.utils.product.ProductChannelListing.objects.filter")
+def test_mark_products_in_channels_as_dirty_skips_when_input_as_empty_dict(
+ mocked_product_channel_listing_filter,
+):
+ # when
+ mark_products_in_channels_as_dirty({})
+
+ # then
+ assert not mocked_product_channel_listing_filter.called
+
+
+def test_mark_products_in_channels_as_dirty(product_list, channel_USD):
+ # given
+ product = product_list[0]
+ product_channel_listing = product.channel_listings.all()
+ product_channel_listing.update(discounted_price_dirty=False)
+
+ assert ProductChannelListing.objects.count() != product_channel_listing.count()
+
+ # when
+ mark_products_in_channels_as_dirty({channel_USD.id: {product.id}})
+
+ # then
+ assert product_channel_listing.filter(discounted_price_dirty=False).count() == 0
+ assert (
+ ProductChannelListing.objects.exclude(product_id=product.id)
+ .filter(discounted_price_dirty=True)
+ .count()
+ == 0
+ )
+
+
+def test_mark_products_in_channels_as_dirty_product_process_only_for_provided_channels(
+ product_list, channel_PLN, channel_USD
+):
+ # given
+ product = product_list[0]
+ second_listing = product.channel_listings.create(
+ channel=channel_PLN,
+ discounted_price_amount=20,
+ currency=channel_PLN.currency_code,
+ visible_in_listings=True,
+ available_for_purchase_at=(datetime(1999, 1, 1, tzinfo=pytz.UTC)),
+ discounted_price_dirty=False,
+ )
+ product_channel_listing = product.channel_listings.all()
+ product_channel_listing.update(discounted_price_dirty=False)
+
+ assert ProductChannelListing.objects.count() != product_channel_listing.count()
+
+ # when
+ mark_products_in_channels_as_dirty({channel_USD.id: {product.id}})
+
+ # then
+ second_listing.refresh_from_db()
+ assert second_listing.discounted_price_dirty is False
+ assert (
+ ProductChannelListing.objects.exclude(
+ product_id=product.id, channel_id=channel_USD.id
+ )
+ .filter(discounted_price_dirty=True)
+ .count()
+ == 0
+ )
+
+
+def test_mark_products_in_channels_as_dirty_with_multiple_products_and_channels(
+ product_list, channel_PLN, channel_USD
+):
+ # given
+ first_product = product_list[0]
+ second_listing_for_first_product = first_product.channel_listings.create(
+ channel=channel_PLN,
+ discounted_price_amount=20,
+ currency=channel_PLN.currency_code,
+ visible_in_listings=True,
+ available_for_purchase_at=(datetime(1999, 1, 1, tzinfo=pytz.UTC)),
+ discounted_price_dirty=False,
+ )
+ first_product_channel_listing = first_product.channel_listings.all()
+ first_product_channel_listing.update(discounted_price_dirty=False)
+
+ second_product = product_list[1]
+ second_listing_for_second_product = second_product.channel_listings.create(
+ channel=channel_PLN,
+ discounted_price_amount=20,
+ currency=channel_PLN.currency_code,
+ visible_in_listings=True,
+ available_for_purchase_at=(datetime(1999, 1, 1, tzinfo=pytz.UTC)),
+ discounted_price_dirty=False,
+ )
+
+ # when
+ mark_products_in_channels_as_dirty(
+ {
+ channel_USD.id: {first_product.id, second_product.id},
+ channel_PLN.id: {first_product.id},
+ }
+ )
+
+ # then
+ second_listing_for_first_product.refresh_from_db()
+ second_listing_for_second_product.refresh_from_db()
+ assert second_listing_for_second_product.discounted_price_dirty is False
+ listings_marked_as_dirty = ProductChannelListing.objects.filter(
+ discounted_price_dirty=True
+ )
+ assert listings_marked_as_dirty.all().count() == 3
+ assert listings_marked_as_dirty.filter(
+ product_id=first_product.id, channel_id=channel_USD.id
+ ).first()
+ assert listings_marked_as_dirty.filter(
+ product_id=first_product.id, channel_id=channel_PLN.id
+ ).first()
+ assert listings_marked_as_dirty.filter(
+ product_id=second_product.id, channel_id=channel_USD.id
+ ).first()
+
+
+def test_get_channel_to_products_map_from_rules_empty_rules_qs():
+ # when
+ results = get_channel_to_products_map_from_rules(rules=PromotionRule.objects.none())
+
+ # then
+ assert results == {}
+
+
+def test_get_channel_to_products_when_single_rule_related(
+ catalogue_promotion, channel_USD, product
+):
+ # given
+ rule = catalogue_promotion.rules.first()
+ rule.variants.set([product.variants.first()])
+ rule.channels.set([channel_USD])
+
+ # when
+ result = get_channel_to_products_map_from_rules(
+ rules=PromotionRule.objects.filter(id=rule.id)
+ )
+
+ # then
+ assert isinstance(result, dict)
+ assert dict(result) == {channel_USD.id: {product.id}}
+
+
+def test_get_channel_to_products_when_multiple_rules_related(
+ promotion_list, channel_USD, product_list
+):
+ # given
+ first_product = product_list[0]
+ second_product = product_list[1]
+
+ first_promotion = promotion_list[0]
+ second_promotion = promotion_list[1]
+ first_rule = first_promotion.rules.first()
+ first_rule.variants.set([first_product.variants.first()])
+ first_rule.channels.set([channel_USD])
+ second_rule = second_promotion.rules.first()
+ second_rule.variants.set([second_product.variants.first()])
+ second_rule.channels.set([channel_USD])
+
+ # when
+ results = get_channel_to_products_map_from_rules(
+ rules=PromotionRule.objects.filter(id__in=[first_rule.id, second_rule.id])
+ )
+
+ # then
+ assert isinstance(results, dict)
+ assert dict(results) == {channel_USD.id: {first_product.id, second_product.id}}
+
+
+def test_get_channel_to_products_when_multiple_channels_and_rules_related(
+ promotion_list, channel_USD, channel_PLN, channel_JPY, product_list
+):
+ # given
+ first_product = product_list[0]
+ second_product = product_list[1]
+
+ first_promotion = promotion_list[0]
+ second_promotion = promotion_list[1]
+ first_rule = first_promotion.rules.first()
+ first_rule.variants.set([first_product.variants.first()])
+ first_rule.channels.set([channel_USD, channel_PLN])
+ second_rule = second_promotion.rules.first()
+ second_rule.variants.set([second_product.variants.first()])
+ second_rule.channels.set([channel_PLN, channel_JPY])
+
+ # when
+ results = get_channel_to_products_map_from_rules(
+ rules=PromotionRule.objects.filter(id__in=[first_rule.id, second_rule.id])
+ )
+
+ # then
+ assert isinstance(results, dict)
+ assert results[channel_USD.id] == {
+ first_product.id,
+ }
+ assert results[channel_PLN.id] == {first_product.id, second_product.id}
+ assert results[channel_JPY.id] == {second_product.id}
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index e6369ba6cd..65a60e04a3 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -4,10 +4,10 @@ from typing import TYPE_CHECKING, Union
from ...core.taxes import TaxedMoney, zero_taxed_money
from ...core.tracing import traced_atomic_transaction
from ...core.utils.events import call_event
+from ...discount.utils import mark_active_catalogue_promotion_rules_as_dirty
from ...webhook.event_types import WebhookEventAsyncType
from ...webhook.utils import get_webhooks_for_event
from ..models import Product, ProductChannelListing
-from ..tasks import update_products_discounted_prices_for_promotion_task
if TYPE_CHECKING:
from datetime import date, datetime
@@ -51,9 +51,8 @@ def delete_categories(categories_ids: list[Union[str, int]], manager):
for category in categories:
products = products | collect_categories_tree_products(category)
- ProductChannelListing.objects.filter(product__in=products).update(
- is_published=False, published_at=None
- )
+ product_channel_listing = ProductChannelListing.objects.filter(product__in=products)
+ product_channel_listing.update(is_published=False, published_at=None)
products = list(products)
category_instances = [cat for cat in categories]
@@ -65,10 +64,8 @@ def delete_categories(categories_ids: list[Union[str, int]], manager):
for product in products:
call_event(manager.product_updated, product, webhooks=webhooks)
- call_event(
- update_products_discounted_prices_for_promotion_task.delay,
- product_ids=[product.id for product in products],
- )
+ channel_ids = set(product_channel_listing.values_list("channel_id", flat=True))
+ call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)
def collect_categories_tree_products(category: "Category") -> "QuerySet[Product]":
diff --git a/saleor/product/utils/product.py b/saleor/product/utils/product.py
new file mode 100644
index 0000000000..3e37a0fb95
--- /dev/null
+++ b/saleor/product/utils/product.py
@@ -0,0 +1,126 @@
+from collections import defaultdict
+
+from django.conf import settings
+from django.db.models import Exists, OuterRef, QuerySet
+
+from ...discount.models import PromotionRule
+from ...product.models import ProductChannelListing
+from ..models import ProductVariant
+
+
+def get_channel_to_products_map_from_rules(
+ rules: "QuerySet[PromotionRule]", allow_replica=False
+) -> dict[int, set[int]]:
+ """Build map of channel ids to product ids based on promotion rules relations.
+
+ The function returns the dictionary of channel_id to product_ids. Channels are
+ aggregated from the input promotion rules. Returned product ids are ID of the
+ product which has a variant assigned to the promotion rule.
+ """
+ PromotionRuleVariant = PromotionRule.variants.through
+ promotion_rule_qs = PromotionRuleVariant.objects.all()
+ product_variant_qs = ProductVariant.objects.all()
+ PromotionRuleChannel = PromotionRule.channels.through
+ promotion_rule_channel_qs = PromotionRuleChannel.objects.all()
+ rules_qs = rules
+ if allow_replica:
+ rules_qs = rules.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ product_variant_qs = product_variant_qs.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ )
+ promotion_rule_qs = promotion_rule_qs.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ )
+ promotion_rule_channel_qs = promotion_rule_channel_qs.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ )
+ rule_variants = promotion_rule_qs.filter(
+ Exists(rules_qs.filter(pk=OuterRef("promotionrule_id")))
+ )
+
+ variant_to_product_qs = product_variant_qs.filter(
+ Exists(rule_variants.filter(productvariant_id=OuterRef("id")))
+ ).values_list("id", "product_id")
+ variant_to_product_map = {}
+ for variant_id, product_id in variant_to_product_qs:
+ variant_to_product_map[variant_id] = product_id
+
+ rule_channels = promotion_rule_channel_qs.filter(
+ Exists(rules_qs.filter(pk=OuterRef("promotionrule_id")))
+ ).values_list("promotionrule_id", "channel_id")
+ rule_to_channels_map = defaultdict(set)
+ for rule_id, channel_id in rule_channels:
+ rule_to_channels_map[rule_id].add(channel_id)
+
+ channel_to_products_map = defaultdict(set)
+ for rule_variant in rule_variants:
+ channel_ids = rule_to_channels_map[rule_variant.promotionrule_id]
+ for channel_id in channel_ids:
+ product_id = variant_to_product_map[rule_variant.productvariant_id]
+ channel_to_products_map[channel_id].add(product_id)
+ return channel_to_products_map
+
+
+def mark_products_in_channels_as_dirty_based_on_rules(
+ rules: "QuerySet[PromotionRule]", allow_replica=False
+):
+ """Mark products as dirty to recalculate prices.
+
+ Takes the promotion rules as input and marks the discounted_price_dirty flag as
+ True for all product channel listings related to input rules.
+ """
+ channel_to_product_ids = get_channel_to_products_map_from_rules(
+ rules, allow_replica=allow_replica
+ )
+ if channel_to_product_ids:
+ mark_products_in_channels_as_dirty(
+ channel_to_product_ids, allow_replica=allow_replica
+ )
+
+
+def mark_products_in_channels_as_dirty(
+ channel_to_product_ids: dict[int, set[int]], allow_replica=False
+):
+ """Mark products as dirty to recalculate prices.
+
+ Takes the dictionary of channel_id to product_ids as input and marks the
+ discounted_price_dirty flag as True for all product channel listings related to
+ input channels and products.
+ The input structure looks like below:
+ {
+ channel_id1: {product_id1, product_id2, ...},
+ channel_id2: {product_id3, product_id4, ...},
+ ...
+ }
+
+ The structure can be built by function `get_channel_to_products_map_from_rules`
+ """
+
+ if not channel_to_product_ids:
+ return
+ channels = list(channel_to_product_ids.keys())
+ product_ids = {
+ product_id
+ for product_ids in channel_to_product_ids.values()
+ for product_id in product_ids
+ }
+ listing_ids_to_update = []
+ product_channel_listings_qs = ProductChannelListing.objects.all()
+ if allow_replica:
+ product_channel_listings_qs = product_channel_listings_qs.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ )
+
+ product_channel_listings = product_channel_listings_qs.filter(
+ product_id__in=product_ids, channel_id__in=channels
+ ).values_list("id", "product_id", "channel_id")
+
+ for id, product_id, channel_id in product_channel_listings.iterator():
+ product_ids = channel_to_product_ids.get(channel_id, set())
+ if product_id in product_ids:
+ listing_ids_to_update.append(id)
+
+ if listing_ids_to_update:
+ ProductChannelListing.objects.filter(id__in=listing_ids_to_update).update(
+ discounted_price_dirty=True
+ )
diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.py
index d5a7e1a7fa..23a970435a 100644
--- a/saleor/product/utils/variant_prices.py
+++ b/saleor/product/utils/variant_prices.py
@@ -2,6 +2,7 @@ from collections import defaultdict
from decimal import Decimal
from uuid import UUID
+from django.conf import settings
from django.db import transaction
from django.db.models import Exists, OuterRef
from prices import Money
@@ -23,7 +24,9 @@ from ..models import (
)
-def update_discounted_prices_for_promotion(products: ProductsQueryset):
+def update_discounted_prices_for_promotion(
+ products: ProductsQueryset, only_dirty_products: bool = False
+):
"""Update Products and ProductVariants discounted prices.
The discounted price is the minimal price of the product/variant based on active
@@ -31,6 +34,9 @@ def update_discounted_prices_for_promotion(products: ProductsQueryset):
If there is no applied promotion rule, the discounted price for the product
is equal to the cheapest variant price, in the case of the variant it's equal
to the variant price.
+
+ When only_dirty_products set to True, the prices will be recalculated only for the
+ listings marked as dirty.
"""
variant_qs = ProductVariant.objects.filter(
Exists(products.filter(id=OuterRef("product_id")))
@@ -49,9 +55,12 @@ def update_discounted_prices_for_promotion(products: ProductsQueryset):
changed_variant_listing_promotion_rule_to_create = []
changed_variant_listing_promotion_rule_to_update = []
- product_channel_listings = ProductChannelListing.objects.filter(
- Exists(products.filter(id=OuterRef("product_id")))
- )
+ product_channel_listings = ProductChannelListing.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(Exists(products.filter(id=OuterRef("product_id"))))
+ if only_dirty_products:
+ product_channel_listings.filter(discounted_price_dirty=True)
+
for product_channel_listing in product_channel_listings:
product_id = product_channel_listing.product_id
channel_id = product_channel_listing.channel_id
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index b82017a764..c3e850b44a 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -70,3 +70,4 @@ def fetch_variants_for_promotion_rules(
]
)
update_rule_variant_relation(rules, new_rules_variants)
+ return new_rules_variants
diff --git a/saleor/settings.py b/saleor/settings.py
index 669ae3e218..77ed50553e 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -558,6 +558,11 @@ BEAT_UPDATE_SEARCH_SEC = parse(
)
BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC = BEAT_UPDATE_SEARCH_SEC
+BEAT_PRICE_RECALCULATION_SCHEDULE = parse(
+ os.environ.get("BEAT_PRICE_RECALCULATION_SCHEDULE", "30 seconds")
+)
+BEAT_PRICE_RECALCULATION_SCHEDULE_EXPIRE_AFTER_SEC = BEAT_PRICE_RECALCULATION_SCHEDULE
+
# Defines the Celery beat scheduler entries.
#
# Note: if a Celery task triggered by a Celery beat entry has an expiration
@@ -627,6 +632,19 @@ CELERY_BEAT_SCHEDULE = {
"task": "saleor.payment.tasks.transaction_release_funds_for_checkout_task",
"schedule": timedelta(minutes=10),
},
+ "recalculate-promotion-rules": {
+ "task": (
+ "saleor.product.tasks"
+ ".update_variant_relations_for_active_promotion_rules_task"
+ ),
+ "schedule": timedelta(seconds=BEAT_PRICE_RECALCULATION_SCHEDULE),
+ "options": {"expires": BEAT_PRICE_RECALCULATION_SCHEDULE_EXPIRE_AFTER_SEC},
+ },
+ "recalculate-discounted-price-for-products": {
+ "task": "saleor.product.tasks.recalculate_discounted_price_for_products_task",
+ "schedule": timedelta(seconds=BEAT_PRICE_RECALCULATION_SCHEDULE),
+ "options": {"expires": BEAT_PRICE_RECALCULATION_SCHEDULE_EXPIRE_AFTER_SEC},
+ },
}
# The maximum wait time between each is_due() call on schedulers
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_fixed_promotion.py b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_fixed_promotion.py
index 7467ee834a..ff3c75dad6 100644
--- a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_fixed_promotion.py
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_fixed_promotion.py
@@ -1,5 +1,6 @@
import pytest
+from ......product.tasks import recalculate_discounted_price_for_products_task
from ....product.utils.preparing_product import prepare_product
from ....promotions.utils import create_promotion, create_promotion_rule
from ....shop.utils import prepare_default_shop
@@ -72,6 +73,10 @@ def test_checkout_products_on_fixed_promotion_core_2102(
assert promotion_rule["channels"][0]["id"] == channel_id
assert product_predicate[0] == product_id
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - checkoutCreate for product on promotion
lines = [
{"variantId": product_variant_id, "quantity": 2},
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_percentage_promotion.py b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_percentage_promotion.py
index 710444bbc5..23f3e98f74 100644
--- a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_percentage_promotion.py
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_percentage_promotion.py
@@ -1,5 +1,6 @@
import pytest
+from ......product.tasks import recalculate_discounted_price_for_products_task
from ....product.utils.preparing_product import prepare_product
from ....promotions.utils import create_promotion, create_promotion_rule
from ....shop.utils import prepare_default_shop
@@ -70,6 +71,10 @@ def test_checkout_products_on_percentage_promotion_core_2104(
assert promotion_rule["channels"][0]["id"] == channel_id
assert product_predicate[0] == product_id
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - checkoutCreate for product on promotion
lines = [
{"variantId": product_variant_id, "quantity": 2},
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price.py b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price.py
index d68265d00b..9c115e0f4f 100644
--- a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price.py
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price.py
@@ -1,5 +1,6 @@
import pytest
+from ......product.tasks import recalculate_discounted_price_for_products_task
from ....product.utils import get_product
from ....product.utils.preparing_product import prepare_product
from ....promotions.utils import create_promotion, create_promotion_rule
@@ -72,6 +73,10 @@ def test_checkout_with_fixed_promotion_should_not_result_in_negative_price_CORE_
assert promotion_rule["channels"][0]["id"] == channel_id
assert product_predicate[0] == product_id
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 2 - Get product and check if it is on promotion
product_data = get_product(e2e_staff_api_client, product_id, channel_slug)
assert product_data["id"] == product_id
diff --git a/saleor/tests/e2e/checkout/discounts/sales/test_checkout_product_on_fixed_sale.py b/saleor/tests/e2e/checkout/discounts/sales/test_checkout_product_on_fixed_sale.py
index 77a7ffcec4..9cc6a8e8d5 100644
--- a/saleor/tests/e2e/checkout/discounts/sales/test_checkout_product_on_fixed_sale.py
+++ b/saleor/tests/e2e/checkout/discounts/sales/test_checkout_product_on_fixed_sale.py
@@ -1,5 +1,6 @@
import pytest
+from ......product.tasks import recalculate_discounted_price_for_products_task
from ....product.utils.preparing_product import prepare_product
from ....sales.utils import (
create_sale,
@@ -91,6 +92,9 @@ def test_checkout_products_on_fixed_sale_core_1002(
sale_discount_type="FIXED",
sale_discount_value=3,
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
# Step 1 - checkoutCreate for product on sale
lines = [
diff --git a/saleor/tests/e2e/checkout/discounts/sales/test_checkout_product_on_percentage_sale.py b/saleor/tests/e2e/checkout/discounts/sales/test_checkout_product_on_percentage_sale.py
index ec9daf11a1..d15e3a228c 100644
--- a/saleor/tests/e2e/checkout/discounts/sales/test_checkout_product_on_percentage_sale.py
+++ b/saleor/tests/e2e/checkout/discounts/sales/test_checkout_product_on_percentage_sale.py
@@ -1,5 +1,6 @@
import pytest
+from ......product.tasks import recalculate_discounted_price_for_products_task
from ....product.utils.preparing_product import prepare_product
from ....sales.utils import (
create_sale,
@@ -92,6 +93,10 @@ def test_checkout_products_on_percentage_sale_core_1004(
sale_discount_value=3,
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - checkoutCreate for product on sale
lines = [
{
diff --git a/saleor/tests/e2e/checkout/discounts/test_checkout_calculate_correct_discount_for_sale_and_voucher.py b/saleor/tests/e2e/checkout/discounts/test_checkout_calculate_correct_discount_for_sale_and_voucher.py
index 378878b35b..a6120932e9 100644
--- a/saleor/tests/e2e/checkout/discounts/test_checkout_calculate_correct_discount_for_sale_and_voucher.py
+++ b/saleor/tests/e2e/checkout/discounts/test_checkout_calculate_correct_discount_for_sale_and_voucher.py
@@ -1,5 +1,6 @@
import pytest
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ...product.utils.preparing_product import prepare_product
from ...sales.utils import create_sale, create_sale_channel_listing, sale_catalogues_add
from ...shop.utils.preparing_shop import prepare_default_shop
@@ -154,6 +155,10 @@ def test_checkout_calculate_discount_for_sale_and_voucher_1014(
voucher_discount_value,
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create checkout for product on sale
lines = [
{"variantId": product_variant_id, "quantity": 1},
diff --git a/saleor/tests/e2e/checkout/discounts/test_checkout_with_promotion_and_voucher.py b/saleor/tests/e2e/checkout/discounts/test_checkout_with_promotion_and_voucher.py
index 3652876b2d..7905c26d1e 100644
--- a/saleor/tests/e2e/checkout/discounts/test_checkout_with_promotion_and_voucher.py
+++ b/saleor/tests/e2e/checkout/discounts/test_checkout_with_promotion_and_voucher.py
@@ -1,5 +1,6 @@
import pytest
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ...product.utils.preparing_product import prepare_product
from ...promotions.utils import create_promotion, create_promotion_rule
from ...shop.utils.preparing_shop import prepare_default_shop
@@ -178,6 +179,10 @@ def test_checkout_with_promotion_and_voucher_CORE_2107(
voucher_discount_value,
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create checkout for product with promotion
lines = [
{"variantId": product_variant_id, "quantity": 1},
diff --git a/saleor/tests/e2e/orders/discounts/test_apply_better_promotion_to_product.py b/saleor/tests/e2e/orders/discounts/test_apply_better_promotion_to_product.py
index 3dd41986a9..2a4295b78b 100644
--- a/saleor/tests/e2e/orders/discounts/test_apply_better_promotion_to_product.py
+++ b/saleor/tests/e2e/orders/discounts/test_apply_better_promotion_to_product.py
@@ -1,5 +1,6 @@
import pytest
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils import get_product
from ...product.utils.preparing_product import prepare_product
@@ -119,6 +120,10 @@ def test_apply_best_promotion_to_product_core_2105(
product_id,
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Get product and check if it is on promotion
product_data = get_product(e2e_staff_api_client, product_id, channel_slug)
diff --git a/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py b/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py
index 702d3930d2..13edade740 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py
@@ -1,5 +1,6 @@
import pytest
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...promotions.utils import create_promotion, create_promotion_rule
@@ -70,6 +71,10 @@ def test_order_products_on_percentage_promotion_CORE_2103(
assert promotion_rule["channels"][0]["id"] == channel_id
assert product_predicate[0] == product_id
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create a draft order for a product with fixed promotion
input = {
"channelId": channel_id,
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_from_the_same_category_on_fixed_promotion.py b/saleor/tests/e2e/orders/discounts/test_order_products_from_the_same_category_on_fixed_promotion.py
index 33b5e8692e..8ab0598515 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_from_the_same_category_on_fixed_promotion.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_from_the_same_category_on_fixed_promotion.py
@@ -1,5 +1,6 @@
import pytest
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils import (
create_category,
@@ -177,6 +178,10 @@ def test_order_products_from_category_on_fixed_promotion_CORE_2106(
promotion_rule_name,
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create a draft order for a product with fixed promotion
input = {
"channelId": channel_id,
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_promotion.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_promotion.py
index 91c39e7521..6b44467456 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_promotion.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_promotion.py
@@ -1,5 +1,6 @@
import pytest
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...promotions.utils import create_promotion, create_promotion_rule
@@ -72,6 +73,10 @@ def test_order_products_on_fixed_promotion_CORE_2101(
assert promotion_rule["channels"][0]["id"] == channel_id
assert product_predicate[0] == product_id
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create a draft order for a product with fixed promotion
input = {
"channelId": channel_id,
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_sale.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_sale.py
index d3822fc4b3..f8f93447db 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_sale.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_sale.py
@@ -1,5 +1,6 @@
import pytest
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...sales.utils import create_sale, create_sale_channel_listing, sale_catalogues_add
@@ -89,6 +90,10 @@ def test_order_products_on_fixed_sale_CORE_1001(
sale_discount_value=30,
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create a draft order
input = {
"channelId": channel_id,
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_percentage_sale.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_percentage_sale.py
index 8192f76bb4..e6b719f323 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_percentage_sale.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_percentage_sale.py
@@ -1,5 +1,6 @@
import pytest
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...sales.utils import create_sale, create_sale_channel_listing, sale_catalogues_add
@@ -89,6 +90,10 @@ def test_order_products_on_percentage_sale_CORE_1003(
sale_discount_value=30,
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create a draft order
input = {
"channelId": channel_id,
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
index 11bf9b6634..8965e3f9a0 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
@@ -3,6 +3,7 @@ from decimal import Decimal
import pytest
from .....core.prices import quantize_price
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...promotions.utils import create_promotion, create_promotion_rule
@@ -78,6 +79,10 @@ def test_order_products_on_promotion_and_manual_order_discount_CORE_2108(
assert product_predicate[0] == product_id
currency = "USD"
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create a draft order for a product with fixed promotion
input = {
"channelId": channel_id,
diff --git a/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py b/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py
index 7971a9d197..a6f5c01302 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py
@@ -4,6 +4,7 @@ import pytest
from django.utils import timezone
from freezegun import freeze_time
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils import get_product
from ...product.utils.preparing_product import prepare_product
@@ -53,6 +54,10 @@ def test_order_promotion_not_applied_when_not_within_time_range_CORE_2110(
e2e_staff_api_client, warehouse_id, channel_id, variant_price=20
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create promotion lasting for a specific time range
promotion_type = "CATALOGUE"
promotion_data = create_promotion(
diff --git a/saleor/tests/e2e/orders/discounts/test_order_promotion_still_applied_to_the_order_when_promotion_is_removed.py b/saleor/tests/e2e/orders/discounts/test_order_promotion_still_applied_to_the_order_when_promotion_is_removed.py
index aaec1a842b..8bb5ca0197 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_promotion_still_applied_to_the_order_when_promotion_is_removed.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_promotion_still_applied_to_the_order_when_promotion_is_removed.py
@@ -1,5 +1,6 @@
import pytest
+from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...product.utils.product_query import get_product
@@ -78,6 +79,10 @@ def test_order_promotion_still_applied_to_the_order_when_promotion_is_removed_CO
assert promotion_rule["channels"][0]["id"] == channel_id
assert product_predicate[0] == product_id
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Create a draft order for a product with fixed promotion
input = {
"channelId": channel_id,
@@ -118,6 +123,11 @@ def test_order_promotion_still_applied_to_the_order_when_promotion_is_removed_CO
# Step 4 - Remove the promotion and check the product is not on promotion
delete_promotion(e2e_staff_api_client, promotion_id)
+
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
data = promotion_query(e2e_staff_api_client, promotion_id)
assert data["promotion"] is None
product_data = get_product(e2e_staff_api_client, product_id, channel_slug)
diff --git a/saleor/tests/e2e/product/test_product_no_longer_on_promotion_when_promotion_is_removed.py b/saleor/tests/e2e/product/test_product_no_longer_on_promotion_when_promotion_is_removed.py
index 6a7beaf49a..52a2693c5a 100644
--- a/saleor/tests/e2e/product/test_product_no_longer_on_promotion_when_promotion_is_removed.py
+++ b/saleor/tests/e2e/product/test_product_no_longer_on_promotion_when_promotion_is_removed.py
@@ -1,5 +1,6 @@
import pytest
+from ....product.tasks import recalculate_discounted_price_for_products_task
from ..promotions.utils import (
create_promotion,
create_promotion_rule,
@@ -69,6 +70,10 @@ def test_product_no_longer_on_promotion_when_promotion_is_removed_CORE_2114(
assert promotion_rule["channels"][0]["id"] == channel_id
assert product_predicate[0] == product_id
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Check product is on promotion
product_data = get_product(e2e_staff_api_client, product_id, channel_slug)
assert product_data["id"] == product_id
@@ -83,6 +88,10 @@ def test_product_no_longer_on_promotion_when_promotion_is_removed_CORE_2114(
data = promotion_query(e2e_staff_api_client, promotion_id)
assert data["promotion"] is None
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 3 - Check product in no longer on promotion
product_data = get_product(e2e_staff_api_client, product_id, channel_slug)
assert product_data["id"] == product_id
diff --git a/saleor/tests/e2e/promotions/test_staff_can_change_catalog_predicate.py b/saleor/tests/e2e/promotions/test_staff_can_change_catalog_predicate.py
index 75e720586c..f4261e30c9 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_change_catalog_predicate.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_change_catalog_predicate.py
@@ -1,5 +1,6 @@
import pytest
+from ....product.tasks import recalculate_discounted_price_for_products_task
from ..product.utils import (
create_collection,
create_collection_channel_listing,
@@ -113,6 +114,10 @@ def test_staff_can_change_catalogue_predicate_core_2112(
}
update_promotion_rule(e2e_staff_api_client, promotion_rule_id, input)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 3 Check if promotion is applied to new variant
product_data = get_product(e2e_staff_api_client, product_id, channel_slug)
first_variant = product_data["variants"][0]
diff --git a/saleor/tests/e2e/promotions/test_staff_can_change_channel_in_promotion_rule.py b/saleor/tests/e2e/promotions/test_staff_can_change_channel_in_promotion_rule.py
index 2692ad3aba..8ece704de8 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_change_channel_in_promotion_rule.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_change_channel_in_promotion_rule.py
@@ -1,5 +1,6 @@
import pytest
+from ....product.tasks import recalculate_discounted_price_for_products_task
from ..product.utils import (
get_product,
raw_create_product_channel_listing,
@@ -155,6 +156,10 @@ def test_staff_can_change_promotion_rule_channel_core_2113(
},
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 2 Check if promotion is applied for product on second channel
product_data_channel_2 = get_product(
e2e_staff_api_client, product_id, pl_channel_slug
diff --git a/saleor/tests/e2e/promotions/test_staff_can_change_reward_value_type_in_promotion_rule.py b/saleor/tests/e2e/promotions/test_staff_can_change_reward_value_type_in_promotion_rule.py
index 001dae24d6..3f8bfca7ee 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_change_reward_value_type_in_promotion_rule.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_change_reward_value_type_in_promotion_rule.py
@@ -1,5 +1,6 @@
import pytest
+from ....product.tasks import recalculate_discounted_price_for_products_task
from ..product.utils import get_product
from ..product.utils.preparing_product import prepare_product
from ..shop.utils.preparing_shop import prepare_default_shop
@@ -73,6 +74,10 @@ def test_staff_can_change_reward_value_type_in_promotion_rule_core_2117(
channel_id=channel_id,
)
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 1 - Get product and check prices
product_data = get_product(e2e_staff_api_client, product_id, channel_slug)
variant = product_data["variants"][0]
@@ -88,6 +93,10 @@ def test_staff_can_change_reward_value_type_in_promotion_rule_core_2117(
assert rule_data["rewardValueType"] == "FIXED"
assert rule_data["rewardValue"] == fixed_reward_value
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 3 - Get product and check prices
product_data = get_product(e2e_staff_api_client, product_id, channel_slug)
variant = product_data["variants"][0]
diff --git a/saleor/tests/e2e/promotions/test_staff_can_create_promotion_for_collections.py b/saleor/tests/e2e/promotions/test_staff_can_create_promotion_for_collections.py
index 578270c83f..972df2f6f6 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_create_promotion_for_collections.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_create_promotion_for_collections.py
@@ -1,5 +1,6 @@
import pytest
+from ....product.tasks import recalculate_discounted_price_for_products_task
from ..product.utils import (
create_category,
create_collection,
@@ -120,6 +121,10 @@ def test_create_promotion_for_collection_core_2109(
assert promotion_rule["channels"][0]["id"] == channel_id
assert collection_predicate["ids"][0] == collection_id
+ # prices are updated in the background, we need to force it to retrieve the correct
+ # ones
+ recalculate_discounted_price_for_products_task()
+
# Step 2 Get product and verify that is on sale
product_data = get_product(e2e_staff_api_client, product_id, channel_slug)
variant_discount = round(float(variant_price) * discount_value / 100, 2)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index a9fd83bed5..17c0c3a08f 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1,5 +1,6 @@
import datetime
import itertools
+import random
import uuid
from collections import namedtuple
from contextlib import contextmanager
@@ -8849,7 +8850,7 @@ def async_subscription_webhooks_with_root_objects(
@pytest.fixture
-def lots_of_products_with_variants(product_type):
+def lots_of_products_with_variants(product_type, channel_USD):
def chunks(iterable, size):
it = iter(iterable)
chunk = tuple(itertools.islice(it, size))
@@ -8864,19 +8865,41 @@ def lots_of_products_with_variants(product_type):
for batch in chunks(range(products_count), 500):
batch_len = len(batch)
variants = []
- for product in Product.objects.bulk_create(
- [
- Product(
- name=i,
- slug=next(slug_generator),
- product_type_id=product_type.pk,
+ product_listings = []
+ products = [
+ Product(
+ name=i,
+ slug=next(slug_generator),
+ product_type_id=product_type.pk,
+ )
+ for i in range(batch_len)
+ ]
+ for product in Product.objects.bulk_create(products):
+ product_listings.append(
+ ProductChannelListing(
+ channel=channel_USD,
+ product=product,
+ visible_in_listings=True,
+ available_for_purchase_at="2022-01-01",
+ currency=channel_USD.currency_code,
)
- for i in range(batch_len)
- ]
- ):
+ )
for x in range(variants_per_product):
variant = ProductVariant(name=x, product_id=product.id)
variants.append(variant)
ProductVariant.objects.bulk_create(variants)
-
+ variant_listings = []
+ for variant in variants:
+ price = random.randint(1, 100)
+ variant_listings.append(
+ ProductVariantChannelListing(
+ variant=variant,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ price_amount=price,
+ discounted_price_amount=price,
+ )
+ )
+ ProductVariantChannelListing.objects.bulk_create(variant_listings)
+ ProductChannelListing.objects.bulk_create(product_listings)
return Product.objects.all()