Skip to content

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

Fix rule variants recalculation (#15067)

Iga Karbowiake88db5f13968
diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.py
index ab41a46016..460fc5d918 100644
--- a/saleor/discount/tasks.py
+++ b/saleor/discount/tasks.py
@@ -98,7 +98,7 @@ def handle_promotion_toggle():
if product_ids:
# Recalculate discounts of affected products
update_products_discounted_prices_for_promotion_task.delay(
- product_ids, rule_ids
+ product_ids, rule_ids=rule_ids
)
starting_promotion_ids = ", ".join(
diff --git a/saleor/discount/tests/test_tasks.py b/saleor/discount/tests/test_tasks.py
index f4ce9dbcd4..63c541221c 100644
--- a/saleor/discount/tests/test_tasks.py
+++ b/saleor/discount/tests/test_tasks.py
@@ -190,7 +190,7 @@ def test_handle_promotion_toggle(
product_list[2].id,
}
- assert {rule_id for rule_id in args[1]} == {
+ assert {rule_id for rule_id in kwargs["rule_ids"]} == {
rules[0].id,
rules[2].id,
}
diff --git a/saleor/product/tests/test_fetch_variants_for_promotion_rules.py b/saleor/product/tests/test_fetch_variants_for_promotion_rules.py
index 74039b7d65..c3029b7dd4 100644
--- a/saleor/product/tests/test_fetch_variants_for_promotion_rules.py
+++ b/saleor/product/tests/test_fetch_variants_for_promotion_rules.py
@@ -81,3 +81,19 @@ def test_fetch_variants_for_promotion_rules_no_applicable_variants(
# then
rule.refresh_from_db()
assert rule.variants.count() == 0
+
+
+def test_fetch_variants_for_promotion_rules_relation_already_exist(
+ promotion,
+):
+ # given
+ PromotionRuleVariant = PromotionRule.variants.through
+ rule = PromotionRuleVariant.objects.first().promotionrule
+ assert rule.variants.count() > 0
+
+ # when
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+
+ # then
+ rule.refresh_from_db()
+ assert rule.variants.count() > 0
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index b063692ed5..b80da5682c 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -64,9 +64,9 @@ def fetch_variants_for_promotion_rules(
promotion_rule_variants.extend(
[
PromotionRuleVariant(
- promotionrule_id=rule.pk, productvariant_id=variant.pk
+ promotionrule_id=rule.pk, productvariant_id=variant_id
)
- for variant in variants
+ for variant_id in set(variants.values_list("pk", flat=True))
]
)
@@ -75,4 +75,6 @@ def fetch_variants_for_promotion_rules(
PromotionRuleVariant.objects.filter(
Exists(rules.filter(pk=OuterRef("promotionrule_id")))
).delete()
- PromotionRuleVariant.objects.bulk_create(promotion_rule_variants)
+ PromotionRuleVariant.objects.bulk_create(
+ promotion_rule_variants, ignore_conflicts=True
+ )