Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Drop sale models. (#14258)
Piotr Zabieglikb17f360e4e52
diff --git a/conftest.py b/conftest.pyindex 12ea1fed2f..1aaf7b41fb 100644--- a/conftest.py+++ b/conftest.py@@ -20,7 +20,6 @@ pytest_plugins = ["saleor.graphql.order.tests.benchmark.fixtures","saleor.graphql.giftcard.tests.benchmark.fixtures","saleor.graphql.webhook.tests.benchmark.fixtures",- "saleor.graphql.webhook.tests.fixtures","saleor.plugins.webhook.tests.subscription_webhooks.fixtures","saleor.tax.tests.fixtures",]diff --git a/saleor/checkout/tests/test_base_calculations.py b/saleor/checkout/tests/test_base_calculations.pyindex 459a69192b..33e084a222 100644--- a/saleor/checkout/tests/test_base_calculations.py+++ b/saleor/checkout/tests/test_base_calculations.py@@ -4,7 +4,6 @@ from prices import Money, TaxedMoneyfrom ...discount import DiscountValueType, RewardValueType, VoucherTypefrom ...discount.models import PromotionRule-from ...discount.tests.sale_converter import convert_sales_to_promotionsfrom ...plugins.manager import get_plugins_managerfrom ...tax.utils import calculate_tax_ratefrom ..base_calculations import (@@ -60,7 +59,6 @@ def test_calculate_base_line_unit_price_with_variant_on_sale(checkout_with_item_on_sale,):# given- convert_sales_to_promotions()checkout = checkout_with_item_on_salecheckout_lines_info, _ = fetch_checkout_lines(checkout_with_item_on_sale)@@ -86,8 +84,6 @@ def test_calculate_base_line_unit_price_with_variant_on_sale_custom_price(line.price_override = price_overrideline.save(update_fields=["price_override"])- convert_sales_to_promotions()-checkout_lines_info, _ = fetch_checkout_lines(checkout_with_item_on_sale)checkout_line_info = checkout_lines_info[0]@@ -101,7 +97,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale_custom_price(def test_calculate_base_line_unit_price_with_variant_on_promotion(- checkout_with_item_on_promotion, discount_info, category+ checkout_with_item_on_promotion, category):# givencheckout = checkout_with_item_on_promotion@@ -116,7 +112,7 @@ def test_calculate_base_line_unit_price_with_variant_on_promotion(def test_calculate_base_line_unit_price_with_variant_on_promotion_custom_price(- checkout_with_item_on_promotion, discount_info, category+ checkout_with_item_on_promotion, category):# givencheckout = checkout_with_item_on_promotion@@ -351,7 +347,7 @@ def test_calculate_base_line_unit_price_with_discounts_once_per_order_custom_pridef test_calculate_base_line_unit_price_with_variant_on_sale_and_voucher(- checkout_with_single_item, discount_info, category, voucher, channel_USD+ checkout_with_single_item, category, voucher, channel_USD):# givencheckout_line = checkout_with_single_item.lines.first()@@ -436,7 +432,7 @@ def test_calculate_base_line_total_price(checkout_with_single_item):def test_calculate_base_line_total_price_with_variant_on_sale(- checkout_with_item_on_sale, discount_info+ checkout_with_item_on_sale,):# givenquantity = 3@@ -641,7 +637,7 @@ def test_calculate_base_line_total_price_with_discounts_apply_once_per_order(def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher(- checkout_with_item_on_sale, discount_info, category, voucher, channel_USD+ checkout_with_item_on_sale, category, voucher, channel_USD):# givenquantity = 3@@ -661,8 +657,6 @@ def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher(voucher_channel_listing.discount = voucher_amountvoucher_channel_listing.save()- convert_sales_to_promotions()-checkout.voucher_code = voucher.codecheckout_lines_info, _ = fetch_checkout_lines(checkout)@@ -677,7 +671,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher(def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher_applied_once(- checkout_with_item_on_sale, discount_info, category, voucher, channel_USD+ checkout_with_item_on_sale, category, voucher, channel_USD):# givenquantity = 3@@ -699,8 +693,6 @@ def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher_applievoucher_channel_listing.discount = voucher_amountvoucher_channel_listing.save()- convert_sales_to_promotions()-checkout_lines_info, _ = fetch_checkout_lines(checkout)checkout_line_info = checkout_lines_info[0]@@ -748,7 +740,7 @@ def test_calculate_base_line_total_price_with_variant_on_promotion_and_voucher(def test_calculate_base_line_total_price_variant_on_promotion_and_voucher_applied_once(- checkout_with_item_on_promotion, discount_info, category, voucher, channel_USD+ checkout_with_item_on_promotion, category, voucher, channel_USD):# givenquantity = 3diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex cf99fa3498..f86fc12828 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -20,7 +20,6 @@ from ...discount.models import (Voucher,VoucherChannelListing,)-from ...discount.tests.sale_converter import convert_sales_to_promotionsfrom ...payment.models import Paymentfrom ...plugins.manager import get_plugins_managerfrom ...product.models import VariantChannelListingPromotionRule@@ -1211,8 +1210,6 @@ def test_recalculate_checkout_discount_with_sale(lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)- convert_sales_to_promotions()-# whenrecalculate_checkout_discount(manager, checkout_info, lines)diff --git a/saleor/core/management/commands/cleardb.py b/saleor/core/management/commands/cleardb.pyindex d5c4d5a13c..f150989ebe 100644--- a/saleor/core/management/commands/cleardb.py+++ b/saleor/core/management/commands/cleardb.py@@ -12,7 +12,7 @@ from django.db.models import Qfrom ....account.models import Userfrom ....attribute.models import Attributefrom ....checkout.models import Checkout-from ....discount.models import Sale, Voucher+from ....discount.models import Promotion, Voucherfrom ....giftcard.models import GiftCardfrom ....order.models import Orderfrom ....page.models import Page, PageType@@ -73,8 +73,8 @@ class Command(BaseCommand):Collection.objects.all().delete()self.stdout.write("Removed collections")- Sale.objects.all().delete()- self.stdout.write("Removed sales")+ Promotion.objects.all().delete()+ self.stdout.write("Removed promotions")ShippingMethod.objects.all().delete()self.stdout.write("Removed shipping methods")diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.pyindex 172931c0ac..11eed50b8b 100644--- a/saleor/discount/__init__.py+++ b/saleor/discount/__init__.py@@ -1,10 +1,10 @@from dataclasses import dataclass-from typing import TYPE_CHECKING, Dict, List, Set, Union+from typing import TYPE_CHECKING, Listfrom django.db.models import QuerySetif TYPE_CHECKING:- from .models import PromotionRule, Sale, SaleChannelListing+ from .models import PromotionRuleclass DiscountValueType:@@ -73,16 +73,6 @@ class PromotionEvents:]-@dataclass-class DiscountInfo:- sale: "Sale"- channel_listings: Dict[str, "SaleChannelListing"]- product_ids: Union[List[int], Set[int]]- category_ids: Union[List[int], Set[int]]- collection_ids: Union[List[int], Set[int]]- variants_ids: Union[List[int], Set[int]]--@dataclassclass PromotionRuleInfo:rule: "PromotionRule"diff --git a/saleor/discount/migrations/0051_detach_sale_from_permission.py b/saleor/discount/migrations/0051_detach_sale_from_permission.pynew file mode 100644index 0000000000..ff564b4bb9--- /dev/null+++ b/saleor/discount/migrations/0051_detach_sale_from_permission.py@@ -0,0 +1,95 @@+from django.contrib.contenttypes.management import create_contenttypes+from django.db import DEFAULT_DB_ALIAS, migrations+from django.apps import apps as global_apps+from django.contrib.auth import get_permission_codename+++def handle_permissions(apps, _schema_editor):+ app_config = apps.get_app_config("discount")+ app_config.models_module = True+ create_permissions(app_config, apps=apps)+ app_config.models_module = None+++def create_permissions(+ app_config,+ verbosity=0,+ interactive=True,+ using=DEFAULT_DB_ALIAS,+ apps=global_apps,+ **kwargs+):+ create_contenttypes(+ app_config,+ verbosity=verbosity,+ interactive=interactive,+ using=using,+ apps=apps,+ **kwargs,+ )++ ContentType = apps.get_model("contenttypes", "ContentType")+ Permission = apps.get_model("permission", "Permission")+ searched_perms = []+ ctypes = set()+ for model in app_config.get_models():+ ctype = ContentType.objects.db_manager(using).get_for_model(+ model, for_concrete_model=False+ )++ ctypes.add(ctype)+ for perm in _get_all_permissions(model._meta):+ searched_perms.append((ctype, perm))+ all_perms = set(+ Permission.objects.using(using)+ .filter(+ content_type__in=ctypes,+ )+ .values_list("content_type", "codename")+ )+ perms = [+ Permission(codename=codename, name=name, content_type=ct)+ for ct, (codename, name) in searched_perms+ if (ct.pk, codename) not in all_perms+ ]+ Permission.objects.using(using).bulk_create(perms)+++def _get_all_permissions(opts): # noqa: D200, D212+ return [*_get_builtin_permissions(opts), *opts.permissions]+++def _get_builtin_permissions(opts): # noqa: D205, D212+ perms = []+ for action in opts.default_permissions:+ perms.append(+ (+ get_permission_codename(action, opts),+ "Can %s %s" % (action, opts.verbose_name_raw),+ )+ )+ return perms+++class Migration(migrations.Migration):+ dependencies = [+ ("discount", "0050_merge_20231004_1306"),+ ]++ operations = [+ migrations.RunPython(+ handle_permissions, reverse_code=migrations.RunPython.noop+ ),+ migrations.RunSQL(+ """+ update permission_permission+ set content_type_id = (+ select id+ from django_content_type+ where app_label = 'discount' and model='promotion'+ )+ where codename = 'manage_discounts'+ """,+ reverse_sql=migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/discount/migrations/0052_drop_sales_constraints.py b/saleor/discount/migrations/0052_drop_sales_constraints.pynew file mode 100644index 0000000000..6249906b97--- /dev/null+++ b/saleor/discount/migrations/0052_drop_sales_constraints.py@@ -0,0 +1,47 @@+from django.db import migrations++DROP_CONSTRAINTS_SQL = """+do $$+declare+ r record;+ tab text;+ tabs text[] := array[+ 'discount_sale_collections',+ 'discount_sale_categories',+ 'discount_sale_products',+ 'discount_sale_variants',+ 'discount_salechannellisting',+ 'discount_saletranslation',+ 'discount_sale'+ ];+begin+ ALTER TABLE discount_orderdiscount DROP CONSTRAINT IF EXISTS+ "discount_orderdiscount_sale_id_849ebbef_fk_discount_sale_id";+ ALTER TABLE discount_checkoutlinediscount DROP CONSTRAINT IF EXISTS+ "discount_checkoutlin_sale_id_b0964e58_fk_discount_";+ ALTER TABLE discount_orderlinediscount DROP CONSTRAINT IF EXISTS+ "discount_orderlinediscount_sale_id_d95994f8_fk_discount_sale_id";+ foreach tab in array tabs loop+ for r in (+ select constraint_name+ from information_schema.table_constraints+ where table_name=tab+ ) loop+ execute concat(+ 'ALTER TABLE '||tab||' DROP CONSTRAINT IF EXISTS "'||r.constraint_name||'"'+ );+ end loop;+ end loop;+end;+$$+"""+++class Migration(migrations.Migration):+ dependencies = [+ ("discount", "0051_detach_sale_from_permission"),+ ]++ operations = [+ migrations.RunSQL(DROP_CONSTRAINTS_SQL, reverse_sql=migrations.RunSQL.noop),+ ]diff --git a/saleor/discount/migrations/0053_drop_sales_indexes.py b/saleor/discount/migrations/0053_drop_sales_indexes.pynew file mode 100644index 0000000000..8c91cfc478--- /dev/null+++ b/saleor/discount/migrations/0053_drop_sales_indexes.py@@ -0,0 +1,81 @@+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False+ dependencies = [+ ("discount", "0052_drop_sales_constraints"),+ ]++ operations = [+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_sale_collections_sale_id_a912da4a";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY "+ '"discount_sale_collections_collection_id_f66df9d7";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_saletranslation_sale_id_36a69b0a";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_sale_categories_sale_id_2aeee4a7";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY "+ '"discount_sale_categories_category_id_64e132af";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_sale_products_sale_id_10e3a20f";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_sale_products_product_id_d42c9636";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_sale_created_c17254d6";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_sale_updated_at_1fb1171b";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY "+ '"discount_salechannellisting_channel_id_3319ed70";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY "+ '"discount_salechannellisting_sale_id_13a35e18";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_sale_variants_sale_id_50fc4c3a";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY "+ '"discount_sale_variants_productvariant_id_91fa5f1b";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY "+ '"discount_checkoutlinediscount_sale_id_b0964e58";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_orderlinediscount_sale_id_d95994f8";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.RunSQL(+ "DROP INDEX CONCURRENTLY " '"discount_orderdiscount_sale_id_849ebbef";',+ reverse_sql=migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/discount/migrations/0054_drop_sales_models.py b/saleor/discount/migrations/0054_drop_sales_models.pynew file mode 100644index 0000000000..577d27d640--- /dev/null+++ b/saleor/discount/migrations/0054_drop_sales_models.py@@ -0,0 +1,71 @@+from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("discount", "0053_drop_sales_indexes"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveField(+ model_name="sale",+ name="categories",+ ),+ migrations.RemoveField(+ model_name="sale",+ name="collections",+ ),+ migrations.RemoveField(+ model_name="sale",+ name="products",+ ),+ migrations.RemoveField(+ model_name="sale",+ name="variants",+ ),+ migrations.AlterUniqueTogether(+ name="salechannellisting",+ unique_together=None,+ ),+ migrations.RemoveField(+ model_name="salechannellisting",+ name="channel",+ ),+ migrations.RemoveField(+ model_name="salechannellisting",+ name="sale",+ ),+ migrations.AlterUniqueTogether(+ name="saletranslation",+ unique_together=None,+ ),+ migrations.RemoveField(+ model_name="saletranslation",+ name="sale",+ ),+ migrations.RemoveField(+ model_name="checkoutlinediscount",+ name="sale",+ ),+ migrations.RemoveField(+ model_name="orderdiscount",+ name="sale",+ ),+ migrations.RemoveField(+ model_name="orderlinediscount",+ name="sale",+ ),+ migrations.DeleteModel(+ name="Sale",+ ),+ migrations.DeleteModel(+ name="SaleChannelListing",+ ),+ migrations.DeleteModel(+ name="SaleTranslation",+ ),+ ],+ ),+ ]diff --git a/saleor/discount/models.py b/saleor/discount/models.pyindex 7c6356ffa5..363f5267bc 100644--- a/saleor/discount/models.py+++ b/saleor/discount/models.py@@ -22,7 +22,6 @@ from ..core.models import ModelWithMetadatafrom ..core.utils.editorjs import clean_editor_jsfrom ..core.utils.json_serializer import CustomJsonEncoderfrom ..core.utils.translations import Translation-from ..permission.enums import DiscountPermissionsfrom . import (DiscountType,DiscountValueType,@@ -228,20 +227,6 @@ class VoucherCustomer(models.Model):unique_together = (("voucher", "customer_email"),)-class SaleQueryset(models.QuerySet["Sale"]):- def active(self, date=None):- if date is None:- date = timezone.now()- return self.filter(- Q(end_date__isnull=True) | Q(end_date__gte=date), start_date__lte=date- )-- def expired(self, date=None):- if date is None:- date = timezone.now()- return self.filter(end_date__lt=date, start_date__lt=date)--class VoucherTranslation(Translation):voucher = models.ForeignKey(Voucher, related_name="translations", on_delete=models.CASCADE@@ -259,113 +244,6 @@ class VoucherTranslation(Translation):return {"name": self.name}-SaleManager = models.Manager.from_queryset(SaleQueryset)---class Sale(ModelWithMetadata):- name = models.CharField(max_length=255)- type = models.CharField(- max_length=10,- choices=DiscountValueType.CHOICES,- default=DiscountValueType.FIXED,- )- categories = models.ManyToManyField("product.Category", blank=True)- collections = models.ManyToManyField("product.Collection", blank=True)- products = models.ManyToManyField("product.Product", blank=True)- variants = models.ManyToManyField("product.ProductVariant", blank=True)- start_date = models.DateTimeField(default=timezone.now)- end_date = models.DateTimeField(null=True, blank=True)- created_at = models.DateTimeField(auto_now_add=True, db_index=True)- updated_at = models.DateTimeField(auto_now=True, db_index=True)-- notification_sent_datetime = models.DateTimeField(null=True, blank=True)-- objects = SaleManager()-- class Meta:- ordering = ("name", "pk")- app_label = "discount"- permissions = (- (- DiscountPermissions.MANAGE_DISCOUNTS.codename,- "Manage sales and vouchers.",- ),- )-- def __repr__(self):- return f"Sale(name={str(self.name)}, type={self.get_type_display()})"-- def __str__(self):- return self.name-- def get_discount(self, sale_channel_listing):- if not sale_channel_listing:- raise NotApplicable("This sale is not assigned to this channel.")- if self.type == DiscountValueType.FIXED:- discount_amount = Money(- sale_channel_listing.discount_value, sale_channel_listing.currency- )- return partial(fixed_discount, discount=discount_amount)- if self.type == DiscountValueType.PERCENTAGE:- return partial(- percentage_discount,- percentage=sale_channel_listing.discount_value,- rounding=ROUND_HALF_UP,- )- raise NotImplementedError("Unknown discount type")-- def is_active(self, date=None):- if date is None:- date = datetime.now(pytz.utc)- return (not self.end_date or self.end_date >= date) and self.start_date <= date---class SaleChannelListing(models.Model):- sale = models.ForeignKey(- Sale,- null=False,- blank=False,- related_name="channel_listings",- on_delete=models.CASCADE,- )- channel = models.ForeignKey(- Channel,- null=False,- blank=False,- related_name="sale_listings",- on_delete=models.CASCADE,- )- discount_value = models.DecimalField(- max_digits=settings.DEFAULT_MAX_DIGITS,- decimal_places=settings.DEFAULT_DECIMAL_PLACES,- default=Decimal("0.0"),- )- currency = models.CharField(- max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,- )-- class Meta:- unique_together = [["sale", "channel"]]- ordering = ("pk",)---class SaleTranslation(Translation):- name = models.CharField(max_length=255, null=True, blank=True)- sale = models.ForeignKey(- Sale, related_name="translations", on_delete=models.CASCADE- )-- class Meta:- ordering = ("language_code", "name", "pk")- unique_together = (("language_code", "sale"),)-- def get_translated_object_id(self):- return "Sale", self.sale_id-- def get_translated_keys(self):- return {"name": self.name}--class PromotionQueryset(models.QuerySet["Promotion"]):def active(self, date=None):if date is None:@@ -522,9 +400,6 @@ class BaseDiscount(models.Model):name = models.CharField(max_length=255, null=True, blank=True)translated_name = models.CharField(max_length=255, null=True, blank=True)reason = models.TextField(blank=True, null=True)- sale = models.ForeignKey(- Sale, related_name="+", blank=True, null=True, on_delete=models.SET_NULL- )promotion_rule = models.ForeignKey(PromotionRule,related_name="+",diff --git a/saleor/discount/tests/sale_converter.py b/saleor/discount/tests/sale_converter.pydeleted file mode 100644index 4037758882..0000000000--- a/saleor/discount/tests/sale_converter.py+++ /dev/null@@ -1,275 +0,0 @@-from dataclasses import dataclass-from typing import Dict, List--import graphene-from django.db.models import Exists, OuterRef--from ...product.models import Product-from ...product.utils.variant_prices import update_discounted_prices_for_promotion-from .. import DiscountType-from ..models import (- CheckoutLineDiscount,- OrderLineDiscount,- Promotion,- PromotionRule,- PromotionTranslation,- Sale,- SaleChannelListing,- SaleTranslation,-)--# The batch of size 100 takes ~0.9 second and consumes ~30MB memory at peak-BATCH_SIZE = 100---@dataclass-class RuleInfo:- rule: PromotionRule- sale_id: int- channel_id: int---def convert_sales_to_promotions():- sales_listing = SaleChannelListing.objects.order_by("sale_id")- for sale_listing_batch_pks in _channel_listing_in_batches(sales_listing):- sales_listing_batch = (- SaleChannelListing.objects.filter(pk__in=sale_listing_batch_pks)- .order_by("sale_id")- .prefetch_related(- "sale",- "sale__collections",- "sale__categories",- "sale__products",- "sale__variants",- )- )- sales_batch_pks = {listing.sale_id for listing in sales_listing_batch}-- saleid_promotion_map: Dict[int, Promotion] = {}- rules_info: List[RuleInfo] = []-- _migrate_sales_to_promotions(sales_batch_pks, saleid_promotion_map)- _migrate_sale_listing_to_promotion_rules(- sales_listing_batch,- saleid_promotion_map,- rules_info,- )- _migrate_translations(sales_batch_pks, saleid_promotion_map)-- rule_by_channel_and_sale = _get_rule_by_channel_sale(rules_info)- _migrate_checkout_line_discounts(sales_batch_pks, rule_by_channel_and_sale)- _migrate_order_line_discounts(sales_batch_pks, rule_by_channel_and_sale)-- # migrate sales not listed in any channel- sales_not_listed = Sale.objects.filter(- ~Exists(sales_listing.filter(sale_id=OuterRef("pk")))- ).order_by("pk")- for sales_batch_pks in _queryset_in_batches(sales_not_listed):- saleid_promotion_map = {}- _migrate_sales_to_promotions(sales_batch_pks, saleid_promotion_map)- _migrate_sales_to_promotion_rules(sales_batch_pks, saleid_promotion_map)- _migrate_translations(sales_batch_pks, saleid_promotion_map)-- # call price recalculation to create VariantChannelListingPromotionRule objects- update_discounted_prices_for_promotion(Product.objects.all())---def _migrate_sales_to_promotions(sales_pks, saleid_promotion_map):- if sales := Sale.objects.filter(pk__in=sales_pks).order_by("pk"):- for sale in sales:- saleid_promotion_map[sale.id] = _convert_sale_into_promotion(sale)- Promotion.objects.bulk_create(saleid_promotion_map.values())---def _convert_sale_into_promotion(sale):- return Promotion(- name=sale.name,- old_sale_id=sale.id,- start_date=sale.start_date,- end_date=sale.end_date,- created_at=sale.created_at,- updated_at=sale.updated_at,- metadata=sale.metadata,- private_metadata=sale.private_metadata,- last_notification_scheduled_at=sale.notification_sent_datetime,- )---def _migrate_sale_listing_to_promotion_rules(- sale_listings,- saleid_promotion_map,- rules_info,-):- if sale_listings:- for sale_listing in sale_listings:- promotion = saleid_promotion_map[sale_listing.sale_id]- rules_info.append(- RuleInfo(- rule=_create_promotion_rule(- sale_listing.sale,- promotion,- sale_listing.discount_value,- sale_listing.id,- ),- sale_id=sale_listing.sale_id,- channel_id=sale_listing.channel_id,- )- )-- promotion_rules = [rules_info.rule for rules_info in rules_info]- PromotionRule.objects.bulk_create(promotion_rules)-- PromotionRuleChannel = PromotionRule.channels.through- rules_channels = [- PromotionRuleChannel(- promotionrule_id=rule_info.rule.id, channel_id=rule_info.channel_id- )- for rule_info in rules_info- ]- PromotionRuleChannel.objects.bulk_create(rules_channels)---def _create_promotion_rule(- sale, promotion, discount_value=None, old_channel_listing_id=None-):- return PromotionRule(- promotion=promotion,- catalogue_predicate=create_catalogue_predicate_from_sale(sale),- reward_value_type=sale.type,- reward_value=discount_value,- old_channel_listing_id=old_channel_listing_id,- )---def create_catalogue_predicate_from_sale(sale):- collection_ids = [- graphene.Node.to_global_id("Collection", pk)- for pk in sale.collections.values_list("pk", flat=True)- ]- category_ids = [- graphene.Node.to_global_id("Category", pk)- for pk in sale.categories.values_list("pk", flat=True)- ]- product_ids = [- graphene.Node.to_global_id("Product", pk)- for pk in sale.products.values_list("pk", flat=True)- ]- variant_ids = [- graphene.Node.to_global_id("ProductVariant", pk)- for pk in sale.variants.values_list("pk", flat=True)- ]- return create_catalogue_predicate(- collection_ids, category_ids, product_ids, variant_ids- )---def create_catalogue_predicate(collection_ids, category_ids, product_ids, variant_ids):- predicate: Dict[str, List] = {"OR": []}- if collection_ids:- predicate["OR"].append({"collectionPredicate": {"ids": collection_ids}})- if category_ids:- predicate["OR"].append({"categoryPredicate": {"ids": category_ids}})- if product_ids:- predicate["OR"].append({"productPredicate": {"ids": product_ids}})- if variant_ids:- predicate["OR"].append({"variantPredicate": {"ids": variant_ids}})- if not predicate.get("OR"):- predicate = {}-- return predicate---def _migrate_sales_to_promotion_rules(sales_pks, saleid_promotion_map):- if sales := Sale.objects.filter(pk__in=sales_pks).order_by("pk"):- rules: List[PromotionRule] = []- for sale in sales:- promotion = saleid_promotion_map[sale.id]- rules.append(_create_promotion_rule(sale, promotion))- PromotionRule.objects.bulk_create(rules)---def _migrate_translations(sales_pks, saleid_promotion_map):- if sale_translations := SaleTranslation.objects.filter(sale_id__in=sales_pks):- promotion_translations = [- PromotionTranslation(- name=translation.name,- language_code=translation.language_code,- promotion=saleid_promotion_map[translation.sale_id],- )- for translation in sale_translations- ]- PromotionTranslation.objects.bulk_create(promotion_translations)---def _migrate_checkout_line_discounts(sales_pks, rule_by_channel_and_sale):- if checkout_line_discounts := CheckoutLineDiscount.objects.filter(- sale_id__in=sales_pks- ).select_related("line__checkout"):- for checkout_line_discount in checkout_line_discounts:- if checkout_line := checkout_line_discount.line:- channel_id = checkout_line.checkout.channel_id- sale_id = checkout_line_discount.sale_id- lookup = f"{channel_id}_{sale_id}"- if promotion_rule := rule_by_channel_and_sale.get(lookup):- checkout_line_discount.promotion_rule = promotion_rule- checkout_line_discount.type = DiscountType.PROMOTION-- CheckoutLineDiscount.objects.bulk_update(- checkout_line_discounts, ["promotion_rule_id", "type"]- )---def _migrate_order_line_discounts(sales_pks, rule_by_channel_and_sale):- if order_line_discounts := OrderLineDiscount.objects.filter(- sale_id__in=sales_pks- ).select_related("line__order"):- for order_line_discount in order_line_discounts:- if order_line := order_line_discount.line:- channel_id = order_line.order.channel_id- sale_id = order_line_discount.sale_id- lookup = f"{channel_id}_{sale_id}"- if promotion_rule := rule_by_channel_and_sale.get(lookup):- order_line_discount.promotion_rule = promotion_rule- order_line_discount.type = DiscountType.PROMOTION-- OrderLineDiscount.objects.bulk_update(- order_line_discounts, ["promotion_rule_id", "type"]- )---def _get_rule_by_channel_sale(rules_info):- return {- f"{rule_info.channel_id}_{rule_info.sale_id}": rule_info.rule- for rule_info in rules_info- }---def _channel_listing_in_batches(qs):- first_sale_id = 0- while True:- batch_1 = qs.values("sale_id").filter(sale_id__gt=first_sale_id)[:BATCH_SIZE]- if len(batch_1) == 0:- break- last_sale_id = batch_1[len(batch_1) - 1]["sale_id"]-- # `batch_2` extends initial `batch_1` to include all records from- # `SaleChannelListing` which refer to `last_sale_id`- batch_2 = qs.values("pk", "sale_id").filter(- sale_id__gt=first_sale_id, sale_id__lte=last_sale_id- )- pks = [v["pk"] for v in batch_2]- if not pks:- break- yield pks- first_sale_id = batch_2[len(batch_2) - 1]["sale_id"]---def _queryset_in_batches(queryset):- start_pk = 0- while True:- qs = queryset.values("pk").filter(pk__gt=start_pk)[:BATCH_SIZE]- pks = [v["pk"] for v in qs]- if not pks:- break- yield pks- start_pk = pks[-1]diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.pyindex 5a8d7053ac..721b7ea634 100644--- a/saleor/discount/tests/test_discounts.py+++ b/saleor/discount/tests/test_discounts.py@@ -8,18 +8,10 @@ from prices import Money, TaxedMoneyfrom ...discount.interface import VariantPromotionRuleInfofrom .. import DiscountValueType, RewardValueType, VoucherType-from ..models import (- NotApplicable,- Sale,- SaleChannelListing,- Voucher,- VoucherChannelListing,- VoucherCustomer,-)+from ..models import NotApplicable, Voucher, VoucherChannelListing, VoucherCustomerfrom ..utils import (add_voucher_usage_by_customer,decrease_voucher_usage,- fetch_catalogue_info,get_discount_name,get_discount_translated_name,increase_voucher_usage,@@ -406,106 +398,6 @@ def test_validate_voucher_not_applicable_once_per_customer(date_time_now = timezone.now()- "current_date, start_date, end_date, is_active",- (- (date_time_now, date_time_now, date_time_now + timedelta(days=1), True),- (- date_time_now + timedelta(days=1),- date_time_now,- date_time_now + timedelta(days=1),- True,- ),- (- date_time_now + timedelta(days=2),- date_time_now,- date_time_now + timedelta(days=1),- False,- ),- (- date_time_now - timedelta(days=2),- date_time_now,- date_time_now + timedelta(days=1),- False,- ),- (date_time_now, date_time_now, None, True),- (date_time_now + timedelta(weeks=10), date_time_now, None, True),- ),-)-def test_sale_active(current_date, start_date, end_date, is_active, channel_USD):- sale = Sale.objects.create(- type=DiscountValueType.FIXED, start_date=start_date, end_date=end_date- )- SaleChannelListing.objects.create(- sale=sale,- currency=channel_USD.currency_code,- channel=channel_USD,- discount_value=5,- )- sale_is_active = Sale.objects.active(date=current_date).exists()- assert is_active == sale_is_active---def test_get_fixed_sale_discount(sale):- # given- sale.type = DiscountValueType.FIXED- channel_listing = sale.channel_listings.get()-- # when- result = sale.get_discount(channel_listing).keywords-- # then- assert result["discount"] == Money(- channel_listing.discount_value, channel_listing.currency- )---def test_get_percentage_sale_discount(sale):- # given- sale.type = DiscountValueType.PERCENTAGE- channel_listing = sale.channel_listings.get()-- # when- result = sale.get_discount(channel_listing).keywords-- # then- assert result["percentage"] == channel_listing.discount_value---def test_get_unknown_sale_discount(sale):- sale.type = "unknown"- channel_listing = sale.channel_listings.get()-- with pytest.raises(NotImplementedError):- sale.get_discount(channel_listing)---def test_get_not_applicable_sale_discount(sale, channel_PLN):- sale.type = DiscountValueType.PERCENTAGE-- with pytest.raises(NotApplicable):- sale.get_discount(None)---def test_fetch_catalogue_info_for_sale_has_one_element_sets(sale):- category_ids = set(sale.categories.all().values_list("id", flat=True))- collection_ids = set(sale.collections.all().values_list("id", flat=True))- product_ids = set(sale.products.all().values_list("id", flat=True))- variant_ids = set(sale.variants.all().values_list("id", flat=True))-- catalogue_info = fetch_catalogue_info(sale)-- assert catalogue_info["categories"]- assert catalogue_info["collections"]- assert catalogue_info["products"]- assert catalogue_info["variants"]-- assert catalogue_info["categories"] == category_ids- assert catalogue_info["collections"] == collection_ids- assert catalogue_info["products"] == product_ids- assert catalogue_info["variants"] == variant_ids--def test_get_discount_name_only_rule_name(promotion):# givenpromotion.name = ""diff --git a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.pyindex a17e6b75be..d227c7020f 100644--- a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py+++ b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py@@ -94,7 +94,6 @@ def test_create_fixed_discount(assert discount_from_info.reason == discount_from_db.reason is Noneassert discount_from_info.promotion_rule == discount_from_db.promotion_rule == ruleassert discount_from_info.voucher == discount_from_db.voucher is None- assert discount_from_info.sale == discount_from_db.sale is Noneassert (discount_from_info.translated_name== discount_from_db.translated_name@@ -179,7 +178,6 @@ def test_create_fixed_discount_multiple_quantity_in_lines(assert discount_from_info.reason == discount_from_db.reason is Noneassert discount_from_info.promotion_rule == discount_from_db.promotion_rule == ruleassert discount_from_info.voucher == discount_from_db.voucher is None- assert discount_from_info.sale == discount_from_db.sale is Nonefor checkout_line_info in checkout_lines_with_multiple_quantity_info[1:]:assert not checkout_line_info.discounts@@ -329,7 +327,6 @@ def test_create_percentage_discount(checkout_lines_info, promotion_without_rulesassert discount_from_info.reason == discount_from_db.reason is Noneassert discount_from_info.promotion_rule == discount_from_db.promotion_rule == ruleassert discount_from_info.voucher == discount_from_db.voucher is None- assert discount_from_info.sale == discount_from_db.sale is Nonefor checkout_line_info in checkout_lines_info[1:]:assert not checkout_line_info.discounts@@ -411,7 +408,6 @@ def test_create_percentage_discount_multiple_quantity_in_lines(assert discount_from_info.reason == discount_from_db.reason is Noneassert discount_from_info.promotion_rule == discount_from_db.promotion_rule == ruleassert discount_from_info.voucher == discount_from_db.voucher is None- assert discount_from_info.sale == discount_from_db.sale is Nonefor checkout_line_info in checkout_lines_with_multiple_quantity_info[1:]:assert not checkout_line_info.discounts@@ -780,7 +776,6 @@ def test_create_percentage_discount_1_cent_variant_on_10_percentage_discount(assert discount_from_info.reason == discount_from_db.reason is Noneassert discount_from_info.promotion_rule == discount_from_db.promotion_rule == ruleassert discount_from_info.voucher == discount_from_db.voucher is None- assert discount_from_info.sale == discount_from_db.sale is Nonefor checkout_line_info in checkout_lines_info[1:]:assert not checkout_line_info.discountsdiff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 4ca32407ac..337df01fed 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -31,7 +31,6 @@ from .models import (NotApplicable,Promotion,PromotionRule,- Sale,)if TYPE_CHECKING:@@ -251,16 +250,6 @@ def get_products_voucher_discount(return total_amount-def fetch_catalogue_info(instance: Sale) -> CatalogueInfo:- catalogue_info: CatalogueInfo = defaultdict(set)- for sale_data in Sale.objects.filter(id=instance.id).values(*CATALOGUE_FIELDS):- for field in CATALOGUE_FIELDS:- if id := sale_data.get(field):- catalogue_info[field].add(id)-- return catalogue_info--def apply_discount_to_value(value: Decimal,value_type: str,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.pyindex 72eca357f4..e38bc264d3 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py@@ -12,7 +12,6 @@ from .....checkout.error_codes import CheckoutErrorCodefrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.utils import add_variant_to_checkout, set_external_shipping_idfrom .....discount import VoucherType-from .....discount.tests.sale_converter import convert_sales_to_promotionsfrom .....plugins.manager import get_plugins_managerfrom .....product.models import ProductVariantChannelListingfrom .....warehouse.models import Stock@@ -290,8 +289,6 @@ def test_checkout_add_voucher_code_checkout_with_sale(manager = get_plugins_manager()address = checkout.shipping_address- convert_sales_to_promotions()-lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)checkout_info.checkout.price_expiration = timezone.now()@@ -344,8 +341,6 @@ def test_checkout_add_specific_product_voucher_code_checkout_with_sale(checkout.price_expiration = timezone.now()- convert_sales_to_promotions()-lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)@@ -392,8 +387,6 @@ def test_checkout_add_products_voucher_code_checkout_with_sale(voucher.save()voucher.products.add(product)- convert_sales_to_promotions()-manager = get_plugins_manager()lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)@@ -463,8 +456,6 @@ def test_checkout_add_collection_voucher_code_checkout_with_sale(.discount_value)- convert_sales_to_promotions()-manager = get_plugins_manager()checkout.price_expiration = timezone.now()@@ -526,9 +517,6 @@ def test_checkout_add_category_code_checkout_with_sale()checkout.price_expiration = timezone.now()-- convert_sales_to_promotions()-manager = get_plugins_manager()lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.pyindex 67956d874e..a461f0b528 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py@@ -2149,11 +2149,11 @@ def test_checkout_complete_multiple_rules_applied().exists(), "Checkout should have been deleted"-def test_checkout_with_voucher_on_specific_product_complete_with_product_on_sale(+def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promotion(user_api_client,checkout_with_item_and_voucher_specific_products,voucher_specific_product_type,- sale,+ promotion_with_single_rule,address,shipping_method,transaction_events_generator,@@ -2174,8 +2174,14 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_salecheckout_line = checkout.lines.first()checkout_line_variant = checkout_line.variant+ checkout_line_variant_id = graphene.Node.to_global_id(+ "ProductVariant", checkout_line_variant.id+ )- sale.variants.add(checkout_line_variant)+ rule = promotion_with_single_rule.rules.first()+ predicate = {"variantPredicate": {"ids": [checkout_line_variant_id]}}+ rule.catalogue_predicate = predicate+ rule.save(update_fields=["catalogue_predicate"])manager = get_plugins_manager()lines, _ = fetch_checkout_lines(checkout)diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex ced0491b43..77970412c5 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -1625,9 +1625,7 @@ def test_checkout_prices_checkout_with_custom_prices()-def test_checkout_prices_with_sales(- user_api_client, checkout_with_item_on_sale, discount_info-):+def test_checkout_prices_with_sales(user_api_client, checkout_with_item_on_sale):# givenquery = QUERY_CHECKOUT_PRICEScheckout = checkout_with_item_on_salediff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.pyindex 6bd79540c7..1f55305378 100644--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py@@ -4,20 +4,10 @@ from ....plugins.manager import get_plugins_managerfrom ...core.utils import to_global_id_or_nonefrom ...tests.utils import get_graphql_content-# from .mutations.test_checkout_shipping_address_update import (-# MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE,-# )-# from .test_checkout_lines import MUTATION_CHECKOUT_LINE_DELETE--def test_checkout_totals_use_discounts(- api_client, checkout_with_item, sale, channel_USD-):+def test_checkout_totals_use_discounts(api_client, checkout_with_item, channel_USD):+ # givencheckout = checkout_with_item- # make sure that we're testing a variant that is actually on sale- product = checkout.lines.first().variant.product- sale.products.add(product)-query = """query getCheckout($id: ID) {checkout(id: $id) {@@ -43,7 +33,11 @@ def test_checkout_totals_use_discounts("""variables = {"id": to_global_id_or_none(checkout)}++ # whenresponse = api_client.post_graphql(query, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["checkout"]diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.pyindex e4e9c58c11..e3db683860 100644--- a/saleor/graphql/discount/dataloaders.py+++ b/saleor/graphql/discount/dataloaders.py@@ -12,7 +12,6 @@ from ...discount.models import (Promotion,PromotionEvent,PromotionRule,- SaleChannelListing,Voucher,VoucherChannelListing,)@@ -20,40 +19,6 @@ from ..channel.dataloaders import ChannelBySlugLoaderfrom ..core.dataloaders import DataLoader-class SaleChannelListingBySaleIdAndChanneSlugLoader(DataLoader):- context_key = "salechannelisting_by_sale_and_channel"-- def batch_load(self, keys):- sale_ids = [key[0] for key in keys]- channel_slugs = [key[1] for key in keys]- sale_channel_listings = (- SaleChannelListing.objects.using(self.database_connection_name)- .filter(sale_id__in=sale_ids, channel__slug__in=channel_slugs)- .annotate(channel_slug=F("channel__slug"))- .order_by("pk")- )- sale_channel_listings_by_sale_and_channel_map = {}- for sale_channel_listing in sale_channel_listings:- key = (sale_channel_listing.sale_id, sale_channel_listing.channel_slug)- sale_channel_listings_by_sale_and_channel_map[key] = sale_channel_listing- return [sale_channel_listings_by_sale_and_channel_map.get(key) for key in keys]---class SaleChannelListingBySaleIdLoader(DataLoader):- context_key = "salechannelisting_by_sale"-- def batch_load(self, keys):- sale_channel_listings = SaleChannelListing.objects.using(- self.database_connection_name- ).filter(sale_id__in=keys)- sale_channel_listings_by_sale_map = defaultdict(list)- for sale_channel_listing in sale_channel_listings:- sale_channel_listings_by_sale_map[sale_channel_listing.sale_id].append(- sale_channel_listing- )- return [sale_channel_listings_by_sale_map[sale_id] for sale_id in keys]--class VoucherByIdLoader(DataLoader):context_key = "voucher_by_id"diff --git a/saleor/graphql/discount/filters.py b/saleor/graphql/discount/filters.pyindex bd07867d36..128a44a7cd 100644--- a/saleor/graphql/discount/filters.py+++ b/saleor/graphql/discount/filters.py@@ -6,7 +6,7 @@ from django.db.models import Exists, OuterRef, Qfrom django.utils import timezonefrom ...discount import DiscountValueType-from ...discount.models import PromotionRule, Sale, Voucher, VoucherQueryset+from ...discount.models import Promotion, PromotionRule, Voucher, VoucherQuerysetfrom ..core.doc_category import DOC_CATEGORY_DISCOUNTSfrom ..core.filters import (BooleanWhereFilter,@@ -133,7 +133,7 @@ class SaleFilter(MetadataFilterBase):search = django_filters.CharFilter(method=filter_sale_search)class Meta:- model = Sale+ model = Promotionfields = ["status", "sale_type", "started", "search"]diff --git a/saleor/graphql/discount/mutations/sale/sale_create.py b/saleor/graphql/discount/mutations/sale/sale_create.pyindex f03ddbb4e2..6247fa2fc2 100644--- a/saleor/graphql/discount/mutations/sale/sale_create.py+++ b/saleor/graphql/discount/mutations/sale/sale_create.py@@ -8,7 +8,6 @@ from .....core.tracing import traced_atomic_transactionfrom .....discount import modelsfrom .....discount.error_codes import DiscountErrorCodefrom .....discount.models import Promotion-from .....discount.tests.sale_converter import create_catalogue_predicatefrom .....permission.enums import DiscountPermissionsfrom .....product.tasks import update_products_discounted_prices_of_promotion_taskfrom .....webhook.event_types import WebhookEventAsyncType@@ -24,7 +23,10 @@ from ....core.validators import validate_end_is_after_startfrom ....plugins.dataloaders import get_plugin_manager_promisefrom ...enums import DiscountValueTypeEnumfrom ...types import Sale-from ...utils import convert_migrated_sale_predicate_to_catalogue_info+from ...utils import (+ convert_migrated_sale_predicate_to_catalogue_info,+ create_catalogue_predicate,+)class SaleInput(BaseInputObjectType):diff --git a/saleor/graphql/discount/mutations/sale/sale_update.py b/saleor/graphql/discount/mutations/sale/sale_update.pyindex d95f4e0905..043728b750 100644--- a/saleor/graphql/discount/mutations/sale/sale_update.py+++ b/saleor/graphql/discount/mutations/sale/sale_update.py@@ -8,7 +8,6 @@ from django.core.exceptions import ValidationErrorfrom .....core.tracing import traced_atomic_transactionfrom .....discount import modelsfrom .....discount.error_codes import DiscountErrorCode-from .....discount.tests.sale_converter import create_catalogue_predicatefrom .....discount.utils import CATALOGUE_FIELDSfrom .....permission.enums import DiscountPermissionsfrom .....product.tasks import update_products_discounted_prices_for_promotion_task@@ -29,6 +28,7 @@ from ....plugins.dataloaders import get_plugin_manager_promisefrom ...types import Salefrom ...utils import (convert_migrated_sale_predicate_to_catalogue_info,+ create_catalogue_predicate,get_products_for_rule,)from .sale_create import SaleInputdiff --git a/saleor/graphql/discount/tests/benchmark/test_sales.py b/saleor/graphql/discount/tests/benchmark/test_sales.pyindex 41f3e1d628..28601168ca 100644--- a/saleor/graphql/discount/tests/benchmark/test_sales.py+++ b/saleor/graphql/discount/tests/benchmark/test_sales.py@@ -1,35 +1,50 @@import pytest-from .....discount.models import Sale, SaleChannelListing+from .....discount import RewardValueType+from .....discount.models import Promotion, PromotionRulefrom ....tests.utils import get_graphql_content@pytest.fixture-def sales_list(channel_USD, channel_PLN):- sales = Sale.objects.bulk_create(- [Sale(name="Sale1"), Sale(name="Sale2"), Sale(name="Sale2")]+def promotion_converted_from_sale_list(channel_USD, channel_PLN):+ promotions = Promotion.objects.bulk_create(+ [Promotion(name="Sale1"), Promotion(name="Sale2"), Promotion(name="Sale2")])+ for promotion in promotions:+ promotion.assign_old_sale_id()+values = [15, 5, 25]- sale_channel_listings = []- for sale, value in zip(sales, values):- sale_channel_listings.append(- SaleChannelListing(- sale=sale,- channel=channel_USD,- discount_value=value,- currency=channel_USD.currency_code,+ usd_rules, pln_rules = [], []+ for promotion, value in zip(promotions, values):+ usd_rules.append(+ PromotionRule(+ promotion=promotion,+ catalogue_predicate={},+ reward_value_type=RewardValueType.FIXED,+ reward_value=value,))- sale_channel_listings.append(- SaleChannelListing(- sale=sale,- channel=channel_PLN,- discount_value=value * 2,- currency=channel_PLN.currency_code,+ pln_rules.append(+ PromotionRule(+ promotion=promotion,+ catalogue_predicate={},+ reward_value_type=RewardValueType.FIXED,+ reward_value=value * 2,))- SaleChannelListing.objects.bulk_create(sale_channel_listings)- return sales+ PromotionRule.objects.bulk_create(usd_rules + pln_rules)+ PromotionRuleChannel = PromotionRule.channels.through+ usd_rules_channels = [+ PromotionRuleChannel(promotionrule_id=rule.id, channel_id=channel_USD.id)+ for rule in usd_rules+ ]+ pln_rules_channels = [+ PromotionRuleChannel(promotionrule_id=rule.id, channel_id=channel_PLN.id)+ for rule in usd_rules+ ]+ PromotionRuleChannel.objects.bulk_create(usd_rules_channels + pln_rules_channels)++ return promotionsSALES_QUERY = """@@ -95,7 +110,7 @@ query GetSales($channel: String){@pytest.mark.count_queries(autouse=False)def test_sales_query_with_channel_slug(staff_api_client,- sales_list,+ promotion_converted_from_sale_list,channel_USD,permission_manage_discounts,count_queries,@@ -113,9 +128,9 @@ def test_sales_query_with_channel_slug(@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)-def test_sales_query_withot_channel_slug(+def test_sales_query_without_channel_slug(staff_api_client,- sales_list,+ promotion_converted_from_sale_list,permission_manage_discounts,count_queries,):diff --git a/saleor/graphql/discount/tests/deprecated/test_discount.py b/saleor/graphql/discount/tests/deprecated/test_discount.pyindex db7cef8ac2..8db45605e1 100644--- a/saleor/graphql/discount/tests/deprecated/test_discount.py+++ b/saleor/graphql/discount/tests/deprecated/test_discount.py@@ -1,8 +1,7 @@import warningsfrom .....channel.utils import DEPRECATION_WARNING_MESSAGE-from .....discount.models import Sale, Voucher-from .....discount.tests.sale_converter import convert_sales_to_promotions+from .....discount.models import Promotion, Voucherfrom ....tests.utils import get_graphql_contentQUERY_SALES_WITH_SORTING_AND_FILTERING = """@@ -19,13 +18,12 @@ QUERY_SALES_WITH_SORTING_AND_FILTERING = """def test_sales_with_sorting_and_without_channel(- staff_api_client, permission_manage_discounts, new_sale, sale, channel_USD+ staff_api_client,+ permission_manage_discounts,+ promotion_converted_from_sale,+ promotion_converted_from_sale_with_empty_predicate,):# given- listing = new_sale.channel_listings.first()- listing.discount_value = 10- listing.save(update_fields=["discount_value"])- convert_sales_to_promotions()variables = {"sortBy": {"field": "VALUE", "direction": "ASC"}}# when@@ -40,7 +38,14 @@ def test_sales_with_sorting_and_without_channel(# thencontent = get_graphql_content(response)sales_nodes = content["data"]["sales"]["edges"]- assert [node["node"]["name"] for node in sales_nodes] == [sale.name, new_sale.name]+ promotion_names = [+ promotion.name+ for promotion in [+ promotion_converted_from_sale,+ promotion_converted_from_sale_with_empty_predicate,+ ]+ ]+ assert all([node["node"]["name"] in promotion_names for node in sales_nodes])assert any([str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]@@ -85,9 +90,13 @@ def test_query_vouchers_with_sort(def test_filter_sales_by_query(staff_api_client, permission_manage_discounts):- sales = Sale.objects.bulk_create([Sale(name="Spanish"), Sale(name="Inquisition")])- sale = sales[1]- convert_sales_to_promotions()+ promotions = Promotion.objects.bulk_create(+ [Promotion(name="Promotion"), Promotion(name="Sale")]+ )+ for promotion in promotions:+ promotion.assign_old_sale_id()++ promotion = promotions[1]query = """query Sales($query: String) {@@ -102,9 +111,13 @@ def test_filter_sales_by_query(staff_api_client, permission_manage_discounts):"""staff_api_client.user.user_permissions.add(permission_manage_discounts)- response = staff_api_client.post_graphql(query, {"query": sale.name})++ # when+ response = staff_api_client.post_graphql(query, {"query": promotion.name})++ # thencontent = get_graphql_content(response)- assert content["data"]["sales"]["edges"][0]["node"]["name"] == sale.name+ assert content["data"]["sales"]["edges"][0]["node"]["name"] == promotion.namedef test_filter_vouchers_by_query(staff_api_client, permission_manage_discounts):diff --git a/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py b/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.pyindex 2c5faea17b..0b78117b58 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py@@ -1,33 +1,63 @@+from decimal import Decimalfrom unittest import mockimport grapheneimport pytest+from .....discount import RewardValueTypefrom .....discount.error_codes import DiscountErrorCode-from .....discount.models import Promotion, Sale, SaleChannelListing-from .....discount.tests.sale_converter import convert_sales_to_promotions+from .....discount.models import Promotion, PromotionRulefrom ....tests.utils import get_graphql_content@pytest.fixture-def sale_list(channel_USD, product_list, category, collection):- sales = Sale.objects.bulk_create(- [Sale(name="Sale 1"), Sale(name="Sale 2"), Sale(name="Sale 3")]+def promotion_converted_from_sale_list(channel_USD, product_list, category, collection):+ promotions = Promotion.objects.bulk_create(+ [Promotion(name="Sale 1"), Promotion(name="Sale 2"), Promotion(name="Sale 3")])- for sale, product in zip(sales, product_list):- sale.products.add(product)- sale.variants.add(product.variants.first())-- sales[0].categories.add(category)- sales[1].collections.add(collection)-- SaleChannelListing.objects.bulk_create(- [- SaleChannelListing(sale=sale, discount_value=5, channel=channel_USD)- for sale in sales- ]- )- return list(sales)+ for promotion in promotions:+ promotion.assign_old_sale_id()+ predicates = [+ {+ "OR": [+ {+ "productPredicate": {+ "ids": [graphene.Node.to_global_id("Product", product.id)]+ }+ },+ {+ "variantPredicate": {+ "ids": [+ graphene.Node.to_global_id(+ "Product", product.variants.first().id+ )+ ]+ }+ },+ ]+ }+ for product in product_list+ ]+ collection_id = graphene.Node.to_global_id("Collection", collection.id)+ category_id = graphene.Node.to_global_id("Category", category.id)++ predicates[0]["OR"].append({"categoryPredicate": {"ids": [category_id]}})+ predicates[1]["OR"].append({"collectionPredicate": {"ids": [collection_id]}})++ rules = [+ PromotionRule(+ promotion=promotion,+ catalogue_predicate=predicate,+ reward_value_type=RewardValueType.FIXED,+ reward_value=Decimal("5"),+ )+ for promotion, predicate in zip(promotions, predicates)+ ]+ PromotionRule.objects.bulk_create(rules)+ for rule in rules:+ rule.channels.add(channel_USD)++ return promotionsSALE_BULK_DELETE_MUTATION = """@@ -51,14 +81,17 @@ def test_delete_sales(update_products_discounted_prices_for_promotion_task,deleted_webhook_mock,staff_api_client,- sale_list,+ promotion_converted_from_sale_list,permission_manage_discounts,):# given+ promotion_list = promotion_converted_from_sale_listvariables = {- "ids": [graphene.Node.to_global_id("Sale", sale.id) for sale in sale_list]+ "ids": [+ graphene.Node.to_global_id("Sale", promotion.old_sale_id)+ for promotion in promotion_list+ ]}- convert_sales_to_promotions()# whenresponse = staff_api_client.post_graphql(@@ -70,10 +103,10 @@ def test_delete_sales(assert content["data"]["saleBulkDelete"]["count"] == 3assert not Promotion.objects.filter(- old_sale_id__in=[sale.id for sale in sale_list]+ id__in=[promotion.id for promotion in promotion_list]).exists()update_products_discounted_prices_for_promotion_task.called_once()- assert deleted_webhook_mock.call_count == len(sale_list)+ assert deleted_webhook_mock.call_count == len(promotion_list)@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@@ -82,7 +115,7 @@ def test_delete_sales_triggers_webhook(mocked_webhook_trigger,mocked_get_webhooks_for_event,staff_api_client,- sale_list,+ promotion_converted_from_sale_list,permission_manage_discounts,any_webhook,settings,@@ -90,10 +123,15 @@ def test_delete_sales_triggers_webhook(# givenmocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ promotion_list = promotion_converted_from_sale_list+variables = {- "ids": [graphene.Node.to_global_id("Sale", sale.id) for sale in sale_list]+ "ids": [+ graphene.Node.to_global_id("Sale", promotion.old_sale_id)+ for promotion in promotion_list+ ]}- convert_sales_to_promotions()+# whenresponse = staff_api_client.post_graphql(SALE_BULK_DELETE_MUTATION, variables, permissions=[permission_manage_discounts]@@ -112,7 +150,7 @@ def test_delete_sales_with_variants_triggers_webhook(mocked_webhook_trigger,mocked_get_webhooks_for_event,staff_api_client,- sale_list,+ promotion_converted_from_sale_list,permission_manage_discounts,any_webhook,settings,@@ -122,23 +160,44 @@ def test_delete_sales_with_variants_triggers_webhook(product_variant_list,):# given- for sale in sale_list:- sale.products.add(product)- sale.collections.add(collection)- sale.categories.add(category)- sale.variants.add(*product_variant_list)+ collection_id = graphene.Node.to_global_id("Collection", collection.id)+ category_id = graphene.Node.to_global_id("Category", category.id)+ product_id = graphene.Node.to_global_id("Product", product.id)+ variant_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.id)+ for variant in product_variant_list+ ]+ predicate = {+ "OR": [+ {"collectionPredicate": {"ids": [collection_id]}},+ {"categoryPredicate": {"ids": [category_id]}},+ {"productPredicate": {"ids": [product_id]}},+ {"variantPredicate": {"ids": variant_ids}},+ ]+ }++ promotion_list = promotion_converted_from_sale_list+ rules = [promotion.rules.first() for promotion in promotion_list]+ for rule in rules:+ rule.catalogue_predicate = predicate++ PromotionRule.objects.bulk_update(rules, fields=["catalogue_predicate"])mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]variables = {- "ids": [graphene.Node.to_global_id("Sale", sale.id) for sale in sale_list]+ "ids": [+ graphene.Node.to_global_id("Sale", promotion.old_sale_id)+ for promotion in promotion_list+ ]}- convert_sales_to_promotions()# whenresponse = staff_api_client.post_graphql(SALE_BULK_DELETE_MUTATION, variables, permissions=[permission_manage_discounts])++ # thencontent = get_graphql_content(response)assert content["data"]["saleBulkDelete"]["count"] == 3assert mocked_webhook_trigger.call_count == 3@@ -153,15 +212,14 @@ def test_delete_sales_with_promotion_ids(deleted_webhook_mock,staff_api_client,any_webhook,- sale_list,+ promotion_converted_from_sale_list,permission_manage_discounts,):# given- convert_sales_to_promotions()variables = {"ids": [graphene.Node.to_global_id("Promotion", promotion.id)- for promotion in Promotion.objects.all()+ for promotion in promotion_converted_from_sale_list]}diff --git a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.pyindex 03cbac1c2d..9794967014 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py@@ -3,11 +3,7 @@ from unittest.mock import patchimport graphenefrom .....discount.error_codes import DiscountErrorCode-from .....discount.models import Promotion-from .....discount.tests.sale_converter import convert_sales_to_promotions-from .....discount.utils import fetch_catalogue_infofrom ....tests.utils import get_graphql_content-from ...mutations.utils import convert_catalogue_info_to_global_idsfrom ...utils import convert_migrated_sale_predicate_to_catalogue_infoSALE_CATALOGUES_ADD_MUTATION = """@@ -34,7 +30,7 @@ def test_sale_add_catalogues(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- new_sale,+ promotion_converted_from_sale_with_empty_predicate,category,product,collection,@@ -42,11 +38,9 @@ def test_sale_add_catalogues(permission_manage_discounts,):# given- sale = new_salequery = SALE_CATALOGUES_ADD_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)- )+ promotion = promotion_converted_from_sale_with_empty_predicate+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info({})product_id = graphene.Node.to_global_id("Product", product.id)collection_id = graphene.Node.to_global_id("Collection", collection.id)category_id = graphene.Node.to_global_id("Category", category.id)@@ -54,10 +48,9 @@ def test_sale_add_catalogues(graphene.Node.to_global_id("ProductVariant", variant.id)for variant in product_variant_list]- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"products": [product_id],"collections": [collection_id],@@ -74,8 +67,8 @@ def test_sale_add_catalogues(# thencontent = get_graphql_content(response)assert not content["data"]["saleCataloguesAdd"]["errors"]- assert content["data"]["saleCataloguesAdd"]["sale"]["name"] == sale.name- promotion = Promotion.objects.get(old_sale_id=sale.id)+ assert content["data"]["saleCataloguesAdd"]["sale"]["name"] == promotion.name+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)@@ -98,7 +91,8 @@ def test_sale_add_catalogues_no_changes_in_catalogue(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,collection,category,product,@@ -107,17 +101,17 @@ def test_sale_add_catalogues_no_changes_in_catalogue():# givenquery = SALE_CATALOGUES_ADD_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)collection_id = graphene.Node.to_global_id("Collection", collection.id)category_id = graphene.Node.to_global_id("Category", category.id)product_id = graphene.Node.to_global_id("Product", product.id)variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"collections": [collection_id],"categories": [category_id],@@ -134,7 +128,7 @@ def test_sale_add_catalogues_no_changes_in_catalogue(# thencontent = get_graphql_content(response)assert not content["data"]["saleCataloguesAdd"]["errors"]- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)@@ -156,22 +150,24 @@ def test_sale_add_empty_catalogues(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,+ collection,+ category,+ product,+ variant,permission_manage_discounts,):# givenquery = SALE_CATALOGUES_ADD_MUTATION+ promotion = promotion_converted_from_sale+ collection_id = graphene.Node.to_global_id("Collection", collection.id)+ category_id = graphene.Node.to_global_id("Category", category.id)+ product_id = graphene.Node.to_global_id("Product", product.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)- product_id = graphene.Node.to_global_id("Product", sale.products.first().id)- collection_id = graphene.Node.to_global_id(- "Collection", sale.collections.first().id- )- category_id = graphene.Node.to_global_id("Category", sale.categories.first().id)- variant_id = graphene.Node.to_global_id("ProductVariant", sale.variants.first().id)-- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"products": [], "collections": [], "categories": [], "variants": []},}@@ -183,7 +179,7 @@ def test_sale_add_empty_catalogues(# thencontent = get_graphql_content(response)assert not content["data"]["saleCataloguesAdd"]["errors"]- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)@@ -204,14 +200,15 @@ def test_sale_add_empty_catalogues_to_sale_with_empty_catalogues(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- new_sale,+ promotion_converted_from_sale_with_empty_predicate,permission_manage_discounts,):# givenquery = SALE_CATALOGUES_ADD_MUTATION- convert_sales_to_promotions()+ promotion = promotion_converted_from_sale_with_empty_predicate+variables = {- "id": graphene.Node.to_global_id("Sale", new_sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"products": [], "collections": [], "categories": [], "variants": []},}@@ -223,7 +220,7 @@ def test_sale_add_empty_catalogues_to_sale_with_empty_catalogues(# thencontent = get_graphql_content(response)assert not content["data"]["saleCataloguesAdd"]["errors"]- promotion = Promotion.objects.get(old_sale_id=new_sale.id)+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)@@ -244,28 +241,28 @@ def test_sale_add_catalogues_no_product_ids_change(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,+ product,product_variant_list,permission_manage_discounts,):# givenquery = SALE_CATALOGUES_ADD_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)variant_ids = [graphene.Node.to_global_id("ProductVariant", variant.id)for variant in product_variant_list]- product = sale.products.first()for variant in product_variant_list:assert variant.product == product- convert_sales_to_promotions()-variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"variants": variant_ids,},@@ -279,7 +276,7 @@ def test_sale_add_catalogues_no_product_ids_change(# thencontent = get_graphql_content(response)assert not content["data"]["saleCataloguesAdd"]["errors"]- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)@@ -295,7 +292,8 @@ def test_sale_add_catalogues_no_product_ids_change(def test_sale_add_catalogues_with_product_without_variants(update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,category,product,collection,@@ -303,14 +301,14 @@ def test_sale_add_catalogues_with_product_without_variants():# givenquery = SALE_CATALOGUES_ADD_MUTATION+ promotion = promotion_converted_from_saleproduct.variants.all().delete()product_id = graphene.Node.to_global_id("Product", product.id)collection_id = graphene.Node.to_global_id("Collection", collection.id)category_id = graphene.Node.to_global_id("Category", category.id)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"products": [product_id],"collections": [collection_id],@@ -334,16 +332,14 @@ def test_sale_add_catalogues_with_product_without_variants(def test_sale_add_catalogues_with_promotion_id(staff_api_client,- sale,+ promotion_converted_from_sale,product,permission_manage_discounts,):# givenquery = SALE_CATALOGUES_ADD_MUTATION+ promotion = promotion_converted_from_saleproduct_id = graphene.Node.to_global_id("Product", product.id)- convert_sales_to_promotions()-- promotion = Promotion.objects.get(old_sale_id=sale.id)variables = {"id": graphene.Node.to_global_id("Promotion", 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.pyindex e582a77ee2..5005a31ae0 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py@@ -3,11 +3,7 @@ from unittest.mock import patchimport graphenefrom .....discount.error_codes import DiscountErrorCode-from .....discount.models import Promotion-from .....discount.tests.sale_converter import convert_sales_to_promotions-from .....discount.utils import fetch_catalogue_infofrom ....tests.utils import get_graphql_content-from ...mutations.utils import convert_catalogue_info_to_global_idsfrom ...utils import convert_migrated_sale_predicate_to_catalogue_infoSALE_CATALOGUES_REMOVE_MUTATION = """@@ -34,7 +30,8 @@ def test_sale_remove_catalogues(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,category,product,collection,@@ -43,25 +40,30 @@ def test_sale_remove_catalogues(permission_manage_discounts,):# given- sale.products.add(product_list[0])-- assert collection in sale.collections.all()- assert category in sale.categories.all()- assert product in sale.products.all()- assert variant in sale.variants.all()-query = SALE_CATALOGUES_REMOVE_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)- )+ promotion = promotion_converted_from_sale+ predicate = catalogue_predicate+ extra_product = product_list[0]+ extra_product_id = graphene.Node.to_global_id("Product", extra_product.id)product_id = graphene.Node.to_global_id("Product", product.id)collection_id = graphene.Node.to_global_id("Collection", collection.id)category_id = graphene.Node.to_global_id("Category", category.id)variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)- convert_sales_to_promotions()++ predicate["OR"][2]["productPredicate"]["ids"].append(extra_product_id)+ rule = promotion.rules.first()+ rule.catalogue_predicate = predicate+ rule.save(update_fields=["catalogue_predicate"])+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)++ assert collection_id in previous_catalogue["collections"]+ assert category_id in previous_catalogue["categories"]+ assert product_id in previous_catalogue["products"]+ assert extra_product_id in previous_catalogue["products"]+ assert variant_id in previous_catalogue["variants"]variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"collections": [collection_id],"categories": [category_id],@@ -78,8 +80,8 @@ def test_sale_remove_catalogues(# thencontent = get_graphql_content(response)assert not content["data"]["saleCataloguesRemove"]["errors"]- assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == sale.name- promotion = Promotion.objects.get(old_sale_id=sale.id)+ assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == promotion.name+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)@@ -88,10 +90,7 @@ def test_sale_remove_catalogues(assert product_id not in current_catalogue["products"]assert variant_id not in current_catalogue["variants"]- assert (- graphene.Node.to_global_id("Product", product_list[0].id)- in current_catalogue["products"]- )+ assert extra_product_id in current_catalogue["products"]updated_webhook_mock.assert_called_once_with(promotion, previous_catalogue, current_catalogue@@ -107,7 +106,8 @@ def test_sale_remove_empty_catalogues(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,category,product,collection,@@ -115,24 +115,23 @@ def test_sale_remove_empty_catalogues(permission_manage_discounts,):# given- assert collection in sale.collections.all()- assert category in sale.categories.all()- assert product in sale.products.all()- assert variant in sale.variants.all()-query = SALE_CATALOGUES_REMOVE_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)-product_id = graphene.Node.to_global_id("Product", product.id)collection_id = graphene.Node.to_global_id("Collection", collection.id)category_id = graphene.Node.to_global_id("Category", category.id)variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)- convert_sales_to_promotions()++ assert collection_id in previous_catalogue["collections"]+ assert category_id in previous_catalogue["categories"]+ assert product_id in previous_catalogue["products"]+ assert variant_id in previous_catalogue["variants"]variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"collections": [],"categories": [],@@ -149,8 +148,8 @@ def test_sale_remove_empty_catalogues(# thencontent = get_graphql_content(response)assert not content["data"]["saleCataloguesRemove"]["errors"]- assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == sale.name- promotion = Promotion.objects.get(old_sale_id=sale.id)+ assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == promotion.name+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)assert current_catalogue == previous_catalogue@@ -172,16 +171,15 @@ def test_sale_remove_empty_catalogues_from_sale_with_empty_catalogues(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- new_sale,+ promotion_converted_from_sale_with_empty_predicate,permission_manage_discounts,):# given- sale = new_salequery = SALE_CATALOGUES_REMOVE_MUTATION- convert_sales_to_promotions()+ promotion = promotion_converted_from_sale_with_empty_predicatevariables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"collections": [],"categories": [],@@ -198,8 +196,8 @@ def test_sale_remove_empty_catalogues_from_sale_with_empty_catalogues(# thencontent = get_graphql_content(response)assert not content["data"]["saleCataloguesRemove"]["errors"]- assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == sale.name- promotion = Promotion.objects.get(old_sale_id=sale.id)+ assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == promotion.name+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)@@ -220,20 +218,21 @@ def test_sale_remove_catalogues_no_product_changes(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,variant,permission_manage_discounts,):# givenquery = SALE_CATALOGUES_REMOVE_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"products": [],"variants": [variant_id],@@ -248,8 +247,8 @@ def test_sale_remove_catalogues_no_product_changes(# thencontent = get_graphql_content(response)assert not content["data"]["saleCataloguesRemove"]["errors"]- assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == sale.name- promotion = Promotion.objects.get(old_sale_id=sale.id)+ assert content["data"]["saleCataloguesRemove"]["sale"]["name"] == promotion.name+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)@@ -263,16 +262,14 @@ def test_sale_remove_catalogues_no_product_changes(def test_sale_remove_catalogues_with_promotion_id(staff_api_client,- sale,+ promotion_converted_from_sale,product,permission_manage_discounts,):# givenquery = SALE_CATALOGUES_REMOVE_MUTATIONproduct_id = graphene.Node.to_global_id("Product", product.id)- convert_sales_to_promotions()-- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion = promotion_converted_from_salevariables = {"id": graphene.Node.to_global_id("Promotion", 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.pyindex ecaf8a5acf..9c3d7b72e9 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@@ -2,13 +2,8 @@ from unittest.mock import patchimport graphene-from .....discount import DiscountValueType+from .....discount import RewardValueTypefrom .....discount.error_codes import DiscountErrorCode-from .....discount.models import Promotion, PromotionRule, SaleChannelListing-from .....discount.tests.sale_converter import (- convert_sales_to_promotions,- create_catalogue_predicate_from_sale,-)from ....tests.utils import assert_negative_positive_decimal_value, get_graphql_contentSALE_CHANNEL_LISTING_UPDATE_MUTATION = """@@ -44,23 +39,16 @@ mutation UpdateSaleChannelListing(def test_sale_channel_listing_add_channels(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_PLN,):# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)discounted = 1.12- channel_listing = SaleChannelListing.objects.filter(- sale_id=sale.pk, channel_id=channel_PLN.id- )- assert len(channel_listing) == 0-- convert_sales_to_promotions()- assert len(PromotionRule.objects.all()) == 1-variables = {"id": sale_id,"input": {@@ -79,7 +67,7 @@ def test_sale_channel_listing_add_channels(# thenassert not content["data"]["saleChannelListingUpdate"]["errors"]data = content["data"]["saleChannelListingUpdate"]["sale"]- assert data["name"] == sale.name+ assert data["name"] == promotion.namechannel_listing = data["channelListings"]discounts = [item["discountValue"] for item in channel_listing]@@ -87,7 +75,7 @@ def test_sale_channel_listing_add_channels(assert discounted in discountsassert channel_PLN.slug in slugs- promotion = Promotion.objects.get(old_sale_id=sale.pk)+ promotion.refresh_from_db()rules = promotion.rules.all()assert len(rules) == 2assert (@@ -108,23 +96,18 @@ def test_sale_channel_listing_add_channels(def test_sale_channel_listing_add_multiple_channels(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_PLN,channel_JPY,):# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)channel_jpy_id = graphene.Node.to_global_id("Channel", channel_JPY.id)discounted = 5- channel_listing = SaleChannelListing.objects.filter(- sale_id=sale.pk, channel_id__in=[channel_PLN.id, channel_JPY.id]- )- assert len(channel_listing) == 0- convert_sales_to_promotions()-variables = {"id": sale_id,"input": {@@ -146,7 +129,7 @@ def test_sale_channel_listing_add_multiple_channels(# thenassert not content["data"]["saleChannelListingUpdate"]["errors"]data = content["data"]["saleChannelListingUpdate"]["sale"]- assert data["name"] == sale.name+ assert data["name"] == promotion.namechannel_listing = data["channelListings"]discounts = [item["discountValue"] for item in channel_listing]@@ -155,7 +138,7 @@ def test_sale_channel_listing_add_multiple_channels(assert channel_PLN.slug in slugsassert channel_JPY.slug in slugs- promotion = Promotion.objects.get(old_sale_id=sale.pk)+ promotion.refresh_from_db()rules = promotion.rules.all()assert len(rules) == 3old_channel_listing_ids = [rule.old_channel_listing_id for rule in rules]@@ -174,15 +157,15 @@ def test_sale_channel_listing_add_multiple_channels(def test_sale_channel_listing_update_channels(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_USD,):# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)discounted = 10.11- convert_sales_to_promotions()variables = {"id": sale_id,@@ -190,10 +173,6 @@ def test_sale_channel_listing_update_channels("addChannels": [{"channelId": channel_id, "discountValue": discounted}]},}- channel_listing = SaleChannelListing.objects.get(- sale_id=sale.pk, channel_id=channel_USD.id- )- assert channel_listing.discount_value == 5# whenresponse = staff_api_client.post_graphql(@@ -213,7 +192,7 @@ def test_sale_channel_listing_update_channels(assert channel_listing[0]["discountValue"] == discountedassert channel_listing[0]["channel"]["slug"] == channel_USD.slug- promotion = Promotion.objects.get(old_sale_id=sale.pk)+ promotion.refresh_from_db()rules = promotion.rules.all()assert len(rules) == 1@@ -229,22 +208,16 @@ def test_sale_channel_listing_update_channels(def test_sale_channel_listing_remove_channels(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale_with_many_channels,+ promotion_converted_from_sale_with_many_channels,permission_manage_discounts,channel_USD,channel_PLN,):# given- sale = sale_with_many_channels- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale_with_many_channels+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)- channel_listing = SaleChannelListing.objects.filter(sale_id=sale.pk)- assert len(channel_listing) == 2-- convert_sales_to_promotions()- assert len(PromotionRule.objects.all()) == 2-variables = {"id": sale_id,"input": {"removeChannels": [channel_id]},@@ -261,13 +234,13 @@ def test_sale_channel_listing_remove_channels(# thenassert not content["data"]["saleChannelListingUpdate"]["errors"]data = content["data"]["saleChannelListingUpdate"]["sale"]- assert data["name"] == sale.name+ assert data["name"] == promotion.namechannel_listing = data["channelListings"]assert len(channel_listing) == 1assert channel_listing[0]["channel"]["slug"] == channel_PLN.slug- promotion = Promotion.objects.get(old_sale_id=sale.pk)+ promotion.refresh_from_db()rules = promotion.rules.all()assert len(rules) == 1@@ -283,24 +256,22 @@ def test_sale_channel_listing_remove_channels(def test_sale_channel_listing_remove_all_channels(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale_with_many_channels,+ promotion_converted_from_sale_with_many_channels,permission_manage_discounts,channel_USD,channel_PLN,):# given- sale = sale_with_many_channels- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale_with_many_channels+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_ids = [graphene.Node.to_global_id("Channel", channel.id)for channel in [channel_USD, channel_PLN]]- channel_listing = SaleChannelListing.objects.filter(sale_id=sale.pk)- assert len(channel_listing) == 2-- convert_sales_to_promotions()- assert len(PromotionRule.objects.all()) == 2+ rule = promotion.rules.first()+ reward_value_type = rule.reward_value_type+ predicate = rule.catalogue_predicatevariables = {"id": sale_id,@@ -318,16 +289,16 @@ def test_sale_channel_listing_remove_all_channels(# thenassert not content["data"]["saleChannelListingUpdate"]["errors"]data = content["data"]["saleChannelListingUpdate"]["sale"]- assert data["name"] == sale.name+ assert data["name"] == promotion.nameassert not data["channelListings"]- promotion = Promotion.objects.get(old_sale_id=sale.pk)+ promotion.refresh_from_db()# Despite removing the promotion from all channels, we ensure at least one rule# is assigned to promotion in order to determine old sale's type and cataloguerules = promotion.rules.all()assert len(rules) == 1- assert rules[0].reward_value_type == sale.type- assert rules[0].catalogue_predicate == create_catalogue_predicate_from_sale(sale)+ assert rules[0].reward_value_type == reward_value_type+ assert rules[0].catalogue_predicate == predicatemock_update_products_discounted_prices_of_promotion_task.delay.assert_called_once_with(promotion.pk@@ -341,28 +312,20 @@ def test_sale_channel_listing_remove_all_channels(def test_sale_channel_listing_add_update_remove_channels(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale_with_many_channels,+ promotion_converted_from_sale_with_many_channels,permission_manage_discounts,channel_PLN,channel_USD,channel_JPY,):# given- sale = sale_with_many_channels- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale_with_many_channels+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)channel_jpy_id = graphene.Node.to_global_id("Channel", channel_JPY.id)discounted = 5- channel_listing = SaleChannelListing.objects.filter(sale_id=sale.pk).order_by(- "currency"- )- assert len(channel_listing) == 2- assert channel_listing[0].channel_id == channel_PLN.id- assert channel_listing[1].channel_id == channel_USD.id- convert_sales_to_promotions()-variables = {"id": sale_id,"input": {@@ -385,7 +348,7 @@ def test_sale_channel_listing_add_update_remove_channels(# thenassert not content["data"]["saleChannelListingUpdate"]["errors"]data = content["data"]["saleChannelListingUpdate"]["sale"]- assert data["name"] == sale.name+ assert data["name"] == promotion.namechannel_listings = data["channelListings"]assert len(channel_listings) == 2assert all(@@ -396,7 +359,7 @@ def test_sale_channel_listing_add_update_remove_channels()assert all([listing["discountValue"] == discounted for listing in channel_listings])- promotion = Promotion.objects.get(old_sale_id=sale.pk)+ promotion.refresh_from_db()rules = promotion.rules.all()assert len(rules) == 2for rule in rules:@@ -409,20 +372,15 @@ def test_sale_channel_listing_add_update_remove_channels(def test_sale_channel_listing_update_with_negative_discounted_value(staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_USD,):# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)discounted_value = -10- convert_sales_to_promotions()-- channel_listing = SaleChannelListing.objects.get(- sale_id=sale.pk, channel_id=channel_USD.id- )- assert channel_listing.discount_value == 5staff_api_client.user.user_permissions.add(permission_manage_discounts)variables = {@@ -451,15 +409,15 @@ def test_sale_channel_listing_update_with_negative_discounted_value(def test_sale_channel_listing_update_duplicated_ids_in_add_and_remove(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_USD,):# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)discounted = 10.11- convert_sales_to_promotions()variables = {"id": sale_id,@@ -493,15 +451,15 @@ def test_sale_channel_listing_update_duplicated_ids_in_add_and_remove(def test_sale_channel_listing_update_duplicated_channel_in_add(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_USD,):# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)discounted = 10.11- convert_sales_to_promotions()variables = {"id": sale_id,@@ -537,14 +495,15 @@ def test_sale_channel_listing_update_duplicated_channel_in_add(def test_sale_channel_listing_update_duplicated_channel_in_remove(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_USD,):# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)- convert_sales_to_promotions()+variables = {"id": sale_id,"input": {"removeChannels": [channel_id, channel_id]},@@ -574,15 +533,16 @@ def test_sale_channel_listing_update_duplicated_channel_in_remove(def test_sale_channel_listing_update_with_invalid_decimal_places(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_USD,):# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)discounted = 1.123channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)- convert_sales_to_promotions()+variables = {"id": sale_id,"input": {@@ -614,18 +574,19 @@ def test_sale_channel_listing_update_with_invalid_decimal_places(def test_sale_channel_listing_update_with_invalid_percentage_value(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_USD,):# given- sale = sale- sale.type = DiscountValueType.PERCENTAGE- sale.save()- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)+ rule = promotion.rules.first()+ rule.reward_value_type = RewardValueType.PERCENTAGE+ rule.save(update_fields=["reward_value_type"])discounted = 101channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)- convert_sales_to_promotions()+variables = {"id": sale_id,"input": {@@ -640,9 +601,9 @@ def test_sale_channel_listing_update_with_invalid_percentage_value(permissions=(permission_manage_discounts,),)content = get_graphql_content(response)+# thenerrors = content["data"]["saleChannelListingUpdate"]["errors"]-assert len(errors) == 1assert errors[0]["code"] == DiscountErrorCode.INVALID.nameassert errors[0]["field"] == "input"@@ -690,16 +651,20 @@ mutation UpdateSaleChannelListing(def test_invalidate_data_sale_channel_listings_update(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_USD,):# givendiscount_value = 10- sale.channel_listings.all().delete()- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ rule = promotion.rules.first()+ rule_name = rule.name+ rule.channels.remove(channel_USD)++ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)- convert_sales_to_promotions()+variables = {"id": sale_id,"saleInput": {},@@ -717,14 +682,13 @@ def test_invalidate_data_sale_channel_listings_update(content = get_graphql_content(response)# then- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()rules = promotion.rules.all()assert len(rules) == 2- old_rule = rules.get(old_channel_listing_id__isnull=True)- new_rule = rules.get(old_channel_listing_id__isnull=False)- assert old_rule.reward_value is None- assert new_rule.reward_value == discount_value+ old_rule = rules.get(name=rule_name)+ new_rule = rules.get(name__isnull=True)+ assert new_rule.reward_value == discount_valueassert old_rule.channels.first() is Noneassert new_rule.channels.first().id == channel_USD.idassert len(new_rule.channels.all()) == 1@@ -754,7 +718,7 @@ def test_invalidate_data_sale_channel_listings_update(def test_sale_channel_listing_remove_all_channels_multiple_times(mock_update_products_discounted_prices_of_promotion_task,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,channel_PLN,channel_USD,@@ -765,11 +729,11 @@ def test_sale_channel_listing_remove_all_channels_multiple_times(# times.# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)discounted = 2- convert_sales_to_promotions()staff_api_client.user.user_permissions.add(permission_manage_discounts)query = SALE_CHANNEL_LISTING_UPDATE_MUTATIONmock_update_products_discounted_prices_of_promotion_task.return_value = None@@ -795,7 +759,7 @@ def test_sale_channel_listing_remove_all_channels_multiple_times(staff_api_client.post_graphql(query, variables=variables_remove)# then- promotion = Promotion.objects.get(old_sale_id=sale.pk)+ promotion.refresh_from_db()rules = promotion.rules.all()assert len(rules) == 1assert not rules[0].channels.first()diff --git a/saleor/graphql/discount/tests/mutations/test_sale_delete.py b/saleor/graphql/discount/tests/mutations/test_sale_delete.pyindex 7a01711b71..16eadd3e52 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_delete.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_delete.py@@ -5,10 +5,8 @@ import pytestfrom .....discount.error_codes import DiscountErrorCodefrom .....discount.models import Promotion, PromotionRule-from .....discount.tests.sale_converter import convert_sales_to_promotions-from .....discount.utils import fetch_catalogue_infofrom ....tests.utils import get_graphql_content-from ...mutations.utils import convert_catalogue_info_to_global_ids+from ...utils import convert_migrated_sale_predicate_to_catalogue_infoSALE_DELETE_MUTATION = """mutation DeleteSale($id: ID!) {@@ -35,21 +33,17 @@ def test_sale_delete_mutation(deleted_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,):# givenquery = SALE_DELETE_MUTATION- variables = {"id": graphene.Node.to_global_id("Sale", sale.id)}- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)- convert_sales_to_promotions()-- promotion = Promotion.objects.get(old_sale_id=sale.id)- assert promotion- rules = promotion.rules.all()- assert len(rules) == 1+ variables = {"id": graphene.Node.to_global_id("Sale", promotion.old_sale_id)}# whenresponse = staff_api_client.post_graphql(@@ -60,11 +54,11 @@ def test_sale_delete_mutation(content = get_graphql_content(response)assert not content["data"]["saleDelete"]["errors"]data = content["data"]["saleDelete"]["sale"]- assert data["name"] == sale.name- assert data["id"] == graphene.Node.to_global_id("Sale", sale.id)+ assert data["name"] == promotion.name+ assert data["id"] == graphene.Node.to_global_id("Sale", promotion.old_sale_id)assert not Promotion.objects.filter(id=promotion.id).first()- assert not PromotionRule.objects.filter(id=rules[0].id).first()+ assert not PromotionRule.objects.filter(promotion_id=promotion.id).first()with pytest.raises(promotion._meta.model.DoesNotExist):promotion.refresh_from_db()@@ -80,13 +74,12 @@ def test_sale_delete_mutation_with_promotion_id(deleted_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,):# givenquery = SALE_DELETE_MUTATION- convert_sales_to_promotions()- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion = promotion_converted_from_salevariables = {"id": graphene.Node.to_global_id("Promotion", promotion.id)}# whendiff --git a/saleor/graphql/discount/tests/mutations/test_sale_update.py b/saleor/graphql/discount/tests/mutations/test_sale_update.pyindex ca6969548d..e1fa161f0b 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_update.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_update.py@@ -5,14 +5,10 @@ import graphenefrom django.utils import timezonefrom freezegun import freeze_time-from .....discount import DiscountValueType+from .....discount import RewardValueTypefrom .....discount.error_codes import DiscountErrorCode-from .....discount.models import Promotion-from .....discount.tests.sale_converter import convert_sales_to_promotions-from .....discount.utils import fetch_catalogue_infofrom ....tests.utils import get_graphql_contentfrom ...enums import DiscountValueTypeEnum-from ...mutations.utils import convert_catalogue_info_to_global_idsfrom ...utils import convert_migrated_sale_predicate_to_catalogue_infoSALE_UPDATE_MUTATION = """@@ -42,7 +38,8 @@ def test_update_sale(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,product_list,):@@ -50,11 +47,12 @@ def test_update_sale(query = SALE_UPDATE_MUTATION# Set discount value type to 'fixed' and change it in mutation- sale.type = DiscountValueType.FIXED- sale.save(update_fields=["type"])+ promotion = promotion_converted_from_sale+ rule = promotion.rules.first()+ assert rule.reward_value_type == RewardValueType.FIXED- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)new_product_pks = [product.id for product in product_list]new_product_ids = [@@ -62,10 +60,8 @@ def test_update_sale(for product_id in new_product_pks]- convert_sales_to_promotions()-variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"type": DiscountValueTypeEnum.PERCENTAGE.name,"products": new_product_ids,@@ -81,10 +77,10 @@ def test_update_sale(content = get_graphql_content(response)assert not content["data"]["saleUpdate"]["errors"]data = content["data"]["saleUpdate"]["sale"]- assert data["type"] == DiscountValueType.PERCENTAGE.upper()- promotion = Promotion.objects.get(old_sale_id=sale.id)+ assert data["type"] == RewardValueType.PERCENTAGE.upper()+ promotion.refresh_from_db()rule = promotion.rules.first()- assert rule.reward_value_type == DiscountValueType.PERCENTAGE+ assert rule.reward_value_type == RewardValueType.PERCENTAGEcurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(rule.catalogue_predicate@@ -103,20 +99,21 @@ def test_update_sale_name(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,product_list,):# givenquery = SALE_UPDATE_MUTATION-+ promotion = promotion_converted_from_salenew_name = "New name"- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)- convert_sales_to_promotions()+variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"name": new_name,},@@ -132,7 +129,7 @@ def test_update_sale_name(assert not content["data"]["saleUpdate"]["errors"]data = content["data"]["saleUpdate"]["sale"]assert data["name"] == new_name- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert promotion.name == new_namecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(@@ -155,7 +152,8 @@ def test_update_sale_start_date_after_current_date_notification_not_sent(sale_toggle_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,):"""Ensure the notification is not sent when the start date is set after the current@@ -164,16 +162,16 @@ def test_update_sale_start_date_after_current_date_notification_not_sent(# givenquery = SALE_UPDATE_MUTATION- sale.notification_sent_datetime = None- sale.save(update_fields=["notification_sent_datetime"])- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ promotion.last_notification_scheduled_at = None+ promotion.save(update_fields=["last_notification_scheduled_at"])+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)start_date = timezone.now() + timedelta(days=1)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"startDate": start_date},}@@ -187,7 +185,7 @@ def test_update_sale_start_date_after_current_date_notification_not_sent(assert not content["data"]["saleUpdate"]["errors"]data = content["data"]["saleUpdate"]["sale"]assert data["startDate"] == start_date.isoformat()- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert promotion.start_date.isoformat() == start_date.isoformat()assert promotion.last_notification_scheduled_at is None@@ -212,7 +210,8 @@ def test_update_sale_start_date_before_current_date_notification_already_sent(sale_toggle_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,):"""Ensure the notification is not sent when the start date is set before@@ -220,21 +219,18 @@ def test_update_sale_start_date_before_current_date_notification_already_sent("""# givenquery = SALE_UPDATE_MUTATION- now = timezone.now()- # Set discount value type to 'fixed' and change it in mutation- sale.type = DiscountValueType.FIXED- notification_sent_datetime = now - timedelta(minutes=5)- sale.notification_sent_datetime = notification_sent_datetime- sale.save(update_fields=["type", "notification_sent_datetime"])- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ last_notification_scheduled_at = timezone.now() - timedelta(minutes=5)+ promotion.last_notification_scheduled_at = last_notification_scheduled_at+ promotion.save(update_fields=["last_notification_scheduled_at"])+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)start_date = timezone.now() - timedelta(days=1)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"startDate": start_date},}@@ -248,11 +244,11 @@ def test_update_sale_start_date_before_current_date_notification_already_sent(assert not content["data"]["saleUpdate"]["errors"]data = content["data"]["saleUpdate"]["sale"]assert data["startDate"] == start_date.isoformat()- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert promotion.start_date.isoformat() == start_date.isoformat()assert (promotion.last_notification_scheduled_at.isoformat()- == notification_sent_datetime.isoformat()+ == last_notification_scheduled_at.isoformat())current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(@@ -276,7 +272,8 @@ def test_update_sale_start_date_before_current_date_notification_sent(sale_toggle_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,):"""Ensure the sale_toggle notification is sent and the notification date is set@@ -286,18 +283,16 @@ def test_update_sale_start_date_before_current_date_notification_sent(# givenquery = SALE_UPDATE_MUTATION- # Set discount value type to 'fixed' and change it in mutation- sale.type = DiscountValueType.FIXED- sale.notification_sent_datetime = None- sale.save(update_fields=["type", "notification_sent_datetime"])- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ promotion.last_notification_scheduled_at = None+ promotion.save(update_fields=["last_notification_scheduled_at"])+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)start_date = timezone.now() - timedelta(days=1)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"startDate": start_date},}@@ -311,7 +306,7 @@ def test_update_sale_start_date_before_current_date_notification_sent(assert not content["data"]["saleUpdate"]["errors"]data = content["data"]["saleUpdate"]["sale"]assert data["startDate"] == start_date.isoformat()- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert promotion.start_date.isoformat() == start_date.isoformat()assert promotion.last_notification_scheduled_at == timezone.now()@@ -337,7 +332,8 @@ def test_update_sale_end_date_after_current_date_notification_not_sent(sale_toggle_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,):"""Ensure the notification is not sent when the end date is set after@@ -346,16 +342,16 @@ def test_update_sale_end_date_after_current_date_notification_not_sent(# givenquery = SALE_UPDATE_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ promotion.start_date = timezone.now() - timedelta(days=1)+ promotion.save(update_fields=["start_date"])+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)- sale.start_date = timezone.now() - timedelta(days=1)- sale.save(update_fields=["start_date"])end_date = timezone.now() + timedelta(days=1)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"endDate": end_date},}@@ -370,7 +366,7 @@ def test_update_sale_end_date_after_current_date_notification_not_sent(data = content["data"]["saleUpdate"]["sale"]assert data["endDate"] == end_date.isoformat()- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert promotion.end_date.isoformat() == end_date.isoformat()assert promotion.last_notification_scheduled_at is None@@ -395,7 +391,8 @@ def test_update_sale_end_date_before_current_date_notification_already_sent(sale_toggle_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,):"""Ensure the notification is sent when the end date is set before@@ -406,20 +403,18 @@ def test_update_sale_end_date_before_current_date_notification_already_sent(query = SALE_UPDATE_MUTATIONnow = timezone.now()- # Set discount value type to 'fixed' and change it in mutation- sale.type = DiscountValueType.FIXED- notification_sent_datetime = now - timedelta(minutes=5)- sale.notification_sent_datetime = notification_sent_datetime- sale.start_date = now - timedelta(days=2)- sale.save(update_fields=["type", "notification_sent_datetime", "start_date"])- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ last_notification_scheduled_at = now - timedelta(minutes=5)+ promotion.last_notification_scheduled_at = last_notification_scheduled_at+ promotion.start_date = now - timedelta(days=2)+ promotion.save(update_fields=["last_notification_scheduled_at", "start_date"])+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)end_date = now - timedelta(days=1)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"endDate": end_date},}@@ -433,7 +428,7 @@ def test_update_sale_end_date_before_current_date_notification_already_sent(assert not content["data"]["saleUpdate"]["errors"]data = content["data"]["saleUpdate"]["sale"]assert data["endDate"] == end_date.isoformat()- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert promotion.end_date.isoformat() == end_date.isoformat()assert promotion.last_notification_scheduled_at == now@@ -458,7 +453,8 @@ def test_update_sale_end_date_before_current_date_notification_sent(sale_toggle_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,):"""Ensure the sale_toggle notification is sent and the notification date is set@@ -468,19 +464,17 @@ def test_update_sale_end_date_before_current_date_notification_sent(# givenquery = SALE_UPDATE_MUTATION- # Set discount value type to 'fixed' and change it in mutation- sale.type = DiscountValueType.FIXED- sale.notification_sent_datetime = None- sale.start_date = timezone.now() - timedelta(days=2)- sale.save(update_fields=["type", "notification_sent_datetime", "start_date"])- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ promotion.last_notification_scheduled_at = None+ promotion.start_date = timezone.now() - timedelta(days=2)+ promotion.save(update_fields=["last_notification_scheduled_at", "start_date"])+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)end_date = timezone.now() - timedelta(days=1)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"endDate": end_date},}@@ -494,7 +488,7 @@ def test_update_sale_end_date_before_current_date_notification_sent(assert not content["data"]["saleUpdate"]["errors"]data = content["data"]["saleUpdate"]["sale"]assert data["endDate"] == end_date.isoformat()- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert promotion.end_date.isoformat() == end_date.isoformat()assert promotion.last_notification_scheduled_at == timezone.now()@@ -516,7 +510,8 @@ def test_update_sale_categories(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,product_list,non_default_category,@@ -524,14 +519,14 @@ def test_update_sale_categories(# givenquery = SALE_UPDATE_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)- convert_sales_to_promotions()new_category_id = graphene.Node.to_global_id("Category", non_default_category.id)variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"categories": [new_category_id],},@@ -545,7 +540,7 @@ def test_update_sale_categories(# thencontent = get_graphql_content(response)assert not content["data"]["saleUpdate"]["errors"]- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)assert current_catalogue["categories"] == {new_category_id}@@ -564,7 +559,8 @@ def test_update_sale_collections(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,product_list,published_collection,@@ -572,16 +568,16 @@ def test_update_sale_collections(# givenquery = SALE_UPDATE_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)new_collection_id = graphene.Node.to_global_id("Collection", published_collection.id)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"collections": [new_collection_id],},@@ -595,7 +591,7 @@ def test_update_sale_collections(# thencontent = get_graphql_content(response)assert not content["data"]["saleUpdate"]["errors"]- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)assert current_catalogue["collections"] == {new_collection_id}@@ -614,7 +610,8 @@ def test_update_sale_variants(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,product_list,preorder_variant_global_threshold,@@ -622,16 +619,16 @@ def test_update_sale_variants(# givenquery = SALE_UPDATE_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)- convert_sales_to_promotions()new_variant_id = graphene.Node.to_global_id("ProductVariant", preorder_variant_global_threshold.id)variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"variants": [new_variant_id],},@@ -645,7 +642,7 @@ def test_update_sale_variants(# thencontent = get_graphql_content(response)assert not content["data"]["saleUpdate"]["errors"]- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)assert current_catalogue["variants"] == {new_variant_id}@@ -664,7 +661,8 @@ def test_update_sale_products(updated_webhook_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,+ catalogue_predicate,permission_manage_discounts,product_list,published_collection,@@ -672,14 +670,14 @@ def test_update_sale_products(# givenquery = SALE_UPDATE_MUTATION- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)+ promotion = promotion_converted_from_sale+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(+ catalogue_predicate)- convert_sales_to_promotions()new_product_id = graphene.Node.to_global_id("Product", product_list[-1].id)variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"products": [new_product_id],},@@ -693,7 +691,7 @@ def test_update_sale_products(# thencontent = get_graphql_content(response)assert not content["data"]["saleUpdate"]["errors"]- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()predicate = promotion.rules.first().catalogue_predicatecurrent_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)assert current_catalogue["products"] == {new_product_id}@@ -715,19 +713,19 @@ def test_update_sale_end_date_before_start_date(sale_toggle_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,):# givenquery = SALE_UPDATE_MUTATION- sale.start_date = timezone.now() + timedelta(days=1)- sale.save(update_fields=["start_date"])+ promotion = promotion_converted_from_sale+ promotion.start_date = timezone.now() + timedelta(days=1)+ promotion.save(update_fields=["start_date"])end_date = timezone.now() - timedelta(days=1)- convert_sales_to_promotions()variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"endDate": end_date},}@@ -751,24 +749,23 @@ def test_update_sale_end_date_before_start_date(@freeze_time("2020-03-18 12:00:00")def test_update_sale_with_none_values(staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,):"""Ensure that non-required fields can be nullified."""# givenquery = SALE_UPDATE_MUTATION+ promotion = promotion_converted_from_sale- sale.name = "Sale name"- sale.type = DiscountValueType.FIXED+ promotion.name = "Sale name"start_date = timezone.now() + timedelta(days=1)- sale.start_date = start_date- sale.end_date = timezone.now() + timedelta(days=5)- sale.save(update_fields=["name", "type", "start_date", "end_date"])- convert_sales_to_promotions()+ promotion.start_date = start_date+ promotion.end_date = timezone.now() + timedelta(days=5)+ promotion.save(update_fields=["name", "start_date", "end_date"])variables = {- "id": graphene.Node.to_global_id("Sale", sale.id),+ "id": graphene.Node.to_global_id("Sale", promotion.old_sale_id),"input": {"name": None,"startDate": None,@@ -790,18 +787,18 @@ def test_update_sale_with_none_values(content = get_graphql_content(response)assert not content["data"]["saleUpdate"]["errors"]data = content["data"]["saleUpdate"]["sale"]- assert data["type"] == DiscountValueType.FIXED.upper()+ assert data["type"] == RewardValueType.FIXED.upper()assert data["name"] == "Sale name"assert data["startDate"] == start_date.isoformat()assert not data["endDate"]- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert promotion.start_date.isoformat() == start_date.isoformat()assert promotion.start_date == start_dateassert not promotion.end_daterule = promotion.rules.first()- assert rule.reward_value_type == DiscountValueType.FIXED+ assert rule.reward_value_type == RewardValueType.FIXEDassert not rule.catalogue_predicate@@ -815,14 +812,13 @@ def test_update_sale_with_promotion_id(sale_toggle_mock,update_products_discounted_prices_for_promotion_task_mock,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_discounts,):# givenquery = SALE_UPDATE_MUTATION+ promotion = promotion_converted_from_saleend_date = timezone.now() - timedelta(days=1)- convert_sales_to_promotions()- promotion = Promotion.objects.get(old_sale_id=sale.id)variables = {"id": graphene.Node.to_global_id("Promotion", promotion.id),diff --git a/saleor/graphql/discount/tests/queries/test_sale.py b/saleor/graphql/discount/tests/queries/test_sale.pyindex a00fcefc25..08e9561315 100644--- a/saleor/graphql/discount/tests/queries/test_sale.py+++ b/saleor/graphql/discount/tests/queries/test_sale.py@@ -132,7 +132,7 @@ def test_query_sale_by_customer(api_client, promotion_converted_from_sale):def test_staff_query_sale_by_invalid_id(- staff_api_client, sale, permission_manage_discounts+ staff_api_client, promotion_converted_from_sale, permission_manage_discounts):# givenid = "bh/"diff --git a/saleor/graphql/discount/tests/queries/test_sales.py b/saleor/graphql/discount/tests/queries/test_sales.pyindex 37809f8eca..d13eef6ffa 100644--- a/saleor/graphql/discount/tests/queries/test_sales.py+++ b/saleor/graphql/discount/tests/queries/test_sales.py@@ -1,4 +1,3 @@-from .....discount.tests.sale_converter import convert_sales_to_promotionsfrom ....tests.utils import get_graphql_content@@ -118,13 +117,12 @@ def test_sale_query_with_channel_slug(def test_sales_query(staff_api_client,- sale_with_many_channels,- sale,+ promotion_converted_from_sale,+ promotion_converted_from_sale_with_empty_predicate,permission_manage_discounts,channel_USD,permission_manage_products,):- convert_sales_to_promotions()query = """query sales {sales(first: 2) {@@ -147,13 +145,12 @@ def test_sales_query(def test_sales_query_with_channel_slug(staff_api_client,- sale_with_many_channels,- sale,+ promotion_converted_from_sale_with_empty_predicate,+ promotion_converted_from_sale_with_many_channels,permission_manage_discounts,channel_PLN,permission_manage_products,):- convert_sales_to_promotions()query = """query sales($channel: String) {sales(first: 2, channel: $channel) {@@ -178,13 +175,12 @@ def test_sales_query_with_channel_slug(def test_sales_query_channel_listing(staff_api_client,- sale_with_many_channels,+ promotion_converted_from_sale_with_many_channels,permission_manage_discounts,channel_USD,channel_PLN,):# given- convert_sales_to_promotions()query = """query sales {sales(first: 10) {diff --git a/saleor/graphql/discount/tests/queries/test_sales_filtering.py b/saleor/graphql/discount/tests/queries/test_sales_filtering.pyindex dcefa5b57c..44dd74eb2d 100644--- a/saleor/graphql/discount/tests/queries/test_sales_filtering.py+++ b/saleor/graphql/discount/tests/queries/test_sales_filtering.py@@ -3,9 +3,8 @@ from datetime import timedeltaimport pytestfrom django.utils import timezone-from .....discount import DiscountValueType-from .....discount.models import Promotion, Sale, SaleChannelListing-from .....discount.tests.sale_converter import convert_sales_to_promotions+from .....discount import RewardValueType+from .....discount.models import Promotion, PromotionRulefrom ....tests.utils import get_graphql_contentQUERY_SALES_WITH_FILTER = """@@ -56,24 +55,15 @@ def test_query_sales_with_filter_status(channel_USD,):# given- sales = Sale.objects.bulk_create(+ promotions = Promotion.objects.bulk_create([- Sale(name="Sale1", start_date=timezone.now()),- Sale(name="Sale2", start_date=start_date, end_date=end_date),+ Promotion(name="Sale1", start_date=timezone.now()),+ Promotion(name="Sale2", start_date=start_date, end_date=end_date),])- SaleChannelListing.objects.bulk_create(- [- SaleChannelListing(- sale=sale,- discount_value=123,- channel=channel_USD,- currency=channel_USD.currency_code,- )- for sale in sales- ]- )- convert_sales_to_promotions()+ for promotion in promotions:+ promotion.assign_old_sale_id()+variables = {"filter": sale_filter}# when@@ -90,8 +80,8 @@ def test_query_sales_with_filter_status(@pytest.mark.parametrize("sale_filter, count, sale_type",[- ({"saleType": "PERCENTAGE"}, 1, DiscountValueType.PERCENTAGE),- ({"saleType": "FIXED"}, 2, DiscountValueType.FIXED),+ ({"saleType": "PERCENTAGE"}, 1, RewardValueType.PERCENTAGE),+ ({"saleType": "FIXED"}, 2, RewardValueType.FIXED),],)def test_query_sales_with_filter_discount_type(@@ -102,13 +92,25 @@ def test_query_sales_with_filter_discount_type(permission_manage_discounts,):# given- Sale.objects.bulk_create(+ promotions = Promotion.objects.bulk_create([- Sale(name="Sale1", type=DiscountValueType.FIXED),- Sale(name="Sale2", type=sale_type),+ Promotion(name="Sale1"),+ Promotion(name="Sale2"),])- convert_sales_to_promotions()+ for promotion in promotions:+ promotion.assign_old_sale_id()+ PromotionRule.objects.create(+ promotion=promotions[0],+ reward_value=123,+ reward_value_type=RewardValueType.FIXED,+ )+ PromotionRule.objects.create(+ promotion=promotions[1],+ reward_value=123,+ reward_value_type=sale_type,+ )+variables = {"filter": sale_filter}# when@@ -147,27 +149,18 @@ def test_query_sales_with_filter_started(channel_USD,):# given- sales = Sale.objects.bulk_create(+ promotions = Promotion.objects.bulk_create([- Sale(name="Sale1"),- Sale(+ Promotion(name="Sale1"),+ Promotion(name="Sale2",start_date=timezone.now().replace(year=2012, month=1, day=5),),])- SaleChannelListing.objects.bulk_create(- [- SaleChannelListing(- sale=sale,- discount_value=123,- channel=channel_USD,- currency=channel_USD.currency_code,- )- for sale in sales- ]- )- convert_sales_to_promotions()+ for promotion in promotions:+ promotion.assign_old_sale_id()+variables = {"filter": sale_filter}# when@@ -209,22 +202,15 @@ def test_query_sales_with_filter_updated_at(channel_USD,):# given- sale_1 = Sale.objects.create(name="Sale1")- sale_2 = Sale.objects.create(name="Sale2")- SaleChannelListing.objects.bulk_create(+ promotions = Promotion.objects.bulk_create([- SaleChannelListing(- sale=sale,- discount_value=123,- channel=channel_USD,- currency=channel_USD.currency_code,- )- for sale in [sale_1, sale_2]+ Promotion(name="Sale1"),+ Promotion(name="Sale2"),])+ for promotion in promotions:+ promotion.assign_old_sale_id()- convert_sales_to_promotions()- promotions = Promotion.objects.all()assert len(promotions) == 2promotions[0].updated_at = timezone.now().replace(year=2012, month=1, day=14, hour=11, minute=0, second=0@@ -259,29 +245,36 @@ def test_query_sales_with_filter_search(channel_USD,):# given- sales = Sale.objects.bulk_create(+ promotions = Promotion.objects.bulk_create([- Sale(name="BigSale", type="PERCENTAGE"),- Sale(+ Promotion(name="BigSale"),+ Promotion(name="Sale2",- type="FIXED",start_date=timezone.now().replace(year=2012, month=1, day=5),),- Sale(+ Promotion(name="Sale3",- type="FIXED",start_date=timezone.now().replace(year=2012, month=1, day=5),),])+ for promotion in promotions:+ promotion.assign_old_sale_id()+values = [123, 123, 69]- SaleChannelListing.objects.bulk_create(+ types = [RewardValueType.PERCENTAGE, RewardValueType.FIXED, RewardValueType.FIXED]++ PromotionRule.objects.bulk_create([- SaleChannelListing(channel=channel_USD, discount_value=values[i], sale=sale)- for i, sale in enumerate(sales)+ PromotionRule(+ promotion=promotion,+ reward_value=values[i],+ reward_value_type=types[i],+ )+ for i, promotion in enumerate(promotions)])- convert_sales_to_promotions()+variables = {"filter": sale_filter}# whendiff --git a/saleor/graphql/discount/tests/queries/test_sales_pagination.py b/saleor/graphql/discount/tests/queries/test_sales_pagination.pyindex c0f39dcf35..e651cf6a6b 100644--- a/saleor/graphql/discount/tests/queries/test_sales_pagination.py+++ b/saleor/graphql/discount/tests/queries/test_sales_pagination.py@@ -4,9 +4,8 @@ import pytestfrom django.utils import timezonefrom freezegun import freeze_time-from .....discount import DiscountValueType-from .....discount.models import Promotion, Sale, SaleChannelListing-from .....discount.tests.sale_converter import convert_sales_to_promotions+from .....discount import RewardValueType+from .....discount.models import Promotion, PromotionRulefrom ....tests.utils import get_graphql_content@@ -14,48 +13,52 @@ from ....tests.utils import get_graphql_content@freeze_time("2020-03-18 12:00:00")def sales_for_pagination(channel_USD):now = timezone.now()- sales = Sale.objects.bulk_create(+ promotions = Promotion.objects.bulk_create([- Sale(+ Promotion(name="Sale1",start_date=now + timezone.timedelta(hours=4),end_date=now + timezone.timedelta(hours=14),- type=DiscountValueType.PERCENTAGE,),- Sale(+ Promotion(name="Sale2",end_date=now + timezone.timedelta(hours=1),),- Sale(+ Promotion(name="Sale3",end_date=now + timezone.timedelta(hours=2),- type=DiscountValueType.PERCENTAGE,),- Sale(+ Promotion(name="Sale4",end_date=now + timezone.timedelta(hours=1),),- Sale(+ Promotion(name="Sale15",start_date=now + timezone.timedelta(hours=1),end_date=now + timezone.timedelta(hours=2),),])+ for promotion in promotions:+ promotion.assign_old_sale_id()+values = [Decimal("1"), Decimal("7"), Decimal("5"), Decimal("5"), Decimal("25")]- SaleChannelListing.objects.bulk_create(+ rules = PromotionRule.objects.bulk_create([- SaleChannelListing(- discount_value=values[i],- sale=sale,- channel=channel_USD,- currency=channel_USD.currency_code,+ PromotionRule(+ promotion=promotion,+ reward_value=values[i],+ reward_value_type=RewardValueType.FIXED,)- for i, sale in enumerate(sales)+ for i, promotion in enumerate(promotions)])- convert_sales_to_promotions()- promotions = Promotion.objects.order_by("created_at").all()+ rules[0].reward_value_type = RewardValueType.PERCENTAGE+ rules[2].reward_value_type = RewardValueType.PERCENTAGE+ PromotionRule.objects.bulk_update(rules, fields=["reward_value_type"])+ for rule in rules:+ rule.channels.add(channel_USD)+return promotions@@ -101,7 +104,7 @@ def test_sales_pagination_with_sorting(permission_manage_discounts,sales_for_pagination,):- page_size = 3+ page_size = 5variables = {"first": page_size, "after": None, "sortBy": sort_by}response = staff_api_client.post_graphql(diff --git a/saleor/graphql/discount/tests/queries/test_sales_sorting.py b/saleor/graphql/discount/tests/queries/test_sales_sorting.pyindex 584474a19a..b905277f28 100644--- a/saleor/graphql/discount/tests/queries/test_sales_sorting.py+++ b/saleor/graphql/discount/tests/queries/test_sales_sorting.py@@ -1,84 +1,72 @@import pytestfrom django.utils import timezone-from .....discount import DiscountValueType-from .....discount.models import Promotion, Sale, SaleChannelListing-from .....discount.tests.sale_converter import convert_sales_to_promotions+from .....discount import RewardValueType+from .....discount.models import Promotion, PromotionRulefrom ....tests.utils import assert_graphql_error_with_message, get_graphql_content@pytest.fixturedef sales_for_sorting_with_channels(db, channel_USD, channel_PLN):- sales = Sale.objects.bulk_create(+ promotions = Promotion.objects.bulk_create([- Sale(- name="Sale1",- type=DiscountValueType.PERCENTAGE,- ),- Sale(name="Sale2"),- Sale(- name="Sale3",- type=DiscountValueType.PERCENTAGE,- ),- Sale(name="Sale4"),- Sale(name="Sale15"),+ Promotion(name="Sale1"),+ Promotion(name="Sale2"),+ Promotion(name="Sale3"),+ Promotion(name="Sale4"),+ Promotion(name="Sale15"),])- SaleChannelListing.objects.bulk_create(++ for promotion in promotions:+ promotion.assign_old_sale_id()++ rules = PromotionRule.objects.bulk_create([- SaleChannelListing(- discount_value=1,- sale=sales[0],- channel=channel_USD,- currency=channel_USD.currency_code,+ PromotionRule(+ promotion=promotions[0],+ reward_value=1,+ reward_value_type=RewardValueType.PERCENTAGE,),- SaleChannelListing(- discount_value=7,- sale=sales[0],- channel=channel_PLN,- currency=channel_PLN.currency_code,+ PromotionRule(+ promotion=promotions[0],+ reward_value=7,+ reward_value_type=RewardValueType.PERCENTAGE,),- SaleChannelListing(- discount_value=7,- sale=sales[1],- channel=channel_USD,- currency=channel_USD.currency_code,+ PromotionRule(+ promotion=promotions[1],+ reward_value=7,+ reward_value_type=RewardValueType.FIXED,),- SaleChannelListing(- discount_value=1,- sale=sales[1],- channel=channel_PLN,- currency=channel_PLN.currency_code,+ PromotionRule(+ promotion=promotions[1],+ reward_value=1,+ reward_value_type=RewardValueType.FIXED,),- SaleChannelListing(- discount_value=5,- sale=sales[2],- channel=channel_USD,- currency=channel_USD.currency_code,+ PromotionRule(+ promotion=promotions[2],+ reward_value=5,+ reward_value_type=RewardValueType.PERCENTAGE,),- SaleChannelListing(- discount_value=2,- sale=sales[3],- channel=channel_PLN,- currency=channel_PLN.currency_code,+ PromotionRule(+ promotion=promotions[3],+ reward_value=2,+ reward_value_type=RewardValueType.FIXED,),- SaleChannelListing(- discount_value=2,- sale=sales[4],- channel=channel_USD,- currency=channel_USD.currency_code,+ PromotionRule(+ promotion=promotions[4],+ reward_value=2,+ reward_value_type=RewardValueType.FIXED,),- SaleChannelListing(- discount_value=5,- sale=sales[4],- channel=channel_PLN,- currency=channel_PLN.currency_code,+ PromotionRule(+ promotion=promotions[4],+ reward_value=5,+ reward_value_type=RewardValueType.FIXED,),])-- convert_sales_to_promotions()- promotions = Promotion.objects.order_by("created_at").all()+ channel_USD.promotionrule_set.add(rules[0], rules[2], rules[4], rules[6])+ channel_PLN.promotionrule_set.add(rules[1], rules[3], rules[5], rules[7])promotions[4].save()promotions[2].save()@@ -290,24 +278,37 @@ def test_query_sales_with_sort(sale_sort, result_order, staff_api_client, permission_manage_discounts, channel_USD):# given- Sale.objects.bulk_create(+ promotions = Promotion.objects.bulk_create([- Sale(name="BigSale", type="PERCENTAGE"),- Sale(+ Promotion(name="BigSale"),+ Promotion(name="Sale2",- type="FIXED",start_date=timezone.now().replace(year=2012, month=1, day=5),end_date=timezone.now().replace(year=2013, month=1, day=5),),- Sale(+ Promotion(name="Sale3",- type="FIXED",start_date=timezone.now().replace(year=2011, month=1, day=5),end_date=timezone.now().replace(year=2015, month=12, day=31),),])- convert_sales_to_promotions()+ for promotion in promotions:+ promotion.assign_old_sale_id()++ rules = PromotionRule.objects.bulk_create(+ [+ PromotionRule(+ promotion=promotion,+ reward_value=5,+ reward_value_type=RewardValueType.FIXED,+ )+ for promotion in promotions+ ]+ )+ rules[0].reward_value_type = RewardValueType.PERCENTAGE+ rules[0].save(update_fields=["reward_value_type"])+variables = {"sort_by": sale_sort}staff_api_client.user.user_permissions.add(permission_manage_discounts)diff --git a/saleor/graphql/discount/types/sales.py b/saleor/graphql/discount/types/sales.pyindex 450f0eb10a..b656018817 100644--- a/saleor/graphql/discount/types/sales.py+++ b/saleor/graphql/discount/types/sales.py@@ -62,7 +62,7 @@ class SaleChannelListing(BaseObjectType):doc_category = DOC_CATEGORY_DISCOUNTS-class Sale(ChannelContextTypeWithMetadata, ModelObjectType[models.Sale]):+class Sale(ChannelContextTypeWithMetadata, ModelObjectType[models.Promotion]):id = graphene.GlobalID(required=True, description="The ID of the sale.")name = graphene.String(required=True, description="The name of the sale.")type = SaleType(required=True, description="Type of the sale, fixed or percentage.")diff --git a/saleor/graphql/discount/utils.py b/saleor/graphql/discount/utils.pyindex e7184d87de..421cf950f2 100644--- a/saleor/graphql/discount/utils.py+++ b/saleor/graphql/discount/utils.py@@ -323,3 +323,19 @@ def subtract_catalogues_info(new_catalogue["products"] -= catalogue_2.get("products", set())new_catalogue["variants"] -= catalogue_2.get("variants", set())return new_catalogue+++def create_catalogue_predicate(collection_ids, category_ids, product_ids, variant_ids):+ predicate: Dict[str, List] = {"OR": []}+ if collection_ids:+ predicate["OR"].append({"collectionPredicate": {"ids": collection_ids}})+ if category_ids:+ predicate["OR"].append({"categoryPredicate": {"ids": category_ids}})+ if product_ids:+ predicate["OR"].append({"productPredicate": {"ids": product_ids}})+ if variant_ids:+ predicate["OR"].append({"variantPredicate": {"ids": variant_ids}})+ if not predicate.get("OR"):+ predicate = {}++ return predicatediff --git a/saleor/graphql/meta/mutations/base.py b/saleor/graphql/meta/mutations/base.pyindex d27f633e18..4467b11a73 100644--- a/saleor/graphql/meta/mutations/base.py+++ b/saleor/graphql/meta/mutations/base.py@@ -263,7 +263,6 @@ class BaseMetadataMutation(BaseMutation):[isinstance(instance, Model)for Model in [- discount_models.Sale,discount_models.Voucher,menu_models.Menu,menu_models.MenuItem,diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.pyindex fd2b15b3a2..60b440108f 100644--- a/saleor/graphql/meta/resolvers.py+++ b/saleor/graphql/meta/resolvers.py@@ -58,7 +58,6 @@ def resolve_object_with_metadata_type(instance):checkout_models.CheckoutMetadata: checkout_types.Checkout,checkout_models.CheckoutLine: checkout_types.CheckoutLine,discount_models.Promotion: discount_types.Promotion,- discount_models.Sale: discount_types.Sale,discount_models.Voucher: discount_types.Voucher,giftcard_models.GiftCard: giftcard_types.GiftCard,invoice_models.Invoice: invoice_types.Invoice,@@ -85,6 +84,10 @@ def resolve_object_with_metadata_type(instance):tax_models.TaxConfiguration: tax_types.TaxConfiguration,warehouse_models.Warehouse: warehouse_types.Warehouse,}+ if instance.__class__ == discount_models.Promotion and getattr(+ instance, "old_sale_id"+ ):+ return discount_types.Sale, instance.pkreturn MODEL_TO_TYPE_MAP.get(instance.__class__, None), instance.pkelif dataclasses.is_dataclass(instance):diff --git a/saleor/graphql/meta/tests/mutations/test_discount.py b/saleor/graphql/meta/tests/mutations/test_discount.pyindex b9c830e896..68056b281c 100644--- a/saleor/graphql/meta/tests/mutations/test_discount.py+++ b/saleor/graphql/meta/tests/mutations/test_discount.py@@ -1,7 +1,5 @@import graphene-from .....discount.models import Promotion-from .....discount.tests.sale_converter import convert_sales_to_promotionsfrom . import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUEfrom .test_delete_metadata import (execute_clear_public_metadata_for_item,@@ -41,13 +39,13 @@ def test_delete_public_metadata_for_voucher(def test_delete_public_metadata_for_sale(- staff_api_client, permission_manage_discounts, sale+ staff_api_client, permission_manage_discounts, promotion_converted_from_sale):# given- sale.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})- sale.save(update_fields=["metadata"])- sale_id = graphene.Node.to_global_id("Sale", sale.pk)- convert_sales_to_promotions()+ promotion = promotion_converted_from_sale+ promotion.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})+ promotion.save(update_fields=["metadata"])+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)# whenresponse = execute_clear_public_metadata_for_item(@@ -55,7 +53,7 @@ def test_delete_public_metadata_for_sale()# then- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert item_without_public_metadata(response["data"]["deleteMetadata"]["item"], promotion, sale_id)@@ -81,13 +79,13 @@ def test_delete_private_metadata_for_voucher(def test_delete_private_metadata_for_sale(- staff_api_client, permission_manage_discounts, sale+ staff_api_client, permission_manage_discounts, promotion_converted_from_sale):# given- sale.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})- sale.save(update_fields=["private_metadata"])- sale_id = graphene.Node.to_global_id("Sale", sale.pk)- convert_sales_to_promotions()+ promotion = promotion_converted_from_sale+ promotion.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})+ promotion.save(update_fields=["private_metadata"])+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)# whenresponse = execute_clear_private_metadata_for_item(@@ -95,7 +93,7 @@ def test_delete_private_metadata_for_sale()# then- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert item_without_private_metadata(response["data"]["deletePrivateMetadata"]["item"], promotion, sale_id)@@ -119,11 +117,11 @@ def test_add_public_metadata_for_voucher(def test_add_private_metadata_for_sale(- staff_api_client, permission_manage_discounts, sale+ staff_api_client, permission_manage_discounts, promotion_converted_from_sale):# given- sale_id = graphene.Node.to_global_id("Sale", sale.pk)- convert_sales_to_promotions()+ promotion = promotion_converted_from_sale+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)# whenresponse = execute_update_private_metadata_for_item(@@ -131,7 +129,7 @@ def test_add_private_metadata_for_sale()# then- promotion = Promotion.objects.get(old_sale_id=sale.id)+ promotion.refresh_from_db()assert item_contains_proper_private_metadata(response["data"]["updatePrivateMetadata"]["item"], promotion, sale_id)diff --git a/saleor/graphql/product/tests/benchmark/conftest.py b/saleor/graphql/product/tests/benchmark/conftest.pyindex e97b131ce4..7b31e1a786 100644--- a/saleor/graphql/product/tests/benchmark/conftest.py+++ b/saleor/graphql/product/tests/benchmark/conftest.py@@ -1,25 +1,40 @@import pytest-from .....discount.models import Sale, SaleChannelListing+from .....discount import RewardValueType+from .....discount.models import Promotion, PromotionRulefrom .....product.models import Category@pytest.fixture-def sales_list(channel_USD):- sales = Sale.objects.bulk_create([Sale(name="Sale1"), Sale(name="Sale2")])+def promotion_converted_from_sale_list(channel_USD):+ promotions = Promotion.objects.bulk_create(+ [Promotion(name="Sale1"), Promotion(name="Sale2")]+ )+ for promotion in promotions:+ promotion.assign_old_sale_id()+values = [15, 5]- SaleChannelListing.objects.bulk_create(++ rules = PromotionRule.objects.bulk_create([- SaleChannelListing(- sale=sale,- channel=channel_USD,- discount_value=values[i],- currency=channel_USD.currency_code,+ PromotionRule(+ promotion=promotion,+ catalogue_predicate={},+ reward_value_type=RewardValueType.FIXED,+ reward_value=value,)- for i, sale in enumerate(sales)+ for promotion, value in zip(promotions, values)])- return list(sales)+ PromotionRuleChannel = PromotionRule.channels.through++ rules_channels = [+ PromotionRuleChannel(promotionrule_id=rule.id, channel_id=channel_USD.id)+ for rule in rules+ ]+ PromotionRuleChannel.objects.bulk_create(rules_channels)++ return promotions@pytest.fixture@@ -31,7 +46,7 @@ def category_with_products(product_with_variant_with_two_attributes,product_with_multiple_values_attributes,product_without_shipping,- sales_list,+ promotion_converted_from_sale_list,):category = categories_treechild = Category.objects.create(name="TestCategory", slug="test-cat")diff --git a/saleor/graphql/product/tests/test_product_discounted_price.py b/saleor/graphql/product/tests/test_product_discounted_price.pyindex aa616adaa6..451459764f 100644--- a/saleor/graphql/product/tests/test_product_discounted_price.py+++ b/saleor/graphql/product/tests/test_product_discounted_price.py@@ -4,7 +4,6 @@ from freezegun import freeze_timefrom graphql_relay import to_global_idfrom ....discount.models import Promotion-from ....discount.tests.sale_converter import convert_sales_to_promotionsfrom ...discount.enums import DiscountValueTypeEnumfrom ...tests.utils import get_graphql_content@@ -264,7 +263,8 @@ def test_sale_create_updates_products_discounted_prices(def test_sale_update_updates_products_discounted_prices(mock_update_products_discounted_prices_for_promotion,staff_api_client,- sale,+ promotion_converted_from_sale,+ product,permission_manage_discounts,):# given@@ -281,10 +281,10 @@ def test_sale_update_updates_products_discounted_prices(}}"""- product_ids = set(sale.products.values_list("id", flat=True).all())- convert_sales_to_promotions()+ promotion = promotion_converted_from_sale+variables = {- "id": to_global_id("Sale", sale.pk),+ "id": to_global_id("Sale", promotion.old_sale_id),"type": DiscountValueTypeEnum.PERCENTAGE.name,}@@ -299,7 +299,7 @@ def test_sale_update_updates_products_discounted_prices(assert content["data"]["saleUpdate"]["errors"] == []args, _ = mock_update_products_discounted_prices_for_promotion.delay.call_args- assert set(args[0]) == product_ids+ assert args[0] == [product.id]@patch(@@ -309,7 +309,8 @@ def test_sale_update_updates_products_discounted_prices(def test_sale_delete_updates_products_discounted_prices(mock_update_products_discounted_prices_for_promotion,staff_api_client,- sale,+ promotion_converted_from_sale,+ product,permission_manage_discounts,):# given@@ -326,9 +327,8 @@ def test_sale_delete_updates_products_discounted_prices(}}"""- variables = {"id": to_global_id("Sale", sale.pk)}- convert_sales_to_promotions()- product_ids = set(sale.products.values_list("id", flat=True))+ promotion = promotion_converted_from_sale+ variables = {"id": to_global_id("Sale", promotion.old_sale_id)}# whenresponse = staff_api_client.post_graphql(@@ -342,7 +342,7 @@ def test_sale_delete_updates_products_discounted_prices(assert content["data"]["saleDelete"]["errors"] == []args, _ = mock_update_products_discounted_prices_for_promotion.delay.call_args- assert set(args[0]) == product_ids+ assert args[0] == [product.id]@patch(@@ -352,7 +352,7 @@ def test_sale_delete_updates_products_discounted_prices(def test_sale_add_catalogues_updates_products_discounted_prices(mock_update_products_discounted_prices_for_promotion,staff_api_client,- new_sale,+ promotion_converted_from_sale_with_empty_predicate,product_list,permission_manage_discounts,):@@ -370,16 +370,18 @@ def test_sale_add_catalogues_updates_products_discounted_prices(}}"""- sale = new_sale- sale.products.add(product_list[0])- sale_id = to_global_id("Sale", sale.pk)- product_ids = [to_global_id("Product", product.pk) for product in product_list[1:]]- convert_sales_to_promotions()+ promotion = promotion_converted_from_sale_with_empty_predicate+ sale_id = to_global_id("Sale", promotion.old_sale_id)+ product_ids = [to_global_id("Product", product.pk) for product in product_list]+ predicate = {"OR": [{"productPredicate": {"ids": [product_ids[0]]}}]}+ rule = promotion.rules.first()+ rule.catalogue_predicate = predicate+ rule.save(update_fields=["catalogue_predicate"])variables = {"id": sale_id,"input": {- "products": product_ids,+ "products": product_ids[1:],},}@@ -405,14 +407,19 @@ def test_sale_add_catalogues_updates_products_discounted_prices(def test_sale_remove_catalogues_updates_products_discounted_prices(mock_update_products_discounted_prices_for_promotion,staff_api_client,- new_sale,+ promotion_converted_from_sale_with_empty_predicate,product_list,permission_manage_discounts,):# given- sale = new_sale- sale.products.add(*product_list)- convert_sales_to_promotions()+ promotion = promotion_converted_from_sale_with_empty_predicate+ sale_id = to_global_id("Sale", promotion.old_sale_id)+ product_ids = [to_global_id("Product", product.pk) for product in product_list]+ predicate = {"OR": [{"productPredicate": {"ids": product_ids}}]}+ rule = promotion.rules.first()+ rule.catalogue_predicate = predicate+ rule.save(update_fields=["catalogue_predicate"])+ product_id = to_global_id("Product", product_list[-1].pk)query = """mutation SaleCataloguesRemove($id: ID!, $input: CatalogueInput!) {@@ -428,9 +435,6 @@ def test_sale_remove_catalogues_updates_products_discounted_prices(}"""- sale_id = to_global_id("Sale", sale.pk)- product_id = to_global_id("Product", product_list[-1].pk)-variables = {"id": sale_id,"input": {diff --git a/saleor/graphql/product/tests/test_variant_pricing.py b/saleor/graphql/product/tests/test_variant_pricing.pyindex 5352b481ec..fffe968fdb 100644--- a/saleor/graphql/product/tests/test_variant_pricing.py+++ b/saleor/graphql/product/tests/test_variant_pricing.py@@ -55,54 +55,16 @@ query ($channel: String, $address: AddressInput) {"""-def test_get_variant_pricing_on_sale(api_client, sale, product, channel_USD):- # given- variant_listing = product.variants.first().channel_listings.get()- price = variant_listing.price- sale_discounted_value = sale.channel_listings.get().discount_value- discounted_price = price.amount - sale_discounted_value- variant_listing.discounted_price_amount = discounted_price- variant_listing.save(update_fields=["discounted_price_amount"])-- variables = {"channel": channel_USD.slug, "address": {"country": "US"}}-- # when- response = api_client.post_graphql(QUERY_GET_VARIANT_PRICING, variables)-- # then- content = get_graphql_content(response)-- pricing = content["data"]["products"]["edges"][0]["node"]["variants"][0]["pricing"]-- # ensure the availability was correctly retrieved and sent- assert pricing-- # check availability- assert pricing["onSale"] is True-- # check the discount- assert pricing["discount"]["currency"] == price.currency- assert pricing["discount"]["net"]["amount"] == discounted_price-- # check the undiscounted price- assert pricing["priceUndiscounted"]["currency"] == price.currency- assert pricing["priceUndiscounted"]["net"]["amount"] == price.amount-- # check the discounted price- assert pricing["price"]["currency"] == price.currency- assert pricing["price"]["net"]["amount"] == discounted_price---def test_get_variant_pricing_on_promotion(api_client, promotion, product, channel_USD):+def test_get_variant_pricing_on_promotion(+ api_client, promotion_with_single_rule, product, channel_USD+):# givenvariant_listing = product.variants.first().channel_listings.get()price = variant_listing.price-+ promotion = promotion_with_single_rulerule = promotion.rules.first()-- discount_amount = rule.reward_value / 100 * price.amount-- discounted_price = price.amount - discount_amount+ discounted_value = rule.reward_value+ discounted_price = price.amount - discounted_valuevariant_listing.discounted_price_amount = discounted_pricevariant_listing.save(update_fields=["discounted_price_amount"])@@ -124,7 +86,7 @@ def test_get_variant_pricing_on_promotion(api_client, promotion, product, channe# check the discountassert pricing["discount"]["currency"] == price.currency- assert pricing["discount"]["net"]["amount"] == discount_amount+ assert pricing["discount"]["net"]["amount"] == discounted_price# check the undiscounted priceassert pricing["priceUndiscounted"]["currency"] == price.currencydiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex c4fefccc4f..4a6d0798d5 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -8316,7 +8316,7 @@ type TranslatableItemEdge {cursor: String!}-union TranslatableItem = ProductTranslatableContent | CollectionTranslatableContent | CategoryTranslatableContent | AttributeTranslatableContent | AttributeValueTranslatableContent | ProductVariantTranslatableContent | PageTranslatableContent | ShippingMethodTranslatableContent | SaleTranslatableContent | VoucherTranslatableContent | MenuItemTranslatableContent | PromotionTranslatableContent | PromotionRuleTranslatableContent+union TranslatableItem = ProductTranslatableContent | CollectionTranslatableContent | CategoryTranslatableContent | AttributeTranslatableContent | AttributeValueTranslatableContent | ProductVariantTranslatableContent | PageTranslatableContent | ShippingMethodTranslatableContent | VoucherTranslatableContent | MenuItemTranslatableContent | PromotionTranslatableContent | PromotionRuleTranslatableContent | SaleTranslatableContent"""Represents product's original translatable fields and related translations.@@ -8815,282 +8815,6 @@ type ShippingMethodTranslatableContent implements Node @doc(category: "Shipping"shippingMethod: ShippingMethodType @deprecated(reason: "This field will be removed in Saleor 4.0. Get model fields from the root level queries.")}-"""-Represents sale's original translatable fields and related translations.--DEPRECATED: this type will be removed in Saleor 4.0. Use `PromotionTranslatableContent` instead.-"""-type SaleTranslatableContent implements Node @doc(category: "Discounts") {- """The ID of the sale translatable content."""- id: ID!-- """Name of the sale to translate."""- name: String!-- """Returns translated sale fields for the given language code."""- translation(- """A language code to return the translation for sale."""- languageCode: LanguageCodeEnum!- ): SaleTranslation-- """- Sales allow creating discounts for categories, collections or products and are visible to all the customers.-- Requires one of the following permissions: MANAGE_DISCOUNTS.- """- sale: Sale @deprecated(reason: "This field will be removed in Saleor 4.0. Get model fields from the root level queries.")-}--"""-Represents sale translations.--DEPRECATED: this type will be removed in Saleor 4.0. Use `PromotionTranslation` instead.-"""-type SaleTranslation implements Node @doc(category: "Discounts") {- """The ID of the sale translation."""- id: ID!-- """Translation language."""- language: LanguageDisplay!-- """Translated name of sale."""- name: String-}--"""-Sales allow creating discounts for categories, collections or products and are visible to all the customers.--DEPRECATED: this type will be removed in Saleor 4.0. Use `Promotion` type instead.-"""-type Sale implements Node & ObjectWithMetadata @doc(category: "Discounts") {- """The ID of the sale."""- id: ID!-- """List of private metadata items. Requires staff permissions to access."""- privateMetadata: [MetadataItem!]!-- """- A single key from private metadata. Requires staff permissions to access.-- Tip: Use GraphQL aliases to fetch multiple keys.-- Added in Saleor 3.3.- """- privateMetafield(key: String!): String-- """- Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.-- Added in Saleor 3.3.- """- privateMetafields(keys: [String!]): Metadata-- """List of public metadata items. Can be accessed without permissions."""- metadata: [MetadataItem!]!-- """- A single key from public metadata.-- Tip: Use GraphQL aliases to fetch multiple keys.-- Added in Saleor 3.3.- """- metafield(key: String!): String-- """- Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.-- Added in Saleor 3.3.- """- metafields(keys: [String!]): Metadata-- """The name of the sale."""- name: String!-- """Type of the sale, fixed or percentage."""- type: SaleType!-- """The start date and time of the sale."""- startDate: DateTime!-- """The end date and time of the sale."""- endDate: DateTime-- """The date and time when the sale was created."""- created: DateTime!-- """The date and time when the sale was updated."""- updatedAt: DateTime!-- """List of categories this sale applies to."""- categories(- """Return the elements in the list that come before the specified cursor."""- before: String-- """Return the elements in the list that come after the specified cursor."""- after: String-- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int-- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): CategoryCountableConnection-- """- List of collections this sale applies to.-- Requires one of the following permissions: MANAGE_DISCOUNTS.- """- collections(- """Return the elements in the list that come before the specified cursor."""- before: String-- """Return the elements in the list that come after the specified cursor."""- after: String-- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int-- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): CollectionCountableConnection-- """- List of products this sale applies to.-- Requires one of the following permissions: MANAGE_DISCOUNTS.- """- products(- """Return the elements in the list that come before the specified cursor."""- before: String-- """Return the elements in the list that come after the specified cursor."""- after: String-- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int-- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): ProductCountableConnection-- """- List of product variants this sale applies to.-- Added in Saleor 3.1.-- Requires one of the following permissions: MANAGE_DISCOUNTS.- """- variants(- """Return the elements in the list that come before the specified cursor."""- before: String-- """Return the elements in the list that come after the specified cursor."""- after: String-- """- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- first: Int-- """- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.- """- last: Int- ): ProductVariantCountableConnection-- """Returns translated sale fields for the given language code."""- translation(- """A language code to return the translation for sale."""- languageCode: LanguageCodeEnum!- ): SaleTranslation-- """- List of channels available for the sale.-- Requires one of the following permissions: MANAGE_DISCOUNTS.- """- channelListings: [SaleChannelListing!]-- """Sale value."""- discountValue: Float-- """Currency code for sale."""- currency: String-}--enum SaleType @doc(category: "Discounts") {- FIXED- PERCENTAGE-}--"""Represents a connection to a list of collections."""-type CollectionCountableConnection @doc(category: "Products") {- """Pagination data for this connection."""- pageInfo: PageInfo!- edges: [CollectionCountableEdge!]!-- """A total count of items in the collection."""- totalCount: Int-}--type CollectionCountableEdge @doc(category: "Products") {- """The item at the end of the edge."""- node: Collection!-- """A cursor for use in pagination."""- cursor: String!-}--type ProductVariantCountableConnection @doc(category: "Products") {- """Pagination data for this connection."""- pageInfo: PageInfo!- edges: [ProductVariantCountableEdge!]!-- """A total count of items in the collection."""- totalCount: Int-}--type ProductVariantCountableEdge @doc(category: "Products") {- """The item at the end of the edge."""- node: ProductVariant!-- """A cursor for use in pagination."""- cursor: String!-}--"""-Represents sale channel listing.--DEPRECATED: this type will be removed in Saleor 4.0. Use `PromotionRule` type instead.-"""-type SaleChannelListing implements Node @doc(category: "Discounts") {- """The ID of the channel listing."""- id: ID!-- """The channel in which the sale is available."""- channel: Channel!-- """The value of the discount applied to the sale in the channel."""- discountValue: Float!-- """The currency in which the discount value is specified."""- currency: String!-}-"""Represents voucher's original translatable fields and related translations."""@@ -9317,15 +9041,50 @@ type Voucher implements Node & ObjectWithMetadata @doc(category: "Discounts") {"""Minimum order value to apply voucher."""minSpent: Money- """Determines a type of voucher."""- type: VoucherTypeEnum!+ """Determines a type of voucher."""+ type: VoucherTypeEnum!++ """+ List of availability in channels for the voucher.++ Requires one of the following permissions: MANAGE_DISCOUNTS.+ """+ channelListings: [VoucherChannelListing!]+}++"""Represents a connection to a list of collections."""+type CollectionCountableConnection @doc(category: "Products") {+ """Pagination data for this connection."""+ pageInfo: PageInfo!+ edges: [CollectionCountableEdge!]!++ """A total count of items in the collection."""+ totalCount: Int+}++type CollectionCountableEdge @doc(category: "Products") {+ """The item at the end of the edge."""+ node: Collection!++ """A cursor for use in pagination."""+ cursor: String!+}++type ProductVariantCountableConnection @doc(category: "Products") {+ """Pagination data for this connection."""+ pageInfo: PageInfo!+ edges: [ProductVariantCountableEdge!]!++ """A total count of items in the collection."""+ totalCount: Int+}++type ProductVariantCountableEdge @doc(category: "Products") {+ """The item at the end of the edge."""+ node: ProductVariant!- """- List of availability in channels for the voucher.-- Requires one of the following permissions: MANAGE_DISCOUNTS.- """- channelListings: [VoucherChannelListing!]+ """A cursor for use in pagination."""+ cursor: String!}enum DiscountValueTypeEnum @doc(category: "Discounts") {@@ -9627,6 +9386,247 @@ type PromotionRuleTranslation implements Node @doc(category: "Discounts") {description: JSONString}+"""+Represents sale's original translatable fields and related translations.++DEPRECATED: this type will be removed in Saleor 4.0. Use `PromotionTranslatableContent` instead.+"""+type SaleTranslatableContent implements Node @doc(category: "Discounts") {+ """The ID of the sale translatable content."""+ id: ID!++ """Name of the sale to translate."""+ name: String!++ """Returns translated sale fields for the given language code."""+ translation(+ """A language code to return the translation for sale."""+ languageCode: LanguageCodeEnum!+ ): SaleTranslation++ """+ Sales allow creating discounts for categories, collections or products and are visible to all the customers.++ Requires one of the following permissions: MANAGE_DISCOUNTS.+ """+ sale: Sale @deprecated(reason: "This field will be removed in Saleor 4.0. Get model fields from the root level queries.")+}++"""+Represents sale translations.++DEPRECATED: this type will be removed in Saleor 4.0. Use `PromotionTranslation` instead.+"""+type SaleTranslation implements Node @doc(category: "Discounts") {+ """The ID of the sale translation."""+ id: ID!++ """Translation language."""+ language: LanguageDisplay!++ """Translated name of sale."""+ name: String+}++"""+Sales allow creating discounts for categories, collections or products and are visible to all the customers.++DEPRECATED: this type will be removed in Saleor 4.0. Use `Promotion` type instead.+"""+type Sale implements Node & ObjectWithMetadata @doc(category: "Discounts") {+ """The ID of the sale."""+ id: ID!++ """List of private metadata items. Requires staff permissions to access."""+ privateMetadata: [MetadataItem!]!++ """+ A single key from private metadata. Requires staff permissions to access.++ Tip: Use GraphQL aliases to fetch multiple keys.++ Added in Saleor 3.3.+ """+ privateMetafield(key: String!): String++ """+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.++ Added in Saleor 3.3.+ """+ privateMetafields(keys: [String!]): Metadata++ """List of public metadata items. Can be accessed without permissions."""+ metadata: [MetadataItem!]!++ """+ A single key from public metadata.++ Tip: Use GraphQL aliases to fetch multiple keys.++ Added in Saleor 3.3.+ """+ metafield(key: String!): String++ """+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.++ Added in Saleor 3.3.+ """+ metafields(keys: [String!]): Metadata++ """The name of the sale."""+ name: String!++ """Type of the sale, fixed or percentage."""+ type: SaleType!++ """The start date and time of the sale."""+ startDate: DateTime!++ """The end date and time of the sale."""+ endDate: DateTime++ """The date and time when the sale was created."""+ created: DateTime!++ """The date and time when the sale was updated."""+ updatedAt: DateTime!++ """List of categories this sale applies to."""+ categories(+ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): CategoryCountableConnection++ """+ List of collections this sale applies to.++ Requires one of the following permissions: MANAGE_DISCOUNTS.+ """+ collections(+ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): CollectionCountableConnection++ """+ List of products this sale applies to.++ Requires one of the following permissions: MANAGE_DISCOUNTS.+ """+ products(+ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): ProductCountableConnection++ """+ List of product variants this sale applies to.++ Added in Saleor 3.1.++ Requires one of the following permissions: MANAGE_DISCOUNTS.+ """+ variants(+ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): ProductVariantCountableConnection++ """Returns translated sale fields for the given language code."""+ translation(+ """A language code to return the translation for sale."""+ languageCode: LanguageCodeEnum!+ ): SaleTranslation++ """+ List of channels available for the sale.++ Requires one of the following permissions: MANAGE_DISCOUNTS.+ """+ channelListings: [SaleChannelListing!]++ """Sale value."""+ discountValue: Float++ """Currency code for sale."""+ currency: String+}++enum SaleType @doc(category: "Discounts") {+ FIXED+ PERCENTAGE+}++"""+Represents sale channel listing.++DEPRECATED: this type will be removed in Saleor 4.0. Use `PromotionRule` type instead.+"""+type SaleChannelListing implements Node @doc(category: "Discounts") {+ """The ID of the channel listing."""+ id: ID!++ """The channel in which the sale is available."""+ channel: Channel!++ """The value of the discount applied to the sale in the channel."""+ discountValue: Float!++ """The currency in which the discount value is specified."""+ currency: String!+}+enum TranslatableKinds {ATTRIBUTEATTRIBUTE_VALUE@@ -34363,7 +34363,7 @@ type TranslationCreated implements Event @doc(category: "Miscellaneous") {translation: TranslationTypes}-union TranslationTypes = ProductTranslation | CollectionTranslation | CategoryTranslation | AttributeTranslation | AttributeValueTranslation | ProductVariantTranslation | PageTranslation | ShippingMethodTranslation | SaleTranslation | VoucherTranslation | MenuItemTranslation | PromotionTranslation | PromotionRuleTranslation+union TranslationTypes = ProductTranslation | CollectionTranslation | CategoryTranslation | AttributeTranslation | AttributeValueTranslation | ProductVariantTranslation | PageTranslation | ShippingMethodTranslation | VoucherTranslation | MenuItemTranslation | PromotionTranslation | PromotionRuleTranslation | SaleTranslation"""Event sent when translation is updated.diff --git a/saleor/graphql/translations/dataloaders.py b/saleor/graphql/translations/dataloaders.pyindex 080162331a..04899eeb4b 100644--- a/saleor/graphql/translations/dataloaders.py+++ b/saleor/graphql/translations/dataloaders.py@@ -105,14 +105,6 @@ class ProductVariantTranslationByIdAndLanguageCodeLoader(relation_name = "product_variant_id"-class SaleTranslationByIdAndLanguageCodeLoader(- BaseTranslationByIdAndLanguageCodeLoader-):- context_key = "sale_translation_by_id_and_language_code"- model = discount_models.SaleTranslation- relation_name = "sale_id"--class ShippingMethodTranslationByIdAndLanguageCodeLoader(BaseTranslationByIdAndLanguageCodeLoader):diff --git a/saleor/graphql/translations/mutations/utils.py b/saleor/graphql/translations/mutations/utils.pyindex 1f1ce55469..127b2fe64e 100644--- a/saleor/graphql/translations/mutations/utils.py+++ b/saleor/graphql/translations/mutations/utils.py@@ -51,7 +51,7 @@ TRANSLATABLE_CONTENT_TO_MODEL = {): shipping_models.ShippingMethod._meta.object_name,str(translation_types.SaleTranslatableContent- ): discount_models.Sale._meta.object_name,+ ): discount_models.Promotion._meta.object_name,str(translation_types.VoucherTranslatableContent): discount_models.Voucher._meta.object_name,diff --git a/saleor/graphql/translations/resolvers.py b/saleor/graphql/translations/resolvers.pyindex 57fc8d5484..08aa898a3c 100644--- a/saleor/graphql/translations/resolvers.py+++ b/saleor/graphql/translations/resolvers.py@@ -26,7 +26,6 @@ TYPE_TO_TRANSLATION_LOADER_MAP = {product_models.ProductVariant: (dataloaders.ProductVariantTranslationByIdAndLanguageCodeLoader),- discount_models.Sale: dataloaders.SaleTranslationByIdAndLanguageCodeLoader,shipping_models.ShippingMethod: (dataloaders.ShippingMethodTranslationByIdAndLanguageCodeLoader),diff --git a/saleor/graphql/translations/schema.py b/saleor/graphql/translations/schema.pyindex 602f31d73d..bddbceedfe 100644--- a/saleor/graphql/translations/schema.py+++ b/saleor/graphql/translations/schema.py@@ -1,7 +1,7 @@import graphenefrom ...attribute.models import Attribute, AttributeValue-from ...discount.models import Promotion, PromotionRule, Sale, Voucher+from ...discount.models import Promotion, PromotionRule, Voucherfrom ...menu.models import MenuItemfrom ...page.models import Pagefrom ...permission.enums import SitePermissions@@ -37,7 +37,6 @@ TYPES_TRANSLATIONS_MAP = {ProductVariant: translation_types.ProductVariantTranslatableContent,Page: translation_types.PageTranslatableContent,ShippingMethod: translation_types.ShippingMethodTranslatableContent,- Sale: translation_types.SaleTranslatableContent,Voucher: translation_types.VoucherTranslatableContent,MenuItem: translation_types.MenuItemTranslatableContent,Promotion: translation_types.PromotionTranslatableContent,@@ -47,7 +46,9 @@ TYPES_TRANSLATIONS_MAP = {class TranslatableItem(graphene.Union):class Meta:- types = tuple(TYPES_TRANSLATIONS_MAP.values())+ types = tuple(TYPES_TRANSLATIONS_MAP.values()) + (+ translation_types.SaleTranslatableContent,+ )@classmethoddef resolve_type(cls, instance, info: ResolveInfo):@@ -154,7 +155,6 @@ class TranslationQueries(graphene.ObjectType):TranslatableKinds.VARIANT.value: ProductVariant, # type: ignore[attr-defined] # noqa: E501TranslatableKinds.PAGE.value: Page, # type: ignore[attr-defined]TranslatableKinds.SHIPPING_METHOD.value: ShippingMethod, # type: ignore[attr-defined] # noqa: E501- TranslatableKinds.SALE.value: Sale, # type: ignore[attr-defined]TranslatableKinds.VOUCHER.value: Voucher, # type: ignore[attr-defined]TranslatableKinds.MENU_ITEM.value: MenuItem, # type: ignore[attr-defined]TranslatableKinds.PROMOTION.value: Promotion, # type: ignore[attr-defined]diff --git a/saleor/graphql/translations/tests/deprecated/test_translations.py b/saleor/graphql/translations/tests/deprecated/test_translations.pyindex dbe4c545c7..df8b5d6621 100644--- a/saleor/graphql/translations/tests/deprecated/test_translations.py+++ b/saleor/graphql/translations/tests/deprecated/test_translations.py@@ -1,8 +1,6 @@import grapheneimport pytest-from .....discount.models import Promotion-from .....discount.tests.sale_converter import convert_sales_to_promotionsfrom ....core.enums import LanguageCodeEnumfrom ....tests.utils import get_graphql_contentfrom ...schema import TranslatableKinds@@ -415,16 +413,15 @@ QUERY_TRANSLATION_SALE = """)def test_translation_query_sale(staff_api_client,- sale,- sale_translation_fr,+ promotion_converted_from_sale,+ promotion_converted_from_sale_translation_fr,perm_codenames,return_sale,permission_manage_translations,permission_manage_discounts,):# given- convert_sales_to_promotions()- promotion = Promotion.objects.first()+ promotion = promotion_converted_from_salepromotion_translation = promotion.translations.first()sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.pyindex 287b40f332..6d11bf3ae7 100644--- a/saleor/graphql/translations/tests/test_translations.py+++ b/saleor/graphql/translations/tests/test_translations.py@@ -10,8 +10,6 @@ from mock import ANYfrom ....attribute.utils import associate_attribute_values_to_instancefrom ....discount.error_codes import DiscountErrorCode-from ....discount.models import Promotion-from ....discount.tests.sale_converter import convert_sales_to_promotionsfrom ....permission.models import Permissionfrom ....tests.utils import dummy_editorjsfrom ....webhook.event_types import WebhookEventAsyncType@@ -1716,15 +1714,15 @@ def test_sale_create_translation(def test_sale_create_translation_by_translatable_content_id(staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_translations,):# given+ promotion = promotion_converted_from_saletranslatable_content_id = graphene.Node.to_global_id(- "SaleTranslatableContent", sale.id+ "SaleTranslatableContent", promotion.old_sale_id)variables = {"saleId": translatable_content_id}- convert_sales_to_promotions()# whenresponse = staff_api_client.post_graphql(@@ -1747,7 +1745,7 @@ def test_sale_update_translation(mocked_get_webhooks_for_event,any_webhook,staff_api_client,- sale,+ promotion_converted_from_sale,permission_manage_translations,settings,):@@ -1755,13 +1753,11 @@ def test_sale_update_translation(mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- translation = sale.translations.create(language_code="pl", name="Sale")+ promotion = promotion_converted_from_sale+ translation = promotion.translations.create(language_code="pl", name="Sale")+ sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)- sale_id = graphene.Node.to_global_id("Sale", sale.id)variables = {"saleId": sale_id}- convert_sales_to_promotions()-- translation = Promotion.objects.first().translations.get(language_code="pl")# whenresponse = staff_api_client.post_graphql(@@ -3542,15 +3538,14 @@ QUERY_TRANSLATION_SALE = """def test_translation_query_sale(staff_api_client,- sale,- sale_translation_fr,+ promotion_converted_from_sale,+ promotion_converted_from_sale_translation_fr,permission_manage_discounts,permission_manage_translations,):# given- convert_sales_to_promotions()- promotion = Promotion.objects.first()- promotion_transaltion = promotion.translations.first()+ promotion = promotion_converted_from_sale+ promotion_translation = promotion.translations.first()sale_id = graphene.Node.to_global_id("Sale", promotion.old_sale_id)variables = {@@ -3570,7 +3565,7 @@ def test_translation_query_sale(content = get_graphql_content(response, ignore_errors=True)data = content["data"]["translation"]assert data["name"] == promotion.name- assert data["translation"]["name"] == promotion_transaltion.name+ assert data["translation"]["name"] == promotion_translation.nameQUERY_TRANSLATION_VOUCHER = """diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.pyindex 3bd8f0674f..79469cee18 100644--- a/saleor/graphql/translations/types.py+++ b/saleor/graphql/translations/types.py@@ -596,12 +596,12 @@ class VoucherTranslatableContent(ModelObjectType[discount_models.Voucher]):return ChannelContext(node=root, channel_slug=None)-class SaleTranslation(BaseTranslationType[discount_models.SaleTranslation]):+class SaleTranslation(BaseTranslationType[discount_models.PromotionTranslation]):id = graphene.GlobalID(required=True, description="The ID of the sale translation.")name = graphene.String(description="Translated name of sale.")class Meta:- model = discount_models.SaleTranslation+ model = discount_models.PromotionTranslationinterfaces = [graphene.relay.Node]description = ("Represents sale translations."@@ -610,7 +610,7 @@ class SaleTranslation(BaseTranslationType[discount_models.SaleTranslation]):)-class SaleTranslatableContent(ModelObjectType[discount_models.Sale]):+class SaleTranslatableContent(ModelObjectType[discount_models.Promotion]):id = graphene.GlobalID(required=True, description="The ID of the sale translatable content.")@@ -629,7 +629,7 @@ class SaleTranslatableContent(ModelObjectType[discount_models.Sale]):)class Meta:- model = discount_models.Sale+ model = discount_models.Promotioninterfaces = [graphene.relay.Node]description = ("Represents sale's original translatable fields and related translations."@@ -638,7 +638,7 @@ class SaleTranslatableContent(ModelObjectType[discount_models.Sale]):)@staticmethod- def resolve_sale(root: discount_models.Sale, _info):+ def resolve_sale(root: discount_models.Promotion, _info):return ChannelContext(node=root, channel_slug=None)diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 0552942bba..1aa71e3a2c 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -11,7 +11,6 @@ from ...core.prices import quantize_pricefrom ...discount.models import (PromotionRuleTranslation,PromotionTranslation,- SaleTranslation,VoucherTranslation,)from ...graphql.shop.types import Shop@@ -95,7 +94,6 @@ TRANSLATIONS_TYPES_MAP = {ProductVariantTranslation: translation_types.ProductVariantTranslation,PageTranslation: translation_types.PageTranslation,ShippingMethodTranslation: translation_types.ShippingMethodTranslation,- SaleTranslation: translation_types.SaleTranslation,VoucherTranslation: translation_types.VoucherTranslation,MenuItemTranslation: translation_types.MenuItemTranslation,PromotionTranslation: translation_types.PromotionTranslation,@@ -2313,7 +2311,9 @@ class PaymentMethodProcessTokenizationSession(class TranslationTypes(Union):class Meta:- types = tuple(TRANSLATIONS_TYPES_MAP.values())+ types = tuple(TRANSLATIONS_TYPES_MAP.values()) + (+ translation_types.SaleTranslation,+ )@classmethoddef resolve_type(cls, instance, info: ResolveInfo):diff --git a/saleor/graphql/webhook/tests/fixtures.py b/saleor/graphql/webhook/tests/fixtures.pydeleted file mode 100644index bfefa2ea54..0000000000--- a/saleor/graphql/webhook/tests/fixtures.py+++ /dev/null@@ -1,424 +0,0 @@-import pytest--from ....webhook.event_types import WebhookEventAsyncType---def async_subscription_webhooks_with_root_objects(- subscription_address_created_webhook,- subscription_address_updated_webhook,- subscription_address_deleted_webhook,- subscription_app_installed_webhook,- subscription_app_updated_webhook,- subscription_app_deleted_webhook,- subscription_app_status_changed_webhook,- subscription_attribute_created_webhook,- subscription_attribute_updated_webhook,- subscription_attribute_deleted_webhook,- subscription_attribute_value_created_webhook,- subscription_attribute_value_updated_webhook,- subscription_attribute_value_deleted_webhook,- subscription_category_created_webhook,- subscription_category_updated_webhook,- subscription_category_deleted_webhook,- subscription_channel_created_webhook,- subscription_channel_updated_webhook,- subscription_channel_deleted_webhook,- subscription_channel_status_changed_webhook,- subscription_gift_card_created_webhook,- subscription_gift_card_updated_webhook,- subscription_gift_card_deleted_webhook,- subscription_gift_card_sent_webhook,- subscription_gift_card_status_changed_webhook,- subscription_gift_card_metadata_updated_webhook,- subscription_menu_created_webhook,- subscription_menu_updated_webhook,- subscription_menu_deleted_webhook,- subscription_menu_item_created_webhook,- subscription_menu_item_updated_webhook,- subscription_menu_item_deleted_webhook,- subscription_shipping_price_created_webhook,- subscription_shipping_price_updated_webhook,- subscription_shipping_price_deleted_webhook,- subscription_shipping_zone_created_webhook,- subscription_shipping_zone_updated_webhook,- subscription_shipping_zone_deleted_webhook,- subscription_shipping_zone_metadata_updated_webhook,- subscription_product_updated_webhook,- subscription_product_created_webhook,- subscription_product_deleted_webhook,- subscription_product_media_updated_webhook,- subscription_product_media_created_webhook,- subscription_product_media_deleted_webhook,- subscription_product_metadata_updated_webhook,- subscription_product_variant_created_webhook,- subscription_product_variant_updated_webhook,- subscription_product_variant_deleted_webhook,- subscription_product_variant_metadata_updated_webhook,- subscription_product_variant_out_of_stock_webhook,- subscription_product_variant_back_in_stock_webhook,- subscription_order_created_webhook,- subscription_order_updated_webhook,- subscription_order_confirmed_webhook,- subscription_order_fully_paid_webhook,- subscription_order_refunded_webhook,- subscription_order_fully_refunded_webhook,- subscription_order_paid_webhook,- subscription_order_cancelled_webhook,- subscription_order_expired_webhook,- subscription_order_fulfilled_webhook,- subscription_order_metadata_updated_webhook,- subscription_order_bulk_created_webhook,- subscription_draft_order_created_webhook,- subscription_draft_order_updated_webhook,- subscription_draft_order_deleted_webhook,- subscription_promotion_created_webhook,- subscription_promotion_updated_webhook,- subscription_promotion_deleted_webhook,- subscription_promotion_started_webhook,- subscription_promotion_ended_webhook,- subscription_sale_created_webhook,- subscription_sale_updated_webhook,- subscription_sale_deleted_webhook,- subscription_sale_toggle_webhook,- subscription_invoice_requested_webhook,- subscription_invoice_deleted_webhook,- subscription_invoice_sent_webhook,- subscription_fulfillment_created_webhook,- subscription_fulfillment_canceled_webhook,- subscription_fulfillment_approved_webhook,- subscription_fulfillment_metadata_updated_webhook,- subscription_customer_created_webhook,- subscription_customer_updated_webhook,- subscription_customer_deleted_webhook,- subscription_customer_metadata_updated_webhook,- subscription_collection_created_webhook,- subscription_collection_updated_webhook,- subscription_collection_deleted_webhook,- subscription_collection_metadata_updated_webhook,- subscription_checkout_created_webhook,- subscription_checkout_updated_webhook,- subscription_checkout_fully_paid_webhook,- subscription_checkout_metadata_updated_webhook,- subscription_page_created_webhook,- subscription_page_updated_webhook,- subscription_page_deleted_webhook,- subscription_page_type_created_webhook,- subscription_page_type_updated_webhook,- subscription_page_type_deleted_webhook,- subscription_permission_group_created_webhook,- subscription_permission_group_updated_webhook,- subscription_permission_group_deleted_webhook,- subscription_product_created_multiple_events_webhook,- subscription_staff_created_webhook,- subscription_staff_updated_webhook,- subscription_staff_deleted_webhook,- subscription_transaction_item_metadata_updated_webhook,- subscription_translation_created_webhook,- subscription_translation_updated_webhook,- subscription_warehouse_created_webhook,- subscription_warehouse_updated_webhook,- subscription_warehouse_deleted_webhook,- subscription_warehouse_metadata_updated_webhook,- subscription_voucher_created_webhook,- subscription_voucher_updated_webhook,- subscription_voucher_deleted_webhook,- subscription_voucher_webhook_with_meta,- subscription_voucher_metadata_updated_webhook,- address,- app,- numeric_attribute,- category,- channel_PLN,- gift_card,- menu_item,- shipping_method,- product,- fulfilled_order,- promotion,- promotion_converted_from_sale,- fulfillment,- stock,- customer_user,- collection,- checkout,- page,- permission_group_manage_users,- shipping_zone,- staff_user,- voucher,- warehouse,- translated_attribute,- transaction_item_created_by_app,- product_media_image,-):- events = WebhookEventAsyncType- attr = numeric_attribute- attr_value = attr.values.first()- menu = menu_item.menu- order = fulfilled_order- invoice = order.invoices.first()- page_type = page.page_type- transaction_item_created_by_app.use_old_id = True- transaction_item_created_by_app.save()-- return {- events.ADDRESS_UPDATED: [subscription_address_updated_webhook, address],- events.ADDRESS_CREATED: [subscription_address_created_webhook, address],- events.ADDRESS_DELETED: [subscription_address_deleted_webhook, address],- events.APP_UPDATED: [subscription_app_updated_webhook, app],- events.APP_DELETED: [subscription_app_deleted_webhook, app],- events.APP_INSTALLED: [subscription_app_installed_webhook, app],- events.APP_STATUS_CHANGED: [subscription_app_status_changed_webhook, app],- events.ATTRIBUTE_CREATED: [subscription_attribute_created_webhook, attr],- events.ATTRIBUTE_UPDATED: [subscription_attribute_updated_webhook, attr],- events.ATTRIBUTE_DELETED: [subscription_attribute_deleted_webhook, attr],- events.ATTRIBUTE_VALUE_UPDATED: [- subscription_attribute_value_updated_webhook,- attr_value,- ],- events.ATTRIBUTE_VALUE_CREATED: [- subscription_attribute_value_created_webhook,- attr_value,- ],- events.ATTRIBUTE_VALUE_DELETED: [- subscription_attribute_value_deleted_webhook,- attr_value,- ],- events.CATEGORY_CREATED: [subscription_category_created_webhook, category],- events.CATEGORY_UPDATED: [subscription_category_updated_webhook, category],- events.CATEGORY_DELETED: [subscription_category_deleted_webhook, category],- events.CHANNEL_CREATED: [subscription_channel_created_webhook, channel_PLN],- events.CHANNEL_UPDATED: [subscription_channel_updated_webhook, channel_PLN],- events.CHANNEL_DELETED: [subscription_channel_deleted_webhook, channel_PLN],- events.CHANNEL_STATUS_CHANGED: [- subscription_channel_status_changed_webhook,- channel_PLN,- ],- events.GIFT_CARD_CREATED: [subscription_gift_card_created_webhook, gift_card],- events.GIFT_CARD_UPDATED: [subscription_gift_card_updated_webhook, gift_card],- events.GIFT_CARD_DELETED: [subscription_gift_card_deleted_webhook, gift_card],- events.GIFT_CARD_SENT: [subscription_gift_card_sent_webhook, gift_card],- events.GIFT_CARD_STATUS_CHANGED: [- subscription_gift_card_status_changed_webhook,- gift_card,- ],- events.GIFT_CARD_METADATA_UPDATED: [- subscription_gift_card_metadata_updated_webhook,- gift_card,- ],- events.MENU_CREATED: [subscription_menu_created_webhook, menu],- events.MENU_UPDATED: [subscription_menu_updated_webhook, menu],- events.MENU_DELETED: [subscription_menu_deleted_webhook, menu],- events.MENU_ITEM_CREATED: [subscription_menu_item_created_webhook, menu_item],- events.MENU_ITEM_UPDATED: [subscription_menu_item_updated_webhook, menu_item],- events.MENU_ITEM_DELETED: [subscription_menu_item_deleted_webhook, menu_item],- events.ORDER_CREATED: [subscription_order_created_webhook, order],- events.ORDER_UPDATED: [subscription_order_updated_webhook, order],- events.ORDER_CONFIRMED: [subscription_order_confirmed_webhook, order],- events.ORDER_FULLY_PAID: [subscription_order_fully_paid_webhook, order],- events.ORDER_PAID: [subscription_order_paid_webhook, order],- events.ORDER_REFUNDED: [subscription_order_refunded_webhook, order],- events.ORDER_FULLY_REFUNDED: [subscription_order_fully_refunded_webhook, order],- events.ORDER_FULFILLED: [subscription_order_fulfilled_webhook, order],- events.ORDER_CANCELLED: [subscription_order_cancelled_webhook, order],- events.ORDER_EXPIRED: [subscription_order_expired_webhook, order],- events.ORDER_METADATA_UPDATED: [- subscription_order_metadata_updated_webhook,- order,- ],- events.ORDER_BULK_CREATED: [subscription_order_bulk_created_webhook, order],- events.DRAFT_ORDER_CREATED: [subscription_draft_order_created_webhook, order],- events.DRAFT_ORDER_UPDATED: [subscription_draft_order_updated_webhook, order],- events.DRAFT_ORDER_DELETED: [subscription_draft_order_deleted_webhook, order],- events.PRODUCT_CREATED: [subscription_product_created_webhook, product],- events.PRODUCT_UPDATED: [subscription_product_updated_webhook, product],- events.PRODUCT_DELETED: [subscription_product_deleted_webhook, product],- events.PRODUCT_MEDIA_CREATED: [- subscription_product_media_created_webhook,- product_media_image,- ],- events.PRODUCT_MEDIA_UPDATED: [- subscription_product_media_updated_webhook,- product_media_image,- ],- events.PRODUCT_MEDIA_DELETED: [- subscription_product_media_deleted_webhook,- product_media_image,- ],- events.PRODUCT_METADATA_UPDATED: [- subscription_product_metadata_updated_webhook,- product,- ],- events.PRODUCT_VARIANT_CREATED: [- subscription_product_variant_created_webhook,- product,- ],- events.PRODUCT_VARIANT_UPDATED: [- subscription_product_variant_updated_webhook,- product,- ],- events.PRODUCT_VARIANT_OUT_OF_STOCK: [- subscription_product_variant_out_of_stock_webhook,- stock,- ],- events.PRODUCT_VARIANT_BACK_IN_STOCK: [- subscription_product_variant_back_in_stock_webhook,- stock,- ],- events.PRODUCT_VARIANT_DELETED: [- subscription_product_variant_deleted_webhook,- product,- ],- events.PRODUCT_VARIANT_METADATA_UPDATED: [- subscription_product_variant_metadata_updated_webhook,- product,- ],- events.PROMOTION_CREATED: [subscription_promotion_created_webhook, promotion],- events.PROMOTION_UPDATED: [subscription_promotion_updated_webhook, promotion],- events.PROMOTION_DELETED: [subscription_promotion_deleted_webhook, promotion],- events.PROMOTION_STARTED: [subscription_promotion_started_webhook, promotion],- events.PROMOTION_ENDED: [subscription_promotion_ended_webhook, promotion],- events.SALE_CREATED: [- subscription_sale_created_webhook,- promotion_converted_from_sale,- ],- events.SALE_UPDATED: [- subscription_sale_updated_webhook,- promotion_converted_from_sale,- ],- events.SALE_DELETED: [- subscription_sale_deleted_webhook,- promotion_converted_from_sale,- ],- events.SALE_TOGGLE: [- subscription_sale_toggle_webhook,- promotion_converted_from_sale,- ],- events.INVOICE_REQUESTED: [subscription_invoice_requested_webhook, invoice],- events.INVOICE_DELETED: [subscription_invoice_deleted_webhook, invoice],- events.INVOICE_SENT: [subscription_invoice_sent_webhook, invoice],- events.FULFILLMENT_CREATED: [- subscription_fulfillment_created_webhook,- fulfillment,- ],- events.FULFILLMENT_CANCELED: [- subscription_fulfillment_canceled_webhook,- fulfillment,- ],- events.FULFILLMENT_APPROVED: [- subscription_fulfillment_approved_webhook,- fulfillment,- ],- events.FULFILLMENT_METADATA_UPDATED: [- subscription_fulfillment_metadata_updated_webhook,- fulfillment,- ],- events.CUSTOMER_CREATED: [subscription_customer_created_webhook, customer_user],- events.CUSTOMER_UPDATED: [subscription_customer_updated_webhook, customer_user],- events.CUSTOMER_METADATA_UPDATED: [- subscription_customer_metadata_updated_webhook,- customer_user,- ],- events.COLLECTION_CREATED: [- subscription_collection_created_webhook,- collection,- ],- events.COLLECTION_UPDATED: [- subscription_collection_updated_webhook,- collection,- ],- events.COLLECTION_DELETED: [- subscription_collection_deleted_webhook,- collection,- ],- events.COLLECTION_METADATA_UPDATED: [- subscription_collection_metadata_updated_webhook,- collection,- ],- events.CHECKOUT_CREATED: [subscription_checkout_created_webhook, checkout],- events.CHECKOUT_UPDATED: [subscription_checkout_updated_webhook, checkout],- events.CHECKOUT_FULLY_PAID: [- subscription_checkout_fully_paid_webhook,- checkout,- ],- events.CHECKOUT_METADATA_UPDATED: [- subscription_checkout_metadata_updated_webhook,- checkout,- ],- events.PAGE_CREATED: [subscription_page_created_webhook, page],- events.PAGE_UPDATED: [subscription_page_updated_webhook, page],- events.PAGE_DELETED: [subscription_page_deleted_webhook, page],- events.PAGE_TYPE_CREATED: [subscription_page_type_created_webhook, page_type],- events.PAGE_TYPE_UPDATED: [subscription_page_type_updated_webhook, page_type],- events.PAGE_TYPE_DELETED: [subscription_page_type_deleted_webhook, page_type],- events.PERMISSION_GROUP_CREATED: [- subscription_permission_group_created_webhook,- permission_group_manage_users,- ],- events.PERMISSION_GROUP_UPDATED: [- subscription_permission_group_updated_webhook,- permission_group_manage_users,- ],- events.PERMISSION_GROUP_DELETED: [- subscription_permission_group_deleted_webhook,- permission_group_manage_users,- ],- events.SHIPPING_PRICE_CREATED: [- subscription_shipping_price_created_webhook,- shipping_method,- ],- events.SHIPPING_PRICE_UPDATED: [- subscription_shipping_price_updated_webhook,- shipping_method,- ],- events.SHIPPING_PRICE_DELETED: [- subscription_shipping_price_deleted_webhook,- shipping_method,- ],- events.SHIPPING_ZONE_CREATED: [- subscription_shipping_zone_created_webhook,- shipping_zone,- ],- events.SHIPPING_ZONE_UPDATED: [- subscription_shipping_zone_updated_webhook,- shipping_zone,- ],- events.SHIPPING_ZONE_DELETED: [- subscription_shipping_zone_deleted_webhook,- shipping_zone,- ],- events.SHIPPING_ZONE_METADATA_UPDATED: [- subscription_shipping_zone_metadata_updated_webhook,- shipping_zone,- ],- events.STAFF_CREATED: [subscription_staff_created_webhook, staff_user],- events.STAFF_UPDATED: [subscription_staff_updated_webhook, staff_user],- events.STAFF_DELETED: [subscription_staff_deleted_webhook, staff_user],- events.TRANSACTION_ITEM_METADATA_UPDATED: [- subscription_transaction_item_metadata_updated_webhook,- transaction_item_created_by_app,- ],- events.TRANSLATION_CREATED: [- subscription_translation_created_webhook,- translated_attribute,- ],- events.TRANSLATION_UPDATED: [- subscription_translation_updated_webhook,- translated_attribute,- ],- events.VOUCHER_CREATED: [subscription_voucher_created_webhook, voucher],- events.VOUCHER_UPDATED: [subscription_voucher_updated_webhook, voucher],- events.VOUCHER_DELETED: [subscription_voucher_deleted_webhook, voucher],- events.VOUCHER_METADATA_UPDATED: [- subscription_voucher_metadata_updated_webhook,- voucher,- ],- events.WAREHOUSE_CREATED: [subscription_warehouse_created_webhook, warehouse],- events.WAREHOUSE_UPDATED: [subscription_warehouse_updated_webhook, warehouse],- events.WAREHOUSE_DELETED: [subscription_warehouse_deleted_webhook, warehouse],- events.WAREHOUSE_METADATA_UPDATED: [- subscription_warehouse_metadata_updated_webhook,- warehouse,- ],- }diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex 6f5a6bf2e9..45df5a5245 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -257,17 +257,17 @@ def test_add_variant_to_order(order,customer_user,variant,- sale,+ promotion_with_single_rule,):# givenmanager = get_plugins_manager()quantity = 4- sale_channel_listing = sale.channel_listings.get(channel=order.channel)-+ promotion = promotion_with_single_rule+ discount_value = promotion.rules.first().reward_valuechannel_listing = variant.channel_listings.get(channel=order.channel)channel_listing.discounted_price_amount = (- channel_listing.price.amount - sale_channel_listing.discount_value+ channel_listing.price.amount - discount_value)channel_listing.save(update_fields=["discounted_price_amount"])diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex 9a5aee301e..eae87df1b3 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -425,7 +425,6 @@ def test_calculate_checkout_line_total_with_variant_on_promotion_and_voucher_onlplugin_configuration,voucher,channel_USD,- discount_info,):# givenplugin_configuration()@@ -550,7 +549,6 @@ def test_calculate_checkout_line_without_sku_total_with_promotion(expected_net,expected_gross,prices_entered_with_tax,- discount_info,checkout_with_item_on_promotion,ship_to_pl_address,monkeypatch,@@ -2719,7 +2717,6 @@ def test_calculate_checkout_line_unit_price_with_variant_on_promotion(shipping_zone,address,plugin_configuration,- discount_info,):# givenplugin_configuration()@@ -2887,7 +2884,6 @@ def test_calculate_checkout_line_unit_price_with_variant_on_promotion_and_voucheplugin_configuration,voucher,channel_USD,- discount_info,):# givenplugin_configuration()@@ -4729,7 +4725,7 @@ def test_get_order_request_data_draft_order_shipping_voucher_amount_too_high(def test_get_order_request_data_draft_order_on_promotion(- order_line_on_promotion, shipping_zone, sale, avatax_config+ order_line_on_promotion, shipping_zone, promotion_with_single_rule, avatax_config):# givenorder = order_line_on_promotion.order@@ -4744,7 +4740,11 @@ def test_get_order_request_data_draft_order_on_promotion(line.undiscounted_base_unit_price_amount = line.unit_price_gross_amountline.save()- sale.variants.add(line.variant)+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.id)+ predicate = {"variantPredicate": {"ids": [variant_id]}}+ rule = promotion_with_single_rule.rules.first()+ rule.catalogue_predicate = predicate+ rule.save(update_fields=["catalogue_predicate"])order.status = OrderStatus.DRAFTorder.shipping_address = order.billing_address.get_copy()diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.pyindex 37893e56e0..bff652585d 100644--- a/saleor/plugins/tests/test_manager.py+++ b/saleor/plugins/tests/test_manager.py@@ -12,8 +12,7 @@ from ...channel import TransactionFlowStrategyfrom ...checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ...core.prices import quantize_pricefrom ...core.taxes import TaxType, zero_money, zero_taxed_money-from ...discount.utils import fetch_catalogue_info-from ...graphql.discount.mutations.utils import convert_catalogue_info_to_global_ids+from ...graphql.discount.utils import convert_migrated_sale_predicate_to_catalogue_infofrom ...payment import TokenizedPaymentFlowfrom ...payment.interface import (ListStoredPaymentMethodsRequestData,@@ -215,7 +214,7 @@ def test_manager_calculates_checkout_subtotal([(["saleor.plugins.tests.sample_plugins.PluginSample"], "1.0"), ([], "0.0")],)def test_manager_calculates_checkout_shipping(- checkout_with_item, discount_info, plugins, shipping_amount+ checkout_with_item, plugins, shipping_amount):currency = checkout_with_item.currencyexpected_shipping_price = Money(shipping_amount, currency)@@ -253,7 +252,7 @@ def test_manager_calculates_order_shipping(order_with_lines, plugins, shipping_a[(["saleor.plugins.tests.sample_plugins.PluginSample"], "1.0"), ([], "15.0")],)def test_manager_calculates_checkout_line_total(- checkout_with_item_on_promotion, discount_info, plugins, amount+ checkout_with_item_on_promotion, plugins, amount):# givencheckout = checkout_with_item_on_promotion@@ -579,61 +578,67 @@ def test_manager_get_taxes_for_order() == expected_tax_data(order)-def test_manager_sale_created(sale):+def test_manager_sale_created(promotion_converted_from_sale):plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]- current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))- sale_returned, current_catalogue_returned = PluginsManager(+ promotion = promotion_converted_from_sale+ predicate = promotion.rules.first().catalogue_predicate+ current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)+ promotion_returned, current_catalogue_returned = PluginsManager(plugins=plugins- ).sale_created(sale, current_catalogue)+ ).sale_created(promotion, current_catalogue)- assert sale == sale_returned+ assert promotion == promotion_returnedassert current_catalogue == current_catalogue_returned-def test_manager_sale_updated(sale):+def test_manager_sale_updated(promotion_converted_from_sale):plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)- )- current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))+ promotion = promotion_converted_from_sale+ predicate = promotion.rules.first().catalogue_predicate+ current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)(- sale_returned,+ promotion_returned,previous_catalogue_returned,current_catalogue_returned,) = PluginsManager(plugins=plugins).sale_updated(- sale, previous_catalogue, current_catalogue+ promotion, previous_catalogue, current_catalogue)- assert sale == sale_returned+ assert promotion == promotion_returnedassert current_catalogue == current_catalogue_returnedassert previous_catalogue == previous_catalogue_returned-def test_manager_sale_deleted(sale):+def test_manager_sale_deleted(promotion_converted_from_sale):plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]- previous_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)- )- sale_returned, previous_catalogue_returned = PluginsManager(+ promotion = promotion_converted_from_sale+ predicate = promotion.rules.first().catalogue_predicate+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)++ promotion_returned, previous_catalogue_returned = PluginsManager(plugins=plugins- ).sale_created(sale, previous_catalogue)+ ).sale_created(promotion, previous_catalogue)- assert sale == sale_returned+ assert promotion == promotion_returnedassert previous_catalogue == previous_catalogue_returned-def test_manager_sale_toggle(sale):+def test_manager_sale_toggle(promotion_converted_from_sale):plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]- current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))- sale_returned, current_catalogue_returned = PluginsManager(+ promotion = promotion_converted_from_sale+ predicate = promotion.rules.first().catalogue_predicate+ current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)++ promotion_returned, current_catalogue_returned = PluginsManager(plugins=plugins- ).sale_toggle(sale, current_catalogue)+ ).sale_toggle(promotion, current_catalogue)- assert sale == sale_returned+ assert promotion == promotion_returnedassert current_catalogue == current_catalogue_returned@@ -1137,7 +1142,6 @@ def test_calculate_checkout_total_zero_default_value(mocked_base_checkout_total,mocked_run_method,checkout_with_item,- discount_info,):# givenplugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.pyindex 2b71851fda..6d26578051 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py@@ -222,13 +222,7 @@ def test_translation_created_promotion_rule(event_type, promotion_rule_translation_fr, webhooks)- expected_payload = json.dumps(- {- "translation": {- "id": translation_id,- }- }- )+ expected_payload = json.dumps({"translation": {"id": translation_id}})assert deliveries[0].payload.payload == expected_payloadassert len(deliveries) == len(webhooks)diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex 58da08571b..f0f0b68d92 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -36,9 +36,8 @@ from ....discount import RewardValueTypefrom ....discount.interface import VariantPromotionRuleInfofrom ....discount.utils import (create_or_update_discount_objects_from_promotion_for_checkout,- fetch_catalogue_info,)-from ....graphql.discount.mutations.utils import convert_catalogue_info_to_global_ids+from ....graphql.discount.utils import convert_migrated_sale_predicate_to_catalogue_infofrom ....payment import TransactionAction, TransactionEventTypefrom ....payment.interface import TransactionActionDatafrom ....payment.models import TransactionItem@@ -1622,20 +1621,28 @@ def test_create_event_payload_reference_with_error(@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")def test_sale_created(- mocked_webhook_trigger, mocked_get_webhooks_for_event, any_webhook, settings, sale+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ settings,+ promotion_converted_from_sale,):mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]manager = get_plugins_manager()- sale_catalogue_info = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)++ promotion = promotion_converted_from_sale+ predicate = promotion.rules.first().catalogue_predicate+ promotion_catalogue_info = convert_migrated_sale_predicate_to_catalogue_info(+ predicate)- manager.sale_created(sale, current_catalogue=sale_catalogue_info)++ manager.sale_created(promotion, current_catalogue=promotion_catalogue_info)mocked_webhook_trigger.assert_called_once_with(None,WebhookEventAsyncType.SALE_CREATED,[any_webhook],- sale,+ promotion,None,legacy_data_generator=ANY,)@@ -1652,30 +1659,36 @@ def test_sale_updated(mocked_get_webhooks_for_event,any_webhook,settings,- sale,+ promotion_converted_from_sale,product_list,):mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]manager = get_plugins_manager()- previous_sale_catalogue_info = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)- )- sale.products.add(*product_list)- current_sale_catalogue_info = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)- )++ promotion = promotion_converted_from_sale+ rule = promotion.rules.first()+ predicate = promotion.rules.first().catalogue_predicate+ previous_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)++ product_ids = [+ graphene.Node.to_global_id("Product", product.id) for product in product_list+ ]+ predicate = {"variantPredicate": {"ids": [product_ids]}}+ rule.catalogue_predicate = predicate+ rule.save(update_fields=["catalogue_predicate"])+ current_catalogue = convert_migrated_sale_predicate_to_catalogue_info(predicate)manager.sale_updated(- sale,- previous_catalogue=previous_sale_catalogue_info,- current_catalogue=current_sale_catalogue_info,+ promotion,+ previous_catalogue=previous_catalogue,+ current_catalogue=current_catalogue,)mocked_webhook_trigger.assert_called_once_with(None,WebhookEventAsyncType.SALE_UPDATED,[any_webhook],- sale,+ promotion,None,legacy_data_generator=ANY,)@@ -1688,20 +1701,26 @@ def test_sale_updated(@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")def test_sale_deleted(- mocked_webhook_trigger, mocked_get_webhooks_for_event, any_webhook, settings, sale+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ settings,+ promotion_converted_from_sale,):mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]manager = get_plugins_manager()- sale_catalogue_info = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)- )- manager.sale_deleted(sale, previous_catalogue=sale_catalogue_info)++ promotion = promotion_converted_from_sale+ predicate = promotion.rules.first().catalogue_predicate+ catalogue_info = convert_migrated_sale_predicate_to_catalogue_info(predicate)++ manager.sale_deleted(promotion, previous_catalogue=catalogue_info)mocked_webhook_trigger.assert_called_once_with(None,WebhookEventAsyncType.SALE_DELETED,[any_webhook],- sale,+ promotion,None,legacy_data_generator=ANY,)@@ -1714,25 +1733,30 @@ def test_sale_deleted(@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")def test_sale_toggle(- mocked_webhook_trigger, mocked_get_webhooks_for_event, any_webhook, settings, sale+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ settings,+ promotion_converted_from_sale,):# givenmocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]manager = get_plugins_manager()- sale_catalogue_info = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(sale)- )++ promotion = promotion_converted_from_sale+ predicate = promotion.rules.first().catalogue_predicate+ catalogue_info = convert_migrated_sale_predicate_to_catalogue_info(predicate)# when- manager.sale_toggle(sale, catalogue=sale_catalogue_info)+ manager.sale_toggle(promotion, catalogue=catalogue_info)# thenmocked_webhook_trigger.assert_called_once_with(None,WebhookEventAsyncType.SALE_TOGGLE,[any_webhook],- sale,+ promotion,None,legacy_data_generator=ANY,)diff --git a/saleor/product/tests/deprecated/test_tasks.py b/saleor/product/tests/deprecated/test_tasks.pyindex f734473dda..ac9de0ce6d 100644--- a/saleor/product/tests/deprecated/test_tasks.py+++ b/saleor/product/tests/deprecated/test_tasks.py@@ -1,7 +1,8 @@import loggingfrom unittest.mock import patch-from ....discount.tests.sale_converter import convert_sales_to_promotions+import graphene+from ...tasks import (update_product_discounted_price_task,update_products_discounted_prices_of_sale_task,@@ -13,22 +14,38 @@ from ...tasks import ()def test_update_products_discounted_prices_of_sale_task(update_discounted_prices_for_promotion_mock,- new_sale,+ promotion_converted_from_sale_with_empty_predicate,product_list,product,category,collection,):# given- new_sale.products.add(product)+ promotion = promotion_converted_from_sale_with_empty_predicate+ collection_id = graphene.Node.to_global_id("Collection", collection.id)+ category_id = graphene.Node.to_global_id("Category", category.id)+ product_id = graphene.Node.to_global_id("Product", product.id)+ variant_id = graphene.Node.to_global_id(+ "ProductVariant", product_list[2].variants.first().id+ )+category.products.add(product_list[0])- new_sale.categories.add(category)collection.products.add(product_list[1])- new_sale.variants.add(product_list[2].variants.first())- convert_sales_to_promotions()++ predicate = {+ "OR": [+ {"collectionPredicate": {"ids": [collection_id]}},+ {"categoryPredicate": {"ids": [category_id]}},+ {"productPredicate": {"ids": [product_id]}},+ {"variantPredicate": {"ids": [variant_id]}},+ ]+ }+ rule = promotion.rules.first()+ rule.catalogue_predicate = predicate+ rule.save(update_fields=["catalogue_predicate"])# when- update_products_discounted_prices_of_sale_task(new_sale.id)+ update_products_discounted_prices_of_sale_task(promotion.old_sale_id)# thenupdate_discounted_prices_for_promotion_mock.assert_called_once()diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.pyindex 4c7a0352ef..5369ad2bcf 100644--- a/saleor/tax/tests/test_checkout_calculations.py+++ b/saleor/tax/tests/test_checkout_calculations.py@@ -84,7 +84,6 @@ def test_calculate_checkout_total_with_sale(address,shipping_zone,voucher,- discount_info,expected_net,expected_gross,voucher_amount,@@ -250,7 +249,6 @@ def test_calculate_checkout_total_with_shipping_voucher_and_sale(checkout_with_item_on_promotion,address,shipping_zone,- discount_info,voucher_shipping_type,expected_net,expected_gross,@@ -773,7 +771,6 @@ def test_calculate_checkout_line_total_with_shipping_voucher(def test_calculate_checkout_shipping(checkout_with_item,shipping_zone,- discount_info,address,):# given@@ -806,7 +803,6 @@ def test_calculate_checkout_shipping(def test_calculate_checkout_shipping_no_shipping_price(checkout_with_item,- discount_info,address,warehouse_for_cc,):@@ -839,7 +835,6 @@ def test_calculate_checkout_shipping_no_shipping_price(def test_calculate_checkout_shipping_voucher_on_shipping(checkout_with_item,shipping_zone,- discount_info,address,voucher_shipping_type,):@@ -884,7 +879,6 @@ def test_calculate_checkout_shipping_voucher_on_shipping(def test_calculate_checkout_shipping_free_shipping_voucher(checkout_with_item,shipping_zone,- discount_info,address,voucher_shipping_type,):@@ -923,7 +917,6 @@ def test_calculate_checkout_shipping_free_shipping_voucher(def test_calculate_checkout_shipping_free_entire_order_voucher(checkout_with_item,shipping_zone,- discount_info,address,voucher,):diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex db6304260a..283e98578e 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -51,7 +51,6 @@ from ..core.utils.editorjs import clean_editor_jsfrom ..csv.events import ExportEventsfrom ..csv.models import ExportEvent, ExportFilefrom ..discount import (- DiscountInfo,DiscountType,DiscountValueType,PromotionEvents,@@ -67,9 +66,6 @@ from ..discount.models import (PromotionRule,PromotionRuleTranslation,PromotionTranslation,- Sale,- SaleChannelListing,- SaleTranslation,Voucher,VoucherChannelListing,VoucherCustomer,@@ -327,19 +323,18 @@ def checkout_with_item(checkout, product):@pytest.fixture-def checkout_with_item_on_sale(checkout_with_item):+def checkout_with_item_on_sale(checkout_with_item, promotion_converted_from_sale):line = checkout_with_item.lines.first()channel = checkout_with_item.channel- sale = Sale.objects.create(name="Sale")discount_amount = Decimal("5.0")- SaleChannelListing.objects.create(- sale=sale,- channel=channel,- discount_value=discount_amount,- currency=channel.currency_code,- )variant = line.variant- sale.products.add(variant.product)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ predicate = {"variantPredicate": {"ids": [variant_id]}}+ rule = promotion_converted_from_sale.rules.first()+ rule.catalogue_predicate = predicate+ rule.reward_value = discount_amount+ rule.save(update_fields=["catalogue_predicate", "reward_value"])+ rule.channels.add(channel)channel_listing = variant.channel_listings.get(channel=channel)channel_listing.discounted_price_amount = (channel_listing.price_amount - discount_amount@@ -348,9 +343,9 @@ def checkout_with_item_on_sale(checkout_with_item):CheckoutLineDiscount.objects.create(line=line,- sale=sale,+ promotion_rule=rule,type=DiscountType.SALE,- value_type=sale.type,+ value_type=rule.reward_value_type,value=discount_amount,amount_value=discount_amount * line.quantity,currency=channel.currency_code,@@ -5371,87 +5366,6 @@ def dummy_webhook_app_payment_data(dummy_payment_data, payment_app):return dummy_payment_data-def new_sale(category, channel_USD):- sale = Sale.objects.create(name="Sale")- SaleChannelListing.objects.create(- sale=sale,- channel=channel_USD,- discount_value=5,- currency=channel_USD.currency_code,- )- return sale---def sale(product, category, collection, variant, channel_USD):- sale = Sale.objects.create(name="Sale")- SaleChannelListing.objects.create(- sale=sale,- channel=channel_USD,- discount_value=5,- currency=channel_USD.currency_code,- )- sale.products.add(product)- sale.categories.add(category)- sale.collections.add(collection)- sale.variants.add(variant)- return sale---def sale_with_many_channels(product, category, collection, channel_USD, channel_PLN):- sale = Sale.objects.create(name="Sale")- SaleChannelListing.objects.create(- sale=sale,- channel=channel_USD,- discount_value=5,- currency=channel_USD.currency_code,- )- SaleChannelListing.objects.create(- sale=sale,- channel=channel_PLN,- discount_value=5,- currency=channel_PLN.currency_code,- )- sale.products.add(product)- sale.categories.add(category)- sale.collections.add(collection)- return sale---def discount_info(category, collection, sale, channel_USD):- sale_channel_listing = sale.channel_listings.get(channel=channel_USD)-- return DiscountInfo(- sale=sale,- channel_listings={channel_USD.slug: sale_channel_listing},- product_ids=set(),- category_ids={category.id}, # assumes this category does not have children- collection_ids={collection.id},- variants_ids=set(),- )---def discount_info_JPY(sale, product_in_channel_JPY, channel_JPY):- sale_channel_listing = sale.channel_listings.create(- channel=channel_JPY,- discount_value=5,- currency=channel_JPY.currency_code,- )-- return DiscountInfo(- sale=sale,- channel_listings={channel_JPY.slug: sale_channel_listing},- product_ids={product_in_channel_JPY.id},- category_ids=set(),- collection_ids=set(),- variants_ids=set(),- )--@pytest.fixturedef promotion(channel_USD, product, collection):promotion = Promotion.objects.create(@@ -5506,6 +5420,20 @@ def promotion_without_rules(db):return promotion+def promotion_with_single_rule(catalogue_predicate, channel_USD):+ promotion = Promotion.objects.create(name="Promotion with single rule")+ rule = PromotionRule.objects.create(+ name="Sale rule",+ promotion=promotion,+ catalogue_predicate=catalogue_predicate,+ reward_value_type=RewardValueType.FIXED,+ reward_value=Decimal(5),+ )+ rule.channels.add(channel_USD)+ return promotion++@pytest.fixturedef promotion_list(channel_USD, product, collection):promotions = Promotion.objects.bulk_create(@@ -5637,20 +5565,69 @@ def rule_info(@pytest.fixture-def promotion_converted_from_sale(sale):- from ..discount.tests.sale_converter import convert_sales_to_promotions+def catalogue_predicate(product, category, collection, variant):+ collection_id = graphene.Node.to_global_id("Collection", collection.id)+ category_id = graphene.Node.to_global_id("Category", category.id)+ product_id = graphene.Node.to_global_id("Product", product.id)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ return {+ "OR": [+ {"collectionPredicate": {"ids": [collection_id]}},+ {"categoryPredicate": {"ids": [category_id]}},+ {"productPredicate": {"ids": [product_id]}},+ {"variantPredicate": {"ids": [variant_id]}},+ ]+ }- convert_sales_to_promotions()- return Promotion.objects.filter(old_sale_id=sale.id).last()++def promotion_converted_from_sale(catalogue_predicate, channel_USD):+ promotion = Promotion.objects.create(name="Sale")+ promotion.assign_old_sale_id()++ rule = PromotionRule.objects.create(+ name="Sale rule",+ promotion=promotion,+ catalogue_predicate=catalogue_predicate,+ reward_value_type=RewardValueType.FIXED,+ reward_value=Decimal(5),+ old_channel_listing_id=PromotionRule.get_old_channel_listing_ids(1)[0][0],+ )+ rule.channels.add(channel_USD)+ return promotion@pytest.fixture-def promotion_converted_from_sale_with_empty_predicate():- from ..discount.tests.sale_converter import convert_sales_to_promotions+def promotion_converted_from_sale_with_many_channels(+ promotion_converted_from_sale, catalogue_predicate, channel_PLN+):+ promotion = promotion_converted_from_sale+ rule = PromotionRule.objects.create(+ name="Sale rule 2",+ promotion=promotion,+ catalogue_predicate=catalogue_predicate,+ reward_value_type=RewardValueType.FIXED,+ reward_value=Decimal(5),+ old_channel_listing_id=PromotionRule.get_old_channel_listing_ids(1)[0][0],+ )+ rule.channels.add(channel_PLN)+ return promotion- sale = Sale.objects.create(name="Sale with no rules", type=DiscountValueType.FIXED)- convert_sales_to_promotions()- return Promotion.objects.filter(old_sale_id=sale.id).last()++def promotion_converted_from_sale_with_empty_predicate(channel_USD):+ promotion = Promotion.objects.create(name="Sale with empty predicate")+ promotion.assign_old_sale_id()+ rule = PromotionRule.objects.create(+ name="Sale with empty predicate rule",+ promotion=promotion,+ catalogue_predicate={},+ reward_value_type=RewardValueType.FIXED,+ reward_value=Decimal(5),+ old_channel_listing_id=PromotionRule.get_old_channel_listing_ids(1)[0][0],+ )+ rule.channels.add(channel_USD)+ return promotion@pytest.fixture@@ -6405,20 +6382,6 @@ def promotion_rule_translation_fr(promotion_rule):)-def sale_translation_fr(sale):- return SaleTranslation.objects.create(- language_code="fr", sale=sale, name="French sale name"- )---def new_sale_translation_fr(new_sale):- return SaleTranslation.objects.create(- language_code="fr", sale=new_sale, name="French sale name"- )--@pytest.fixturedef menu_item_translation_fr(menu_item):return MenuItemTranslation.objects.create(@@ -8172,7 +8135,6 @@ def async_subscription_webhooks_with_root_objects(shipping_method,product,fulfilled_order,- sale,fulfillment,stock,customer_user,@@ -8188,6 +8150,7 @@ def async_subscription_webhooks_with_root_objects(transaction_item_created_by_app,product_media_image,user_export_file,+ promotion_converted_from_sale,):events = WebhookEventAsyncTypeattr = numeric_attribute@@ -8351,10 +8314,22 @@ def async_subscription_webhooks_with_root_objects(subscription_product_variant_metadata_updated_webhook,product,],- events.SALE_CREATED: [subscription_sale_created_webhook, sale],- events.SALE_UPDATED: [subscription_sale_updated_webhook, sale],- events.SALE_DELETED: [subscription_sale_deleted_webhook, sale],- events.SALE_TOGGLE: [subscription_sale_toggle_webhook, sale],+ events.SALE_CREATED: [+ subscription_sale_created_webhook,+ promotion_converted_from_sale,+ ],+ events.SALE_UPDATED: [+ subscription_sale_updated_webhook,+ promotion_converted_from_sale,+ ],+ events.SALE_DELETED: [+ subscription_sale_deleted_webhook,+ promotion_converted_from_sale,+ ],+ events.SALE_TOGGLE: [+ subscription_sale_toggle_webhook,+ promotion_converted_from_sale,+ ],events.INVOICE_REQUESTED: [subscription_invoice_requested_webhook, invoice],events.INVOICE_DELETED: [subscription_invoice_deleted_webhook, invoice],events.INVOICE_SENT: [subscription_invoice_sent_webhook, invoice],