Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Minimal discounted product price refactoring (#12713)
Iga Karbowiak79a371f135f6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e41c7bccd4..ecd859644b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,6 +55,7 @@ All notable, unreleased changes to this project will be documented in this file.- Remove `ENABLE_ACCOUNT_CONFIRMATION_BY_EMAIL` env variable from settings - ##12781 by @SzymJ- Match `Orders` to `User` when creating user using OIDC plugin. - #12863 by @kadewu- Allow defining a custom price in draft orders - #12855 by @KirillPlaksin+- Update price resolvers - use `discounted_price` on `ProductChannelListing` and `ProductVariantChannelListing` channel listings to return the pricing - #12713 by @IKarbowiak# 3.13.0diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 0e877db5bb..b91d35e121 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -82,7 +82,7 @@ from ...product.models import (VariantMedia,)from ...product.search import update_products_search_vector-from ...product.tasks import update_products_discounted_prices_of_discount_task+from ...product.tasks import update_products_discounted_prices_of_sale_taskfrom ...product.utils.variant_prices import update_products_discounted_pricesfrom ...shipping.models import (ShippingMethod,@@ -979,7 +979,7 @@ def create_orders(how_many=10):def create_product_sales(how_many=5):for _ in range(how_many):sale = create_fake_sale()- update_products_discounted_prices_of_discount_task.delay(sale.pk)+ update_products_discounted_prices_of_sale_task.delay(sale.pk)yield f"Sale: {sale}"diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.pyindex badd70844a..559626bc6a 100644--- a/saleor/discount/tasks.py+++ b/saleor/discount/tasks.py@@ -10,6 +10,7 @@ from django.db.models import F, Qfrom ..celeryconf import appfrom ..graphql.discount.mutations.utils import CATALOGUE_FIELD_TO_TYPE_NAMEfrom ..plugins.manager import get_plugins_manager+from ..product.tasks import update_products_discounted_prices_of_catalogues_taskfrom .models import Salefrom .utils import CATALOGUE_FIELDS, CatalogueInfo@@ -17,21 +18,34 @@ task_logger = get_task_logger(__name__)@app.task-def send_sale_toggle_notifications():- """Send the notification about starting or ending sales."""+def handle_sale_toggle():+ """Send the notification about sales toggle and recalculate discounted prcies.++ Send the notifications about starting or ending sales and call recalculation+ of product discounted prices.+ """manager = get_plugins_manager()sales = get_sales_to_notify_about()- catalogue_infos = fetch_catalogue_infos(sales)+ sale_id_to_catalogue_infos, catalogue_infos = fetch_catalogue_infos(sales)if not sales:returnfor sale in sales:- catalogues = catalogue_infos.get(sale.id)+ catalogues = sale_id_to_catalogue_infos.get(sale.id)manager.sale_toggle(sale, catalogues)+ if catalogue_infos:+ # Recalculate discounts of affected products+ update_products_discounted_prices_of_catalogues_task.delay(+ product_ids=list(catalogue_infos["products"]),+ category_ids=list(catalogue_infos["categories"]),+ collection_ids=list(catalogue_infos["collections"]),+ variant_ids=list(catalogue_infos["variants"]),+ )+sale_ids = ", ".join([str(sale.id) for sale in sales])sales.update(notification_sent_datetime=datetime.now(pytz.UTC))@@ -39,19 +53,20 @@ def send_sale_toggle_notifications():def fetch_catalogue_infos(sales):- catalogue_info: Dict[int, CatalogueInfo] = {}+ catalogue_info = defaultdict(set)+ sale_id_to_catalogue_info: Dict[int, CatalogueInfo] = defaultdict(+ lambda: defaultdict(set)+ )for sale_data in sales.values("id", *CATALOGUE_FIELDS):sale_id = sale_data["id"]- if sale_id not in catalogue_info:- catalogue_info[sale_data["id"]] = defaultdict(set)-for field in CATALOGUE_FIELDS:if id := sale_data.get(field):type_name = CATALOGUE_FIELD_TO_TYPE_NAME[field]global_id = graphene.Node.to_global_id(type_name, id)- catalogue_info[sale_data["id"]][field].add(global_id)+ sale_id_to_catalogue_info[sale_id][field].add(global_id)+ catalogue_info[field].add(id)- return catalogue_info+ return sale_id_to_catalogue_info, catalogue_infodef get_sales_to_notify_about():diff --git a/saleor/discount/tests/test_tasks.py b/saleor/discount/tests/test_tasks.pyindex 45187ae04d..1c89d8a5b0 100644--- a/saleor/discount/tests/test_tasks.py+++ b/saleor/discount/tests/test_tasks.py@@ -1,3 +1,4 @@+from collections import defaultdictfrom datetime import timedeltafrom unittest.mock import ANY, patch@@ -6,7 +7,7 @@ from django.utils import timezonefrom freezegun import freeze_timefrom ..models import Sale-from ..tasks import fetch_catalogue_infos, send_sale_toggle_notifications+from ..tasks import fetch_catalogue_infos, handle_sale_toggledef test_fetch_catalogue_infos(sale, new_sale):@@ -14,36 +15,62 @@ def test_fetch_catalogue_infos(sale, new_sale):sales = Sale.objects.all()# when- catalogue_infos = fetch_catalogue_infos(sales)+ sale_id_to_catalogue_infos, catalogue_infos = fetch_catalogue_infos(sales)# then+ expected_catalogue_info = defaultdict(set)for sale_instance in sales:- catalogue_info = catalogue_infos[sale_instance.id]+ catalogue_info = sale_id_to_catalogue_infos[sale_instance.id]+ category_ids = sale_instance.categories.all().values_list("id", flat=True)+ collection_ids = sale_instance.collections.all().values_list("id", flat=True)+ product_ids = sale_instance.products.all().values_list("id", flat=True)+ variant_ids = sale_instance.variants.all().values_list("id", flat=True)assert catalogue_info["categories"] == set(- graphene.Node.to_global_id("Category", id)- for id in sale_instance.categories.all().values_list("id", flat=True)+ graphene.Node.to_global_id("Category", id) for id in category_ids)assert catalogue_info["collections"] == set(- graphene.Node.to_global_id("Collection", id)- for id in sale_instance.collections.all().values_list("id", flat=True)+ graphene.Node.to_global_id("Collection", id) for id in collection_ids)assert catalogue_info["products"] == set(- graphene.Node.to_global_id("Product", id)- for id in sale_instance.products.all().values_list("id", flat=True)+ graphene.Node.to_global_id("Product", id) for id in product_ids)assert catalogue_info["variants"] == set(- graphene.Node.to_global_id("ProductVariant", id)- for id in sale_instance.variants.all().values_list("id", flat=True)+ graphene.Node.to_global_id("ProductVariant", id) for id in variant_ids)+ expected_catalogue_info["categories"].update(set(category_ids))+ expected_catalogue_info["collections"].update(set(collection_ids))+ expected_catalogue_info["products"].update(set(product_ids))+ expected_catalogue_info["variants"].update(set(variant_ids))++ assert catalogue_infos == expected_catalogue_info@freeze_time("2020-03-18 12:00:00")+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_toggle")-def test_send_sale_toggle_notifications(sale_toggle_mock):+def test_handle_sale_toggle(+ sale_toggle_mock,+ mock_update_products_discounted_prices_of_catalogues,+ collection_list,+ product_list,+ category,+):# givennow = timezone.now()sales = Sale.objects.bulk_create([Sale(name=f"Sale-{i}") for i in range(10)])+ variant_ids = []+ for collection, product, sale in zip(collection_list, product_list, sales):+ sale.collections.add(collection)+ sale.products.add(product)+ variant = product.variants.first()+ sale.variants.add(variant)+ variant_ids.append(variant.id)++ sales[7].categories.add(category)+# sales with start date before current date# without notification sent day - should be sentsales[0].start_date = now - timedelta(days=1)@@ -100,19 +127,29 @@ def test_send_sale_toggle_notifications(sale_toggle_mock):"notification_sent_datetime",],)+ indexes_of_toggle_sales = [0, 2, 5, 7]# when- send_sale_toggle_notifications()+ handle_sale_toggle()# thenassert sale_toggle_mock.call_count == 4started_args_list = [args.args for args in sale_toggle_mock.call_args_list]- assert (sales[0], ANY) in started_args_list- assert (sales[2], ANY) in started_args_list- assert (sales[5], ANY) in started_args_list- assert (sales[7], ANY) in started_args_list+ for index in indexes_of_toggle_sales:+ assert (sales[index], ANY) in started_args_list- for index in [0, 2, 5, 7]:+ for index in indexes_of_toggle_sales:sales[index].refresh_from_db()assert sales[index].notification_sent_datetime == now++ mock_update_products_discounted_prices_of_catalogues.assert_called_once()+ args, kwargs = mock_update_products_discounted_prices_of_catalogues.call_args+ # get ids of instances assigned to sales that toggle+ assert set(kwargs["product_ids"]) == {product_list[0].id, product_list[2].id}+ assert set(kwargs["category_ids"]) == {category.id}+ assert set(kwargs["collection_ids"]) == {+ collection_list[0].id,+ collection_list[2].id,+ }+ assert set(kwargs["variant_ids"]) == {variant_ids[0], variant_ids[2]}diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 68b75eb279..72230c6611 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -109,17 +109,16 @@ def get_product_discount_on_sale(def get_product_discounts(*,product: "Product",- collections: Iterable["Collection"],+ collection_ids: Set[int],discounts: Iterable[DiscountInfo],channel: "Channel",variant_id: Optional[int] = None,) -> Iterator[Tuple[int, Callable]]:"""Return sale ids, discount values for all discounts applicable to a product."""- product_collections = set(pc.id for pc in collections)for discount in discounts:try:yield get_product_discount_on_sale(- product, product_collections, discount, channel, variant_id=variant_id+ product, collection_ids, discount, channel, variant_id=variant_id)except NotApplicable:pass@@ -129,7 +128,7 @@ def get_sale_id_with_min_price(*,product: "Product",price: Money,- collections: Iterable["Collection"],+ collection_ids: Set[int],discounts: Optional[Iterable[DiscountInfo]],channel: "Channel",variant_id: Optional[int] = None,@@ -139,7 +138,7 @@ def get_sale_id_with_min_price((sale_id, discount)for sale_id, discount in get_product_discounts(product=product,- collections=collections,+ collection_ids=collection_ids,discounts=discounts or [],channel=channel,variant_id=variant_id,@@ -159,7 +158,7 @@ def calculate_discounted_price(*,product: "Product",price: Money,- collections: Iterable["Collection"],+ collection_ids: Set[int],discounts: Optional[Iterable[DiscountInfo]],channel: "Channel",variant_id: Optional[int] = None,@@ -169,7 +168,7 @@ def calculate_discounted_price(_, price = get_sale_id_with_min_price(product=product,price=price,- collections=collections,+ collection_ids=collection_ids,discounts=discounts,channel=channel,variant_id=variant_id,@@ -190,10 +189,11 @@ def get_sale_id_applied_as_a_discount(if not discounts:return None+ collection_ids = {collection.id for collection in collections}sale_id, _ = get_sale_id_with_min_price(product=product,price=price,- collections=collections,+ collection_ids=collection_ids,discounts=discounts,channel=channel,variant_id=variant_id,diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 039f6a0d33..f390070e38 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -361,6 +361,7 @@ def test_create_checkout_with_reservations(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -390,7 +391,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(68):+ with django_assert_num_queries(67):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -408,7 +409,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(68):+ with django_assert_num_queries(67):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10@@ -627,6 +628,7 @@ def test_update_checkout_lines_with_reservations(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -658,7 +660,7 @@ def test_update_checkout_lines_with_reservations(reservation_length=5,)- with django_assert_num_queries(76):+ with django_assert_num_queries(75):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"id": to_global_id_or_none(checkout),@@ -672,7 +674,7 @@ def test_update_checkout_lines_with_reservations(assert not data["errors"]# Updating multiple lines in checkout has same query count as updating one- with django_assert_num_queries(76):+ with django_assert_num_queries(75):variables = {"id": to_global_id_or_none(checkout),"lines": [],@@ -897,6 +899,7 @@ def test_add_checkout_lines_with_reservations(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -916,7 +919,7 @@ def test_add_checkout_lines_with_reservations(new_lines.append({"quantity": 2, "variantId": variant_id})# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(75):+ with django_assert_num_queries(74):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -929,7 +932,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(75):+ with django_assert_num_queries(74):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,diff --git a/saleor/graphql/discount/mutations/bulk_mutations.py b/saleor/graphql/discount/mutations/bulk_mutations.pyindex cb115cd90d..040519e138 100644--- a/saleor/graphql/discount/mutations/bulk_mutations.py+++ b/saleor/graphql/discount/mutations/bulk_mutations.py@@ -1,8 +1,11 @@+from collections import defaultdict+import graphenefrom ....discount import models-from ....discount.utils import fetch_catalogue_info+from ....discount.utils import CATALOGUE_FIELDS, fetch_catalogue_infofrom ....permission.enums import DiscountPermissions+from ....product.tasks import update_products_discounted_prices_of_catalogues_taskfrom ...core import ResolveInfofrom ...core.mutations import ModelBulkDeleteMutationfrom ...core.types import DiscountError, NonNullList@@ -27,14 +30,27 @@ class SaleBulkDelete(ModelBulkDeleteMutation):@classmethoddef bulk_action(cls, info: ResolveInfo, queryset, /):- sales_and_catalogues = [- (sale, convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale)))- for sale in list(queryset)+ sales_and_catalogue_infos = [+ (sale, fetch_catalogue_info(sale)) for sale in queryset]+queryset.delete()++ catalogues_to_recalculate = defaultdict(set)manager = get_plugin_manager_promise(info.context).get()- for sale, previous_catalogue in sales_and_catalogues:- manager.sale_deleted(sale, previous_catalogue)+ for sale, catalogue_info in sales_and_catalogue_infos:+ manager.sale_deleted(+ sale, convert_catalogue_info_to_global_ids(catalogue_info)+ )+ for field in CATALOGUE_FIELDS:+ catalogues_to_recalculate[field].update(catalogue_info[field])++ update_products_discounted_prices_of_catalogues_task.delay(+ product_ids=list(catalogues_to_recalculate["products"]),+ category_ids=list(catalogues_to_recalculate["categories"]),+ collection_ids=list(catalogues_to_recalculate["collections"]),+ variant_ids=list(catalogues_to_recalculate["variants"]),+ )class VoucherBulkDelete(ModelBulkDeleteMutation):diff --git a/saleor/graphql/discount/mutations/sale_base_discount_catalogue.py b/saleor/graphql/discount/mutations/sale_base_discount_catalogue.pyindex b3f2cf89a8..8936a3a4a8 100644--- a/saleor/graphql/discount/mutations/sale_base_discount_catalogue.py+++ b/saleor/graphql/discount/mutations/sale_base_discount_catalogue.py@@ -40,7 +40,10 @@ class BaseDiscountCatalogueMutation(BaseMutation):variants = cls.get_nodes_or_error(variants, "variants", ProductVariant)node.variants.add(*variants)# Updated the db entries, recalculating discounts of affected products- cls.recalculate_discounted_prices(products, categories, collections, variants)+ if products or categories or collections or variants:+ cls.recalculate_discounted_prices(+ products, categories, collections, variants+ )@classmethoddef clean_product(cls, products):diff --git a/saleor/graphql/discount/mutations/sale_channel_listing_update.py b/saleor/graphql/discount/mutations/sale_channel_listing_update.pyindex 5fade142b0..086140b026 100644--- a/saleor/graphql/discount/mutations/sale_channel_listing_update.py+++ b/saleor/graphql/discount/mutations/sale_channel_listing_update.py@@ -9,7 +9,7 @@ from ....discount import DiscountValueTypefrom ....discount.error_codes import DiscountErrorCodefrom ....discount.models import SaleChannelListingfrom ....permission.enums import DiscountPermissions-from ....product.tasks import update_products_discounted_prices_of_discount_task+from ....product.tasks import update_products_discounted_prices_of_sale_taskfrom ...channel import ChannelContextfrom ...channel.mutations import BaseChannelListingMutationfrom ...core import ResolveInfo@@ -137,7 +137,7 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):with traced_atomic_transaction():cls.add_channels(sale, cleaned_input.get("add_channels", []))cls.remove_channels(sale, cleaned_input.get("remove_channels", []))- update_products_discounted_prices_of_discount_task.delay(sale.pk)+ update_products_discounted_prices_of_sale_task.delay(sale.pk)@classmethoddef perform_mutation( # type: ignore[override]diff --git a/saleor/graphql/discount/mutations/sale_create.py b/saleor/graphql/discount/mutations/sale_create.pyindex 2125a81eca..2195864d12 100644--- a/saleor/graphql/discount/mutations/sale_create.py+++ b/saleor/graphql/discount/mutations/sale_create.py@@ -9,7 +9,7 @@ from ....discount import modelsfrom ....discount.error_codes import DiscountErrorCodefrom ....discount.utils import fetch_catalogue_infofrom ....permission.enums import DiscountPermissions-from ....product.tasks import update_products_discounted_prices_of_discount_task+from ....product.tasks import update_products_discounted_prices_of_sale_taskfrom ...channel import ChannelContextfrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_31@@ -24,17 +24,6 @@ from ..types import Salefrom .utils import convert_catalogue_info_to_global_ids-class SaleUpdateDiscountedPriceMixin:- @classmethod- def success_response(cls, instance):- # Update the "discounted_prices" of the associated, discounted- # products (including collections and categories).- update_products_discounted_prices_of_discount_task.delay(instance.pk)- return super().success_response( # type: ignore[misc] # mixin- ChannelContext(node=instance, channel_slug=None)- )--class SaleInput(BaseInputObjectType):name = graphene.String(description="Voucher name.")type = DiscountValueTypeEnum(description="Fixed or percentage.")@@ -68,7 +57,7 @@ class SaleInput(BaseInputObjectType):doc_category = DOC_CATEGORY_DISCOUNTS-class SaleCreate(SaleUpdateDiscountedPriceMixin, ModelMutation):+class SaleCreate(ModelMutation):class Arguments:input = SaleInput(required=True, description="Fields required to create a sale."@@ -93,6 +82,12 @@ class SaleCreate(SaleUpdateDiscountedPriceMixin, ModelMutation):error.code = DiscountErrorCode.INVALID.valueraise ValidationError({"end_date": error})+ @classmethod+ def success_response(cls, instance):+ return super().success_response(+ ChannelContext(node=instance, channel_slug=None)+ )+@classmethoddef perform_mutation(cls, _root, info: ResolveInfo, /, **data):with traced_atomic_transaction():@@ -100,6 +95,7 @@ class SaleCreate(SaleUpdateDiscountedPriceMixin, ModelMutation):instance = getattr(response, cls._meta.return_field_name).nodemanager = get_plugin_manager_promise(info.context).get()cls.send_sale_notifications(manager, instance)+ update_products_discounted_prices_of_sale_task.delay(instance.pk)return response@classmethoddiff --git a/saleor/graphql/discount/mutations/sale_delete.py b/saleor/graphql/discount/mutations/sale_delete.pyindex 1b28988d2b..ccd2a4a943 100644--- a/saleor/graphql/discount/mutations/sale_delete.py+++ b/saleor/graphql/discount/mutations/sale_delete.py@@ -5,15 +5,16 @@ from ....discount import modelsfrom ....discount.utils import fetch_catalogue_infofrom ....graphql.core.mutations import ModelDeleteMutationfrom ....permission.enums import DiscountPermissions+from ....product.tasks import update_products_discounted_prices_of_catalogues_task+from ...channel import ChannelContextfrom ...core import ResolveInfofrom ...core.types import DiscountErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Sale-from .sale_create import SaleUpdateDiscountedPriceMixinfrom .utils import convert_catalogue_info_to_global_ids-class SaleDelete(SaleUpdateDiscountedPriceMixin, ModelDeleteMutation):+class SaleDelete(ModelDeleteMutation):class Arguments:id = graphene.ID(required=True, description="ID of a sale to delete.")@@ -39,4 +40,12 @@ class SaleDelete(SaleUpdateDiscountedPriceMixin, ModelDeleteMutation):instance, convert_catalogue_info_to_global_ids(previous_catalogue)))+ update_products_discounted_prices_of_catalogues_task.delay(+ product_ids=list(previous_catalogue["products"]),+ category_ids=list(previous_catalogue["categories"]),+ collection_ids=list(previous_catalogue["collections"]),+ variant_ids=list(previous_catalogue["variants"]),+ )+ response.sale = ChannelContext(node=instance, channel_slug=None)+return responsediff --git a/saleor/graphql/discount/mutations/sale_update.py b/saleor/graphql/discount/mutations/sale_update.pyindex 922f66789f..334b14d488 100644--- a/saleor/graphql/discount/mutations/sale_update.py+++ b/saleor/graphql/discount/mutations/sale_update.py@@ -1,3 +1,4 @@+from collections import defaultdictfrom datetime import datetimeimport graphene@@ -5,18 +6,20 @@ import pytzfrom ....core.tracing import traced_atomic_transactionfrom ....discount import models-from ....discount.utils import fetch_catalogue_info+from ....discount.utils import CATALOGUE_FIELDS, fetch_catalogue_infofrom ....permission.enums import DiscountPermissions+from ....product.tasks import update_products_discounted_prices_of_catalogues_task+from ...channel import ChannelContextfrom ...core import ResolveInfofrom ...core.mutations import ModelMutationfrom ...core.types import DiscountErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Sale-from .sale_create import SaleInput, SaleUpdateDiscountedPriceMixin+from .sale_create import SaleInputfrom .utils import convert_catalogue_info_to_global_ids-class SaleUpdate(SaleUpdateDiscountedPriceMixin, ModelMutation):+class SaleUpdate(ModelMutation):class Arguments:id = graphene.ID(required=True, description="ID of a sale to update.")input = SaleInput(@@ -44,18 +47,32 @@ class SaleUpdate(SaleUpdateDiscountedPriceMixin, ModelMutation):cls.clean_instance(info, instance)cls.save(info, instance, cleaned_input)cls._save_m2m(info, instance, cleaned_input)+ current_catalogue = fetch_catalogue_info(instance)cls.send_sale_notifications(- manager, instance, cleaned_input, previous_catalogue, previous_end_date+ manager,+ instance,+ cleaned_input,+ previous_catalogue,+ current_catalogue,+ previous_end_date,)- return cls.success_response(instance)++ cls.update_products_discounted_prices(+ cleaned_input, previous_catalogue, current_catalogue+ )+ return cls.success_response(ChannelContext(node=instance, channel_slug=None))@classmethoddef send_sale_notifications(- cls, manager, instance, cleaned_input, previous_catalogue, previous_end_date+ cls,+ manager,+ instance,+ cleaned_input,+ previous_catalogue,+ current_catalogue,+ previous_end_date,):- current_catalogue = convert_catalogue_info_to_global_ids(- fetch_catalogue_info(instance)- )+ current_catalogue = convert_catalogue_info_to_global_ids(current_catalogue)cls.call_event(manager.sale_updated,instance,@@ -104,3 +121,33 @@ class SaleUpdate(SaleUpdateDiscountedPriceMixin, ModelMutation):manager.sale_toggle(instance, catalogue)instance.notification_sent_datetime = nowinstance.save(update_fields=["notification_sent_datetime"])++ @staticmethod+ def update_products_discounted_prices(+ cleaned_input, previous_catalogue, current_catalogue+ ):+ catalogues_to_recalculate = defaultdict(set)+ for catalogue_field in CATALOGUE_FIELDS:+ if any(+ [+ field in cleaned_input+ for field in [+ catalogue_field,+ "start_date",+ "end_date",+ "type",+ "value",+ ]+ ]+ ):+ catalogues_to_recalculate[catalogue_field] = previous_catalogue[+ catalogue_field+ ].union(current_catalogue[catalogue_field])++ if catalogues_to_recalculate:+ update_products_discounted_prices_of_catalogues_task.delay(+ product_ids=list(catalogues_to_recalculate["products"]),+ category_ids=list(catalogues_to_recalculate["categories"]),+ collection_ids=list(catalogues_to_recalculate["collections"]),+ variant_ids=list(catalogues_to_recalculate["variants"]),+ )diff --git a/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py b/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.pyindex 0c29d43543..56f31496ac 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_bulk_delete.py@@ -1,3 +1,4 @@+import itertoolsimport jsonfrom unittest import mock@@ -12,10 +13,17 @@ from ...mutations.utils import convert_catalogue_info_to_global_ids@pytest.fixture-def sale_list(channel_USD):+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")])+ 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)@@ -34,17 +42,49 @@ SALE_BULK_DELETE_MUTATION = """"""-def test_delete_sales(staff_api_client, sale_list, permission_manage_discounts):+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)+def test_delete_sales(+ update_products_discounted_prices_of_catalogues_task_mock,+ staff_api_client,+ sale_list,+ permission_manage_discounts,+ product_list,+):+ # given+variables = {"ids": [graphene.Node.to_global_id("Sale", sale.id) for sale in sale_list]}+ category_pks = itertools.chain.from_iterable(+ [list(sale.categories.values_list("id", flat=True)) for sale in sale_list]+ )+ collection_pks = itertools.chain.from_iterable(+ [list(sale.collections.values_list("id", flat=True)) for sale in sale_list]+ )+ product_pks = itertools.chain.from_iterable(+ [list(sale.products.values_list("id", flat=True)) for sale in sale_list]+ )+ variant_pks = itertools.chain.from_iterable(+ [list(sale.variants.values_list("id", flat=True)) for sale in sale_list]+ )++ # 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 not Sale.objects.filter(id__in=[sale.id for sale in sale_list]).exists()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == set(category_pks)+ assert set(kwargs["collection_ids"]) == set(collection_pks)+ assert set(kwargs["product_ids"]) == set(product_pks)+ assert set(kwargs["variant_ids"]) == set(variant_pks)@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")diff --git a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.pyindex 1558151428..0b996f6027 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_add.py@@ -23,9 +23,13 @@ SALE_CATALOGUES_ADD_MUTATION = """"""+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_updated")def test_sale_add_catalogues(updated_webhook_mock,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,category,@@ -35,6 +39,7 @@ def test_sale_add_catalogues(product_variant_list,permission_manage_discounts,):+ # givenquery = SALE_CATALOGUES_ADD_MUTATIONprevious_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale)@@ -56,9 +61,12 @@ def test_sale_add_catalogues(},}+ # whenresponse = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_discounts])++ # thencurrent_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))content = get_graphql_content(response)data = content["data"]["saleCataloguesAdd"]@@ -72,10 +80,23 @@ def test_sale_add_catalogues(updated_webhook_mock.assert_called_once_with(sale, previous_catalogue=previous_catalogue, current_catalogue=current_catalogue)+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert kwargs["category_ids"] == [category.id]+ assert kwargs["collection_ids"] == [collection.id]+ assert kwargs["product_ids"] == [product.id]+ assert set(kwargs["variant_ids"]) == {+ variant.id for variant in product_variant_list+ }+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)def test_sale_add_no_catalogues(- staff_api_client, new_sale, permission_manage_discounts+ update_products_discounted_prices_of_catalogues_task_mock,+ staff_api_client,+ new_sale,+ permission_manage_discounts,):# givenquery = SALE_CATALOGUES_ADD_MUTATION@@ -98,9 +119,14 @@ def test_sale_add_no_catalogues(assert not new_sale.categories.exists()assert not new_sale.collections.exists()assert not new_sale.variants.exists()+ update_products_discounted_prices_of_catalogues_task_mock.assert_not_called()+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)def test_sale_remove_no_catalogues(+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,category,@@ -135,10 +161,20 @@ def test_sale_remove_no_catalogues(assert sale.categories.exists()assert sale.collections.exists()assert sale.variants.exists()+ update_products_discounted_prices_of_catalogues_task_mock.assert_not_called()+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)def test_sale_add_catalogues_with_product_without_variants(- staff_api_client, sale, category, product, collection, permission_manage_discounts+ update_products_discounted_prices_of_catalogues_task_mock,+ staff_api_client,+ sale,+ category,+ product,+ collection,+ permission_manage_discounts,):query = SALE_CATALOGUES_ADD_MUTATIONproduct.variants.all().delete()@@ -163,3 +199,4 @@ def test_sale_add_catalogues_with_product_without_variants(assert error["code"] == DiscountErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT.nameassert error["message"] == "Cannot manage products without variants."+ update_products_discounted_prices_of_catalogues_task_mock.assert_not_called()diff --git a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.pyindex f4ff0a6f0c..41cd26d26a 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_catalogues_remove.py@@ -22,9 +22,13 @@ SALE_CATALOGUES_REMOVE_MUTATION = """"""+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_updated")def test_sale_remove_catalogues(updated_webhook_mock,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,category,@@ -81,3 +85,10 @@ def test_sale_remove_catalogues(updated_webhook_mock.assert_called_once_with(sale, previous_catalogue=previous_catalogue, current_catalogue=current_catalogue)+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert kwargs["category_ids"] == [category.id]+ assert kwargs["collection_ids"] == [collection.id]+ assert kwargs["product_ids"] == [product.id]+ assert set(kwargs["variant_ids"]) == {+ variant.id for variant in product_variant_list+ }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 cd2ad31326..2f96d34e69 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@@ -35,7 +35,7 @@ mutation UpdateSaleChannelListing(@patch("saleor.graphql.discount.mutations.sale_channel_listing_update"- ".update_products_discounted_prices_of_discount_task"+ ".update_products_discounted_prices_of_sale_task")def test_sale_channel_listing_create_as_staff_user(mock_update_discounted_prices_of_discount_task,@@ -83,7 +83,7 @@ def test_sale_channel_listing_create_as_staff_user(@patch("saleor.graphql.discount.mutations.sale_channel_listing_update"- ".update_products_discounted_prices_of_discount_task"+ ".update_products_discounted_prices_of_sale_task")def test_sale_channel_listing_update_as_staff_user(mock_update_discounted_prices_of_discount_task,@@ -162,8 +162,16 @@ def test_sale_channel_listing_update_with_negative_discounted_value(assert_negative_positive_decimal_value(response)+@patch(+ "saleor.graphql.discount.mutations.sale_channel_listing_update"+ ".update_products_discounted_prices_of_sale_task"+)def test_sale_channel_listing_update_duplicated_ids_in_add_and_remove(- staff_api_client, sale, permission_manage_discounts, channel_USD+ mock_update_discounted_prices_of_discount_task,+ staff_api_client,+ sale,+ permission_manage_discounts,+ channel_USD,):# givensale_id = graphene.Node.to_global_id("Sale", sale.pk)@@ -191,10 +199,19 @@ def test_sale_channel_listing_update_duplicated_ids_in_add_and_remove(assert errors[0]["field"] == "input"assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.nameassert errors[0]["channels"] == [channel_id]+ mock_update_discounted_prices_of_discount_task.assert_not_called()+@patch(+ "saleor.graphql.discount.mutations.sale_channel_listing_update"+ ".update_products_discounted_prices_of_sale_task"+)def test_sale_channel_listing_update_duplicated_channel_in_add(- staff_api_client, sale, permission_manage_discounts, channel_USD+ mock_update_discounted_prices_of_discount_task,+ staff_api_client,+ sale,+ permission_manage_discounts,+ channel_USD,):# givensale_id = graphene.Node.to_global_id("Sale", sale.pk)@@ -224,10 +241,19 @@ def test_sale_channel_listing_update_duplicated_channel_in_add(assert errors[0]["field"] == "addChannels"assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.nameassert errors[0]["channels"] == [channel_id]+ mock_update_discounted_prices_of_discount_task.assert_not_called()+@patch(+ "saleor.graphql.discount.mutations.sale_channel_listing_update"+ ".update_products_discounted_prices_of_sale_task"+)def test_sale_channel_listing_update_duplicated_channel_in_remove(- staff_api_client, sale, permission_manage_discounts, channel_USD+ mock_update_discounted_prices_of_discount_task,+ staff_api_client,+ sale,+ permission_manage_discounts,+ channel_USD,):# givensale_id = graphene.Node.to_global_id("Sale", sale.pk)@@ -251,10 +277,19 @@ def test_sale_channel_listing_update_duplicated_channel_in_remove(assert errors[0]["field"] == "removeChannels"assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.nameassert errors[0]["channels"] == [channel_id]+ mock_update_discounted_prices_of_discount_task.assert_not_called()+@patch(+ "saleor.graphql.discount.mutations.sale_channel_listing_update"+ ".update_products_discounted_prices_of_sale_task"+)def test_sale_channel_listing_update_with_invalid_decimal_places(- staff_api_client, sale, permission_manage_discounts, channel_USD+ mock_update_discounted_prices_of_discount_task,+ staff_api_client,+ sale,+ permission_manage_discounts,+ channel_USD,):# givensale_id = graphene.Node.to_global_id("Sale", sale.pk)@@ -281,10 +316,19 @@ def test_sale_channel_listing_update_with_invalid_decimal_places(assert errors[0]["code"] == DiscountErrorCode.INVALID.nameassert errors[0]["field"] == "input"assert errors[0]["channels"] == [channel_id]+ mock_update_discounted_prices_of_discount_task.assert_not_called()+@patch(+ "saleor.graphql.discount.mutations.sale_channel_listing_update"+ ".update_products_discounted_prices_of_sale_task"+)def test_sale_channel_listing_update_with_invalid_percentage_value(- staff_api_client, sale, permission_manage_discounts, channel_USD+ mock_update_discounted_prices_of_discount_task,+ staff_api_client,+ sale,+ permission_manage_discounts,+ channel_USD,):# givensale = sale@@ -314,6 +358,7 @@ def test_sale_channel_listing_update_with_invalid_percentage_value(assert errors[0]["code"] == DiscountErrorCode.INVALID.nameassert errors[0]["field"] == "input"assert errors[0]["channels"] == [channel_id]+ mock_update_discounted_prices_of_discount_task.assert_not_called()SALE_AND_SALE_CHANNEL_LISTING_UPDATE_MUTATION = """@@ -349,8 +394,16 @@ mutation UpdateSaleChannelListing("""+@patch(+ "saleor.graphql.discount.mutations.sale_channel_listing_update"+ ".update_products_discounted_prices_of_sale_task"+)def test_invalidate_data_sale_channel_listings_update(- staff_api_client, sale, permission_manage_discounts, channel_USD+ mock_update_discounted_prices_of_discount_task,+ staff_api_client,+ sale,+ permission_manage_discounts,+ channel_USD,):# givendiscount_value = 10@@ -391,3 +444,6 @@ def test_invalidate_data_sale_channel_listings_update(# response from the second mutation contains dataassert channel_listings_data["channelListings"][0]["channel"]["id"] == channel_id+ mock_update_discounted_prices_of_discount_task.delay.assert_called_once_with(+ sale.pk,+ )diff --git a/saleor/graphql/discount/tests/mutations/test_sale_create.py b/saleor/graphql/discount/tests/mutations/test_sale_create.pyindex 03e6815b19..4dde5e35fb 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_create.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_create.py@@ -33,11 +33,13 @@ SALE_CREATE_MUTATION = """@freeze_time("2020-03-18 12:00:00")+@patch("saleor.product.tasks.update_products_discounted_prices_of_sale_task.delay")@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_created")def test_create_sale(created_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_sale_task_mock,staff_api_client,permission_manage_discounts,product_list,@@ -79,14 +81,17 @@ def test_create_sale(current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))created_webhook_mock.assert_called_once_with(sale, current_catalogue)sale_toggle_mock.assert_called_once_with(sale, current_catalogue)+ update_products_discounted_prices_of_sale_task_mock.assert_called_once_with(sale.id)@freeze_time("2020-03-18 12:00:00")+@patch("saleor.product.tasks.update_products_discounted_prices_of_sale_task.delay")@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_created")def test_create_sale_only_start_date(created_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_sale_task_mock,staff_api_client,permission_manage_discounts,product_list,@@ -126,10 +131,14 @@ def test_create_sale_only_start_date(current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))created_webhook_mock.assert_called_once_with(sale, current_catalogue)sale_toggle_mock.assert_called_once_with(sale, current_catalogue)+ update_products_discounted_prices_of_sale_task_mock.assert_called_once_with(sale.id)-def test_create_sale_with_enddate_before_startdate(- staff_api_client, permission_manage_discounts+@patch("saleor.product.tasks.update_products_discounted_prices_of_sale_task.delay")+def test_create_sale_with_end_date_before_startdate(+ update_products_discounted_prices_of_sale_task_mock,+ staff_api_client,+ permission_manage_discounts,):# givenquery = SALE_CREATE_MUTATION@@ -156,13 +165,16 @@ def test_create_sale_with_enddate_before_startdate(assert len(errors) == 1assert errors[0]["field"] == "endDate"assert errors[0]["code"] == DiscountErrorCode.INVALID.name+ update_products_discounted_prices_of_sale_task_mock.assert_not_called()+@patch("saleor.product.tasks.update_products_discounted_prices_of_sale_task.delay")@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_created")def test_create_sale_start_date_and_end_date_before_current_date(created_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_sale_task_mock,staff_api_client,permission_manage_discounts,product_list,@@ -206,13 +218,16 @@ def test_create_sale_start_date_and_end_date_before_current_date(current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))created_webhook_mock.assert_called_once_with(sale, current_catalogue)sale_toggle_mock.assert_not_called()+ update_products_discounted_prices_of_sale_task_mock.assert_called_once_with(sale.id)+@patch("saleor.product.tasks.update_products_discounted_prices_of_sale_task.delay")@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_created")def test_create_sale_start_date_and_end_date_after_current_date(created_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_sale_task_mock,staff_api_client,permission_manage_discounts,product_list,@@ -256,3 +271,4 @@ def test_create_sale_start_date_and_end_date_after_current_date(current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))created_webhook_mock.assert_called_once_with(sale, current_catalogue)sale_toggle_mock.assert_not_called()+ update_products_discounted_prices_of_sale_task_mock.assert_called_once_with(sale.id)diff --git a/saleor/graphql/discount/tests/mutations/test_sale_delete.py b/saleor/graphql/discount/tests/mutations/test_sale_delete.pyindex 5d8666a5db..bc5c0553f7 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_delete.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_delete.py@@ -24,21 +24,43 @@ SALE_DELETE_MUTATION = """"""+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_deleted")def test_sale_delete_mutation(- deleted_webhook_mock, staff_api_client, sale, permission_manage_discounts+ deleted_webhook_mock,+ update_products_discounted_prices_of_catalogues_task_mock,+ staff_api_client,+ sale,+ permission_manage_discounts,):+ # givenquery = SALE_DELETE_MUTATIONvariables = {"id": graphene.Node.to_global_id("Sale", sale.id)}previous_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))+ category_ids = set(sale.categories.values_list("id", flat=True))+ collection_ids = set(sale.collections.values_list("id", flat=True))+ product_ids = set(sale.products.values_list("id", flat=True))+ variant_ids = set(sale.variants.values_list("id", flat=True))++ # whenresponse = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_discounts])++ # thencontent = get_graphql_content(response)data = content["data"]["saleDelete"]assert data["sale"]["name"] == sale.namedeleted_webhook_mock.assert_called_once_with(sale, previous_catalogue)with pytest.raises(sale._meta.model.DoesNotExist):sale.refresh_from_db()+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_ids+ assert set(kwargs["collection_ids"]) == collection_ids+ assert set(kwargs["product_ids"]) == product_ids+ assert set(kwargs["variant_ids"]) == variant_idsdiff --git a/saleor/graphql/discount/tests/mutations/test_sale_update.py b/saleor/graphql/discount/tests/mutations/test_sale_update.pyindex e3d1901725..f5570df158 100644--- a/saleor/graphql/discount/tests/mutations/test_sale_update.py+++ b/saleor/graphql/discount/tests/mutations/test_sale_update.py@@ -20,6 +20,7 @@ SALE_UPDATE_MUTATION = """message}sale {+ nametypestartDateendDate@@ -29,9 +30,13 @@ SALE_UPDATE_MUTATION = """"""+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_updated")def test_update_sale(updated_webhook_mock,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,permission_manage_discounts,@@ -46,14 +51,21 @@ def test_update_sale(previous_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))- product_ids = [- graphene.Node.to_global_id("Product", product.id) for product in product_list+ category_pks = set(sale.categories.values_list("id", flat=True))+ collection_pks = set(sale.collections.values_list("id", flat=True))+ product_pks = set(sale.products.values_list("id", flat=True))+ variant_pks = set(sale.variants.values_list("id", flat=True))+ new_product_pks = [product.id for product in product_list]++ new_product_ids = [+ graphene.Node.to_global_id("Product", product_id)+ for product_id in new_product_pks]variables = {"id": graphene.Node.to_global_id("Sale", sale.id),"input": {"type": DiscountValueTypeEnum.PERCENTAGE.name,- "products": product_ids,+ "products": new_product_ids,},}@@ -71,14 +83,68 @@ def test_update_sale(updated_webhook_mock.assert_called_once_with(sale, previous_catalogue, current_catalogue)+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_pks+ assert set(kwargs["collection_ids"]) == collection_pks+ assert set(kwargs["product_ids"]) == product_pks.union(new_product_pks)+ assert set(kwargs["variant_ids"]) == variant_pks+++@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)+@patch("saleor.plugins.manager.PluginsManager.sale_updated")+def test_update_sale_name(+ updated_webhook_mock,+ update_products_discounted_prices_of_catalogues_task_mock,+ staff_api_client,+ sale,+ permission_manage_discounts,+ product_list,+):+ # given+ query = SALE_UPDATE_MUTATION++ new_name = "New name"+ previous_catalogue = convert_catalogue_info_to_global_ids(+ fetch_catalogue_info(sale)+ )++ variables = {+ "id": graphene.Node.to_global_id("Sale", sale.id),+ "input": {+ "name": new_name,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_discounts]+ )+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))++ # then+ content = get_graphql_content(response)+ data = content["data"]["saleUpdate"]["sale"]+ assert data["name"] == new_name++ updated_webhook_mock.assert_called_once_with(+ sale, previous_catalogue, current_catalogue+ )+ update_products_discounted_prices_of_catalogues_task_mock.assert_not_called()@freeze_time("2020-03-18 12:00:00")+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_updated")def test_update_sale_start_date_after_current_date_notification_not_sent(updated_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,permission_manage_discounts,@@ -92,6 +158,11 @@ def test_update_sale_start_date_after_current_date_notification_not_sent(sale.notification_sent_datetime = Nonesale.save(update_fields=["notification_sent_datetime"])+ category_pks = set(sale.categories.values_list("id", flat=True))+ collection_pks = set(sale.collections.values_list("id", flat=True))+ product_pks = set(sale.products.values_list("id", flat=True))+ variant_pks = set(sale.variants.values_list("id", flat=True))+previous_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))@@ -122,14 +193,24 @@ def test_update_sale_start_date_after_current_date_notification_not_sent(sale, previous_catalogue, current_catalogue)sale_toggle_mock.assert_not_called()+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_pks+ assert set(kwargs["collection_ids"]) == collection_pks+ assert set(kwargs["product_ids"]) == product_pks+ assert set(kwargs["variant_ids"]) == variant_pks@freeze_time("2020-03-18 12:00:00")+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_updated")def test_update_sale_start_date_before_current_date_notification_already_sent(updated_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,permission_manage_discounts,@@ -147,6 +228,11 @@ def test_update_sale_start_date_before_current_date_notification_already_sent(sale.notification_sent_datetime = notification_sent_datetimesale.save(update_fields=["type", "notification_sent_datetime"])+ category_pks = set(sale.categories.values_list("id", flat=True))+ collection_pks = set(sale.collections.values_list("id", flat=True))+ product_pks = set(sale.products.values_list("id", flat=True))+ variant_pks = set(sale.variants.values_list("id", flat=True))+previous_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))@@ -174,14 +260,24 @@ def test_update_sale_start_date_before_current_date_notification_already_sent(sale, previous_catalogue, current_catalogue)sale_toggle_mock.assert_not_called()+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_pks+ assert set(kwargs["collection_ids"]) == collection_pks+ assert set(kwargs["product_ids"]) == product_pks+ assert set(kwargs["variant_ids"]) == variant_pks@freeze_time("2020-03-18 12:00:00")+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_updated")def test_update_sale_start_date_before_current_date_notification_sent(updated_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,permission_manage_discounts,@@ -198,6 +294,11 @@ def test_update_sale_start_date_before_current_date_notification_sent(sale.notification_sent_datetime = Nonesale.save(update_fields=["type", "notification_sent_datetime"])+ category_pks = set(sale.categories.values_list("id", flat=True))+ collection_pks = set(sale.collections.values_list("id", flat=True))+ product_pks = set(sale.products.values_list("id", flat=True))+ variant_pks = set(sale.variants.values_list("id", flat=True))+previous_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))@@ -224,14 +325,24 @@ def test_update_sale_start_date_before_current_date_notification_sent(sale, previous_catalogue, current_catalogue)sale_toggle_mock.assert_called_once_with(sale, current_catalogue)+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_pks+ assert set(kwargs["collection_ids"]) == collection_pks+ assert set(kwargs["product_ids"]) == product_pks+ assert set(kwargs["variant_ids"]) == variant_pks@freeze_time("2020-03-18 12:00:00")+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_updated")def test_update_sale_end_date_after_current_date_notification_not_sent(updated_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,permission_manage_discounts,@@ -247,6 +358,11 @@ def test_update_sale_end_date_after_current_date_notification_not_sent()end_date = timezone.now() + timedelta(days=1)+ category_pks = set(sale.categories.values_list("id", flat=True))+ collection_pks = set(sale.collections.values_list("id", flat=True))+ product_pks = set(sale.products.values_list("id", flat=True))+ variant_pks = set(sale.variants.values_list("id", flat=True))+variables = {"id": graphene.Node.to_global_id("Sale", sale.id),"input": {"endDate": end_date},@@ -272,14 +388,24 @@ def test_update_sale_end_date_after_current_date_notification_not_sent(sale, previous_catalogue, current_catalogue)sale_toggle_mock.assert_not_called()+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_pks+ assert set(kwargs["collection_ids"]) == collection_pks+ assert set(kwargs["product_ids"]) == product_pks+ assert set(kwargs["variant_ids"]) == variant_pks@freeze_time("2020-03-18 12:00:00")+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_updated")def test_update_sale_end_date_before_current_date_notification_already_sent(updated_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,permission_manage_discounts,@@ -299,6 +425,11 @@ def test_update_sale_end_date_before_current_date_notification_already_sent(sale.notification_sent_datetime = notification_sent_datetimesale.save(update_fields=["type", "notification_sent_datetime"])+ category_pks = set(sale.categories.values_list("id", flat=True))+ collection_pks = set(sale.collections.values_list("id", flat=True))+ product_pks = set(sale.products.values_list("id", flat=True))+ variant_pks = set(sale.variants.values_list("id", flat=True))+previous_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))@@ -326,14 +457,24 @@ def test_update_sale_end_date_before_current_date_notification_already_sent(sale, previous_catalogue, current_catalogue)sale_toggle_mock.assert_called_once_with(sale, current_catalogue)+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_pks+ assert set(kwargs["collection_ids"]) == collection_pks+ assert set(kwargs["product_ids"]) == product_pks+ assert set(kwargs["variant_ids"]) == variant_pks@freeze_time("2020-03-18 12:00:00")+@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)@patch("saleor.plugins.manager.PluginsManager.sale_toggle")@patch("saleor.plugins.manager.PluginsManager.sale_updated")def test_update_sale_end_date_before_current_date_notification_sent(updated_webhook_mock,sale_toggle_mock,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,permission_manage_discounts,@@ -350,6 +491,11 @@ def test_update_sale_end_date_before_current_date_notification_sent(sale.notification_sent_datetime = Nonesale.save(update_fields=["type", "notification_sent_datetime"])+ category_pks = set(sale.categories.values_list("id", flat=True))+ collection_pks = set(sale.collections.values_list("id", flat=True))+ product_pks = set(sale.products.values_list("id", flat=True))+ variant_pks = set(sale.variants.values_list("id", flat=True))+previous_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))@@ -376,3 +522,213 @@ def test_update_sale_end_date_before_current_date_notification_sent(sale, previous_catalogue, current_catalogue)sale_toggle_mock.assert_called_once_with(sale, current_catalogue)+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_pks+ assert set(kwargs["collection_ids"]) == collection_pks+ assert set(kwargs["product_ids"]) == product_pks+ assert set(kwargs["variant_ids"]) == variant_pks+++@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)+@patch("saleor.plugins.manager.PluginsManager.sale_updated")+def test_update_sale_categories(+ updated_webhook_mock,+ update_products_discounted_prices_of_catalogues_task_mock,+ staff_api_client,+ sale,+ permission_manage_discounts,+ product_list,+ non_default_category,+):+ # given+ query = SALE_UPDATE_MUTATION++ previous_catalogue = convert_catalogue_info_to_global_ids(+ fetch_catalogue_info(sale)+ )+ category_pks = set(sale.categories.values_list("id", flat=True))++ variables = {+ "id": graphene.Node.to_global_id("Sale", sale.id),+ "input": {+ "categories": [+ graphene.Node.to_global_id("Category", non_default_category.id)+ ],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_discounts]+ )+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))++ # then+ content = get_graphql_content(response)+ assert not content["data"]["saleUpdate"]["errors"]++ updated_webhook_mock.assert_called_once_with(+ sale, previous_catalogue, current_catalogue+ )+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ category_pks.add(non_default_category.id)+ assert set(kwargs["category_ids"]) == category_pks+ assert kwargs["collection_ids"] == []+ assert kwargs["product_ids"] == []+ assert kwargs["variant_ids"] == []+++@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)+@patch("saleor.plugins.manager.PluginsManager.sale_updated")+def test_update_sale_collections(+ updated_webhook_mock,+ update_products_discounted_prices_of_catalogues_task_mock,+ staff_api_client,+ sale,+ permission_manage_discounts,+ product_list,+ published_collection,+):+ # given+ query = SALE_UPDATE_MUTATION++ previous_catalogue = convert_catalogue_info_to_global_ids(+ fetch_catalogue_info(sale)+ )+ collection_pks = set(sale.collections.values_list("id", flat=True))++ variables = {+ "id": graphene.Node.to_global_id("Sale", sale.id),+ "input": {+ "collections": [+ graphene.Node.to_global_id("Collection", published_collection.id)+ ],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_discounts]+ )+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))++ # then+ content = get_graphql_content(response)+ assert not content["data"]["saleUpdate"]["errors"]++ updated_webhook_mock.assert_called_once_with(+ sale, previous_catalogue, current_catalogue+ )+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ collection_pks.add(published_collection.id)+ assert kwargs["category_ids"] == []+ assert set(kwargs["collection_ids"]) == collection_pks+ assert kwargs["product_ids"] == []+ assert kwargs["variant_ids"] == []+++@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)+@patch("saleor.plugins.manager.PluginsManager.sale_updated")+def test_update_sale_variants(+ updated_webhook_mock,+ update_products_discounted_prices_of_catalogues_task_mock,+ staff_api_client,+ sale,+ permission_manage_discounts,+ product_list,+ preorder_variant_global_threshold,+):+ # given+ query = SALE_UPDATE_MUTATION++ previous_catalogue = convert_catalogue_info_to_global_ids(+ fetch_catalogue_info(sale)+ )+ variant_pks = set(sale.variants.values_list("id", flat=True))++ variables = {+ "id": graphene.Node.to_global_id("Sale", sale.id),+ "input": {+ "variants": [+ graphene.Node.to_global_id(+ "ProductVariant", preorder_variant_global_threshold.id+ )+ ],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_discounts]+ )+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))++ # then+ content = get_graphql_content(response)+ assert not content["data"]["saleUpdate"]["errors"]++ updated_webhook_mock.assert_called_once_with(+ sale, previous_catalogue, current_catalogue+ )+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ variant_pks.add(preorder_variant_global_threshold.id)+ assert kwargs["category_ids"] == []+ assert kwargs["collection_ids"] == []+ assert kwargs["product_ids"] == []+ assert set(kwargs["variant_ids"]) == variant_pks+++@patch(+ "saleor.product.tasks.update_products_discounted_prices_of_catalogues_task.delay"+)+@patch("saleor.plugins.manager.PluginsManager.sale_updated")+def test_update_sale_products(+ updated_webhook_mock,+ update_products_discounted_prices_of_catalogues_task_mock,+ staff_api_client,+ sale,+ permission_manage_discounts,+ product_list,+ published_collection,+):+ # given+ query = SALE_UPDATE_MUTATION++ previous_catalogue = convert_catalogue_info_to_global_ids(+ fetch_catalogue_info(sale)+ )+ product_pks = set(sale.products.values_list("id", flat=True))++ variables = {+ "id": graphene.Node.to_global_id("Sale", sale.id),+ "input": {+ "products": [graphene.Node.to_global_id("Product", product_list[-1].id)],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_discounts]+ )+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))++ # then+ content = get_graphql_content(response)+ assert not content["data"]["saleUpdate"]["errors"]++ updated_webhook_mock.assert_called_once_with(+ sale, previous_catalogue, current_catalogue+ )+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ product_pks.add(product_list[-1].id)+ assert kwargs["category_ids"] == []+ assert kwargs["collection_ids"] == []+ assert set(kwargs["product_ids"]) == product_pks+ assert kwargs["variant_ids"] == []diff --git a/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py b/saleor/graphql/product/bulk_mutations/collection_bulk_delete.pyindex 411057f149..2ba2f2c2b6 100644--- a/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py+++ b/saleor/graphql/product/bulk_mutations/collection_bulk_delete.py@@ -1,7 +1,9 @@import graphene+from django.db.models import Exists, OuterReffrom ....permission.enums import ProductPermissionsfrom ....product import models+from ....product.tasks import update_products_discounted_prices_taskfrom ...core.mutations import ModelBulkDeleteMutationfrom ...core.types import CollectionError, NonNullListfrom ...plugins.dataloaders import get_plugin_manager_promise@@ -25,10 +27,13 @@ class CollectionBulkDelete(ModelBulkDeleteMutation):@classmethoddef bulk_action(cls, info, queryset):collections_ids = queryset.values_list("id", flat=True)+ collection_products = models.CollectionProduct.objects.filter(+ collection_id__in=collections_ids+ )products = list(- models.Product.objects.prefetched_for_webhook(single_object=False)- .filter(collections__in=collections_ids)- .distinct()+ models.Product.objects.prefetched_for_webhook(single_object=False).filter(+ Exists(collection_products.filter(product_id=OuterRef("id")))+ ))manager = get_plugin_manager_promise(info.context).get()for collection in queryset.iterator():@@ -37,3 +42,7 @@ class CollectionBulkDelete(ModelBulkDeleteMutation):for product in products:manager.product_updated(product)++ update_products_discounted_prices_task.delay(+ [product.id for product in products]+ )diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.pyindex 691696aaf4..f4a94ec491 100644--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py@@ -18,6 +18,7 @@ from ....core.utils.validators import get_oembed_datafrom ....permission.enums import ProductPermissionsfrom ....product import ProductMediaTypes, modelsfrom ....product.error_codes import ProductBulkCreateErrorCode+from ....product.tasks import update_products_discounted_prices_taskfrom ....warehouse.models import Warehousefrom ...attribute.types import AttributeValueInputfrom ...attribute.utils import AttributeAssignmentMixin@@ -823,8 +824,10 @@ class ProductBulkCreate(BaseMutation):@classmethoddef post_save_actions(cls, info, products, variants, channels):manager = get_plugin_manager_promise(info.context).get()+ product_ids = []for product in products:cls.call_event(manager.product_created, product.node)+ product_ids.append(product.node.id)for variant in variants:cls.call_event(manager.product_variant_created, variant)@@ -832,6 +835,8 @@ class ProductBulkCreate(BaseMutation):for channel in channels:cls.call_event(manager.channel_updated, channel)+ update_products_discounted_prices_task.delay(product_ids)+@classmethod@traced_atomic_transaction()def perform_mutation(cls, root, info, **data):diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.pyindex 57110f14fd..4e536c688a 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py@@ -805,6 +805,9 @@ class ProductVariantBulkCreate(BaseMutation):channel=listing_data["channel"],variant=variant,price_amount=listing_data["price"],+ # set the discounted price the same as price for now, the discounted+ # value will be calculated asynchronously in the celery task+ discounted_price_amount=listing_data["price"],cost_price_amount=listing_data.get("cost_price"),currency=listing_data["channel"].currency_code,preorder_quantity_threshold=listing_data.get("preorder_threshold"),diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.pyindex 74ab9bac95..0b28e265aa 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py@@ -17,6 +17,7 @@ from ....order.tasks import recalculate_orders_taskfrom ....permission.enums import ProductPermissionsfrom ....product import modelsfrom ....product.search import prepare_product_search_vector_value+from ....product.tasks import update_products_discounted_prices_taskfrom ...app.dataloaders import get_app_promisefrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_38@@ -123,6 +124,9 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):])+ # Recalculate the "discounted price" for the related products+ update_products_discounted_prices_task.delay(product_pks)+return response@staticmethoddiff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.pyindex eb7ea4c554..0a52ab5ce8 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py@@ -557,6 +557,9 @@ class ProductVariantBulkUpdate(BaseMutation):channel=listing_data["channel"],variant=variant,price_amount=listing_data["price"],+ # set the discounted price the same as price for now, the discounted+ # value will be calculated asynchronously in the celery task+ discounted_price_amount=listing_data["price"],cost_price_amount=listing_data.get("cost_price"),currency=listing_data["channel"].currency_code,preorder_quantity_threshold=listing_data.get("preorder_threshold"),@@ -573,6 +576,9 @@ class ProductVariantBulkUpdate(BaseMutation):]if "price" in listing_data:listing.price_amount = listing_data["price"]+ # set the discounted price the same as price for now, the discounted+ # value will be calculated asynchronously in the celery task+ listing.discounted_price_amount = listing_data["price"]if "cost_price" in listing_data:listing.cost_price_amount = listing_data["cost_price"]listings_to_update.append(listing)diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.pyindex 3bfca22a22..84e70e624b 100644--- a/saleor/graphql/product/mutations/channels.py+++ b/saleor/graphql/product/mutations/channels.py@@ -350,6 +350,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):cls.update_channels(product, cleaned_input.get("update_channels", []))cls.remove_channels(product, cleaned_input.get("remove_channels", []))product = ProductModel.objects.prefetched_for_webhook().get(pk=product.pk)+ update_product_discounted_price_task.delay(product.id)manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.product_updated, product)@@ -518,6 +519,9 @@ class ProductVariantChannelListingUpdate(BaseMutation):defaults = {"currency": channel.currency_code}if "price" in channel_listing_data.keys():defaults["price_amount"] = channel_listing_data.get("price", None)+ # set the discounted price the same as price for now, the discounted+ # value will be calculated asynchronously in the celery task+ defaults["discounted_price_amount"] = defaults["price_amount"]if "cost_price" in channel_listing_data.keys():defaults["cost_price_amount"] = channel_listing_data.get("cost_price", Nonediff --git a/saleor/graphql/product/mutations/collection/collection_add_products.py b/saleor/graphql/product/mutations/collection/collection_add_products.pyindex dba72e226f..91ef4c9beb 100644--- a/saleor/graphql/product/mutations/collection/collection_add_products.py+++ b/saleor/graphql/product/mutations/collection/collection_add_products.py@@ -5,7 +5,7 @@ from .....core.tracing import traced_atomic_transactionfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....product.error_codes import CollectionErrorCode-from .....product.tasks import update_products_discounted_prices_of_catalogues_task+from .....product.tasks import update_products_discounted_prices_taskfrom .....product.utils import get_products_ids_without_variantsfrom ....channel import ChannelContextfrom ....core import ResolveInfo@@ -55,9 +55,7 @@ class CollectionAddProducts(BaseMutation):collection.products.add(*products)if collection.sale_set.exists():# Updated the db entries, recalculating discounts of affected products- update_products_discounted_prices_of_catalogues_task.delay(- product_ids=[pq.pk for pq in products]- )+ update_products_discounted_prices_task.delay([pq.pk for pq in products])for product in products:cls.call_event(manager.product_updated, product)diff --git a/saleor/graphql/product/mutations/collection/collection_delete.py b/saleor/graphql/product/mutations/collection/collection_delete.pyindex fe3518d378..613488b9e5 100644--- a/saleor/graphql/product/mutations/collection/collection_delete.py+++ b/saleor/graphql/product/mutations/collection/collection_delete.py@@ -2,6 +2,7 @@ import graphenefrom .....permission.enums import ProductPermissionsfrom .....product import models+from .....product.tasks import update_products_discounted_prices_taskfrom ....channel import ChannelContextfrom ....core import ResolveInfofrom ....core.mutations import ModelDeleteMutation@@ -32,6 +33,7 @@ class CollectionDelete(ModelDeleteMutation):single_object=False))+ collection_on_sale = instance.sale_set.exists()result = super().perform_mutation(_root, info, id=id)manager = get_plugin_manager_promise(info.context).get()@@ -39,6 +41,11 @@ class CollectionDelete(ModelDeleteMutation):for product in products:cls.call_event(manager.product_updated, product)+ if collection_on_sale:+ update_products_discounted_prices_task.delay(+ [product.id for product in products]+ )+return CollectionDelete(collection=ChannelContext(node=result.collection, channel_slug=None))diff --git a/saleor/graphql/product/mutations/collection/collection_remove_products.py b/saleor/graphql/product/mutations/collection/collection_remove_products.pyindex 0b64f00aba..8e31ceddb5 100644--- a/saleor/graphql/product/mutations/collection/collection_remove_products.py+++ b/saleor/graphql/product/mutations/collection/collection_remove_products.py@@ -2,7 +2,7 @@ import graphenefrom .....permission.enums import ProductPermissionsfrom .....product import models-from .....product.tasks import update_products_discounted_prices_of_catalogues_task+from .....product.tasks import update_products_discounted_prices_taskfrom ....channel import ChannelContextfrom ....core import ResolveInfofrom ....core.doc_category import DOC_CATEGORY_PRODUCTS@@ -51,9 +51,7 @@ class CollectionRemoveProducts(BaseMutation):cls.call_event(manager.product_updated, product)if collection.sale_set.exists():# Updated the db entries, recalculating discounts of affected products- update_products_discounted_prices_of_catalogues_task.delay(- product_ids=[p.pk for p in products]- )+ update_products_discounted_prices_task.delay([p.pk for p in products])return CollectionRemoveProducts(collection=ChannelContext(node=collection, channel_slug=None))diff --git a/saleor/graphql/product/mutations/product/product_create.py b/saleor/graphql/product/mutations/product/product_create.pyindex efbdc87688..92ec0b435f 100644--- a/saleor/graphql/product/mutations/product/product_create.py+++ b/saleor/graphql/product/mutations/product/product_create.py@@ -10,6 +10,7 @@ from .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....product.error_codes import ProductErrorCodefrom .....product.search import update_product_search_vector+from .....product.tasks import update_product_discounted_price_taskfrom ....attribute.types import AttributeValueInputfrom ....attribute.utils import AttributeAssignmentMixin, AttrValuesInputfrom ....channel import ChannelContext@@ -220,6 +221,7 @@ class ProductCreate(ModelMutation):def post_save_action(cls, info: ResolveInfo, instance, _cleaned_input):product = models.Product.objects.prefetched_for_webhook().get(pk=instance.pk)update_product_search_vector(instance)+ update_product_discounted_price_task.delay(instance.id)manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.product_created, product)diff --git a/saleor/graphql/product/mutations/product/product_update.py b/saleor/graphql/product/mutations/product/product_update.pyindex 167bed003c..c882445fad 100644--- a/saleor/graphql/product/mutations/product/product_update.py+++ b/saleor/graphql/product/mutations/product/product_update.py@@ -6,6 +6,7 @@ from .....attribute import models as attribute_modelsfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....product.search import update_product_search_vector+from .....product.tasks import update_product_discounted_price_taskfrom ....attribute.utils import AttributeAssignmentMixin, AttrValuesInputfrom ....core import ResolveInfofrom ....core.descriptions import ADDED_IN_310@@ -50,9 +51,11 @@ class ProductUpdate(ProductCreate, ModelWithExtRefMutation):return attributes@classmethod- def post_save_action(cls, info: ResolveInfo, instance, _cleaned_input):+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):product = models.Product.objects.prefetched_for_webhook().get(pk=instance.pk)update_product_search_vector(instance)+ if "category" in cleaned_input or "collections" in cleaned_input:+ update_product_discounted_price_task.delay(instance.id)manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.product_updated, product)diff --git a/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py b/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.pyindex 8d1b181572..31ee5087bd 100644--- a/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py+++ b/saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py@@ -58,8 +58,14 @@ mutation UpdateProductChannelListing("""+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")def test_product_channel_listing_update_as_staff_user(- staff_api_client, product, permission_manage_products, channel_USD, channel_PLN+ update_product_discounted_price_task_mock,+ staff_api_client,+ product,+ permission_manage_products,+ channel_USD,+ channel_PLN,):# givenpublication_date = datetime.date.today()@@ -129,6 +135,7 @@ def test_product_channel_listing_update_as_staff_user(product_data["channelListings"][1]["availableForPurchase"]== available_for_purchase_date.isoformat())+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)@patch("saleor.plugins.manager.PluginsManager.product_updated")diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex 9a32eef5b3..8c94ce2c70 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -74,7 +74,9 @@ PRODUCT_BULK_CREATE_MUTATION = """"""+@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")def test_product_bulk_create_with_base_data(+ update_products_discounted_price_task_mock,staff_api_client,product_type,category,@@ -141,6 +143,10 @@ def test_product_bulk_create_with_base_data(assert product.category == categoryassert product.product_type == product_type+ update_products_discounted_price_task_mock.assert_called_once()+ args = set(update_products_discounted_price_task_mock.call_args.args[0])+ assert args == {product.id for product in products}+@patch("saleor.plugins.manager.PluginsManager.product_created")def test_product_bulk_create_send_product_created_webhook(diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.pyindex 2ea67da239..3751286a42 100644--- a/saleor/graphql/product/tests/mutations/test_product_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_create.py@@ -86,11 +86,13 @@ CREATE_PRODUCT_MUTATION = """"""+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")@patch("saleor.plugins.manager.PluginsManager.product_updated")@patch("saleor.plugins.manager.PluginsManager.product_created")def test_create_product(created_webhook_mock,updated_webhook_mock,+ update_product_discounted_price_task_mock,staff_api_client,product_type,category,@@ -184,6 +186,7 @@ def test_create_product(created_webhook_mock.assert_called_once_with(product)updated_webhook_mock.assert_not_called()+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)def test_create_product_use_tax_class_from_product_type(@@ -861,7 +864,9 @@ def test_create_product_no_category_id(assert data["product"]["category"] is None+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")def test_create_product_with_negative_weight(+ update_product_discounted_price_task_mock,staff_api_client,product_type,category,@@ -890,6 +895,7 @@ def test_create_product_with_negative_weight(error = data["errors"][0]assert error["field"] == "weight"assert error["code"] == ProductErrorCode.INVALID.name+ update_product_discounted_price_task_mock.assert_not_called()def test_create_product_with_unicode_in_slug_and_name(diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.pyindex 8b5e9d5522..f0bc15eb8e 100644--- a/saleor/graphql/product/tests/mutations/test_product_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_update.py@@ -26,6 +26,9 @@ MUTATION_UPDATE_PRODUCT = """category {name}+ collections {+ name+ }ratingdescriptionchargeTaxes@@ -79,11 +82,13 @@ MUTATION_UPDATE_PRODUCT = """"""+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")@patch("saleor.plugins.manager.PluginsManager.product_updated")@patch("saleor.plugins.manager.PluginsManager.product_created")def test_update_product(created_webhook_mock,updated_webhook_mock,+ update_product_discounted_price_task_mock,staff_api_client,category,non_default_category,@@ -176,9 +181,12 @@ def test_update_product(updated_webhook_mock.assert_called_once_with(product)created_webhook_mock.assert_not_called()+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")def test_update_and_search_product_by_description(+ update_product_discounted_price_task_mock,staff_api_client,category,non_default_category,@@ -214,6 +222,70 @@ def test_update_and_search_product_by_description(assert data["product"]["name"] == product_nameassert data["product"]["slug"] == product_slugassert data["product"]["description"] == other_description_json+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)+++@patch("saleor.product.tasks.update_product_discounted_price_task.delay")+def test_update_product_only_description(+ update_product_discounted_price_task_mock,+ staff_api_client,+ product,+ other_description_json,+ permission_manage_products,+):+ query = MUTATION_UPDATE_PRODUCT+ other_description_json = json.dumps(other_description_json)++ product_id = graphene.Node.to_global_id("Product", product.pk)++ variables = {+ "productId": product_id,+ "input": {+ "description": other_description_json,+ },+ }++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ assert not data["errors"]+ assert data["product"]["description"] == other_description_json+ update_product_discounted_price_task_mock.assert_not_called()+++@patch("saleor.product.tasks.update_product_discounted_price_task.delay")+def test_update_product_only_collections(+ update_product_discounted_price_task_mock,+ staff_api_client,+ product,+ collection,+ other_description_json,+ permission_manage_products,+):+ query = MUTATION_UPDATE_PRODUCT+ other_description_json = json.dumps(other_description_json)++ product_id = graphene.Node.to_global_id("Product", product.pk)+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)++ variables = {+ "productId": product_id,+ "input": {+ "collections": [collection_id],+ },+ }++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["productUpdate"]+ assert not data["errors"]+ assert len(data["product"]["collections"]) == 1+ assert data["product"]["collections"][0]["name"] == collection.name+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)def test_update_product_clear_description_plaintext_when_description_is_none(diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.pyindex 673ac7cd1d..d9ddb81000 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py@@ -10,7 +10,11 @@ from freezegun import freeze_timefrom .....attribute import AttributeInputTypefrom .....product.error_codes import ProductVariantBulkErrorCode-from .....product.models import ProductChannelListing, ProductVariant+from .....product.models import (+ ProductChannelListing,+ ProductVariant,+ ProductVariantChannelListing,+)from .....tests.utils import dummy_editorjs, flush_post_commit_hooksfrom ....core.enums import ErrorPolicyEnumfrom ....tests.utils import get_graphql_content@@ -91,9 +95,11 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """"""+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")@patch("saleor.plugins.manager.PluginsManager.product_variant_created")def test_product_variant_bulk_create_by_name(product_variant_created_webhook_mock,+ update_product_discounted_price_task_mock,staff_api_client,product,size_attribute,@@ -145,11 +151,14 @@ def test_product_variant_bulk_create_by_name(product.refresh_from_db()assert product.default_variant == product_variantassert product_variant_created_webhook_mock.call_count == data["count"]+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")@patch("saleor.plugins.manager.PluginsManager.product_variant_created")def test_product_variant_bulk_create_by_attribute_id(product_variant_created_webhook_mock,+ update_product_discounted_price_task_mock,staff_api_client,product,size_attribute,@@ -192,6 +201,7 @@ def test_product_variant_bulk_create_by_attribute_id(product.refresh_from_db()assert product.default_variant == product_variantassert product_variant_created_webhook_mock.call_count == data["count"]+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)def test_product_variant_bulk_create_with_swatch_attribute(@@ -1180,6 +1190,15 @@ def test_product_variant_bulk_create_channel_listings_input(])+ # ensure all variants channel listings has discounted_price_amount set+ assert all(+ list(+ ProductVariantChannelListing.objects.values_list(+ "discounted_price_amount", flat=True+ )+ )+ )+def test_product_variant_bulk_create_preorder_channel_listings_input(staff_api_client,@@ -1791,8 +1810,13 @@ def test_product_variant_bulk_create_without_sku(assert ProductVariant.objects.filter(sku__isnull=True).count() == 2+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")def test_product_variant_bulk_create_many_errors(- staff_api_client, product, size_attribute, permission_manage_products+ update_product_discounted_price_task_mock,+ staff_api_client,+ product,+ size_attribute,+ permission_manage_products,):# givenproduct_variant_count = ProductVariant.objects.count()@@ -1852,6 +1876,7 @@ def test_product_variant_bulk_create_many_errors("channels": None,}assert product_variant_count == ProductVariant.objects.count()+ update_product_discounted_price_task_mock.assert_not_called()def test_product_variant_bulk_create_many_errors_with_ignore_failed(diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.pyindex ce7b84598d..c763f493c6 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py@@ -67,9 +67,11 @@ PRODUCT_VARIANT_BULK_UPDATE_MUTATION = """"""+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")def test_product_variant_bulk_update(product_variant_created_webhook_mock,+ update_product_discounted_price_task_mock,staff_api_client,product_with_single_variant,size_attribute,@@ -113,9 +115,14 @@ def test_product_variant_bulk_update(assert product_with_single_variant.variants.count() == 1assert old_name != new_nameassert product_variant_created_webhook_mock.call_count == data["count"]+ update_product_discounted_price_task_mock.assert_called_once_with(+ product_with_single_variant.id+ )+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")def test_product_variant_bulk_update_stocks(+ update_product_discounted_price_task_mock,staff_api_client,variant_with_many_stocks,warehouse,@@ -175,6 +182,9 @@ def test_product_variant_bulk_update_stocks(assert stock_to_update.quantity == new_quantityassert variant.stocks.count() == 3assert variant.stocks.last().quantity == new_stock_quantity+ update_product_discounted_price_task_mock.assert_called_once_with(+ variant.product_id+ )def test_product_variant_bulk_update_and_remove_stock(@@ -218,7 +228,9 @@ def test_product_variant_bulk_update_and_remove_stock(assert variant.stocks.count() == 1+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")def test_product_variant_bulk_update_and_remove_stock_when_stock_not_exists(+ update_product_discounted_price_task_mock,staff_api_client,variant_with_many_stocks,warehouse,@@ -256,6 +268,7 @@ def test_product_variant_bulk_update_and_remove_stock_when_stock_not_exists(assert variant.stocks.count() == 2error = data["results"][0]["errors"][0]assert error["code"] == ProductVariantBulkErrorCode.NOT_FOUND.name+ update_product_discounted_price_task_mock.assert_not_called()def test_product_variant_bulk_update_stocks_with_invalid_warehouse(@@ -370,10 +383,18 @@ def test_product_variant_bulk_update_channel_listings_input(assert (new_variant_channel_listing.price_amount == not_existing_variant_listing_price)+ assert (+ new_variant_channel_listing.discounted_price_amount+ == not_existing_variant_listing_price+ )assert new_variant_channel_listing.channel == channel_PLNassert (existing_variant_listing.price_amount == new_price_for_existing_variant_listing)+ assert (+ existing_variant_listing.discounted_price_amount+ == new_price_for_existing_variant_listing+ )def test_product_variant_bulk_update_and_remove_channel_listings(diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.pyindex bca9936320..7000410995 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py@@ -76,11 +76,13 @@ CREATE_VARIANT_MUTATION = """"""+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")@patch("saleor.plugins.manager.PluginsManager.product_variant_created")@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")def test_create_variant_with_name(updated_webhook_mock,created_webhook_mock,+ update_product_discounted_price_task_mock,staff_api_client,product,product_type,@@ -149,6 +151,7 @@ def test_create_variant_with_name(created_webhook_mock.assert_called_once_with(product.variants.last())updated_webhook_mock.assert_not_called()+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)@patch("saleor.plugins.manager.PluginsManager.product_variant_created")diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_delete.py b/saleor/graphql/product/tests/mutations/test_product_variant_delete.pyindex 949c44acc5..2394f6fd9f 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_delete.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_delete.py@@ -22,11 +22,13 @@ DELETE_VARIANT_BY_SKU_MUTATION = """"""+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")@patch("saleor.order.tasks.recalculate_orders_task.delay")def test_delete_variant_by_sku(mocked_recalculate_orders_task,product_variant_deleted_webhook_mock,+ update_product_discounted_price_task_mock,staff_api_client,product,permission_manage_products,@@ -52,6 +54,7 @@ def test_delete_variant_by_sku(with pytest.raises(variant._meta.model.DoesNotExist):variant.refresh_from_db()mocked_recalculate_orders_task.assert_not_called()+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)DELETE_VARIANT_MUTATION = """@@ -66,11 +69,13 @@ DELETE_VARIANT_MUTATION = """"""+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")@patch("saleor.order.tasks.recalculate_orders_task.delay")def test_delete_variant(mocked_recalculate_orders_task,product_variant_deleted_webhook_mock,+ update_product_discounted_price_task_mock,staff_api_client,product,permission_manage_products,@@ -92,6 +97,7 @@ def test_delete_variant(with pytest.raises(variant._meta.model.DoesNotExist):variant.refresh_from_db()mocked_recalculate_orders_task.assert_not_called()+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)def test_delete_variant_remove_checkout_lines(diff --git a/saleor/graphql/product/tests/queries/test_products_query.py b/saleor/graphql/product/tests/queries/test_products_query.pyindex 79ea352bcc..a97056b811 100644--- a/saleor/graphql/product/tests/queries/test_products_query.py+++ b/saleor/graphql/product/tests/queries/test_products_query.py@@ -578,6 +578,7 @@ def test_sort_products(user_api_client, product, channel_USD):variant=variant,channel=channel_USD,price_amount=Decimal(20),+ discounted_price_amount=Decimal(20),cost_price_amount=Decimal(2),currency=channel_USD.currency_code,)@@ -688,6 +689,7 @@ def test_sort_products_by_price_as_staff(variant=variant,channel=channel_USD,price_amount=Decimal(20),+ discounted_price_amount=Decimal(20),cost_price_amount=Decimal(2),currency=channel_USD.currency_code,)diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.pyindex 10eea43e75..5d6aad5291 100644--- a/saleor/graphql/product/tests/test_bulk_delete.py+++ b/saleor/graphql/product/tests/test_bulk_delete.py@@ -62,24 +62,44 @@ MUTATION_CATEGORY_BULK_DELETE = """"""-def test_delete_categories(staff_api_client, category_list, permission_manage_products):+@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")+def test_delete_categories(+ update_products_discounted_price_task_mock,+ staff_api_client,+ category_list,+ product_list,+ permission_manage_products,+):+ # given+ for product, category in zip(product_list, category_list):+ product.category = category++ Product.objects.bulk_update(product_list, ["category"])+variables = {"ids": [graphene.Node.to_global_id("Category", category.id)for category in category_list]}++ # whenresponse = staff_api_client.post_graphql(MUTATION_CATEGORY_BULK_DELETE,variables,permissions=[permission_manage_products],)++ # thencontent = get_graphql_content(response)assert content["data"]["categoryBulkDelete"]["count"] == 3assert not Category.objects.filter(id__in=[category.id for category in category_list]).exists()+ update_products_discounted_price_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_price_task_mock.call_args+ assert set(kwargs["product_ids"]) == {product.id for product in product_list}@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@@ -283,26 +303,42 @@ MUTATION_COLLECTION_BULK_DELETE = """"""+@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")def test_delete_collections(- staff_api_client, collection_list, permission_manage_products+ update_products_discounted_price_task_mock,+ staff_api_client,+ collection_list,+ product_list,+ permission_manage_products,):+ # givenquery = MUTATION_COLLECTION_BULK_DELETE+ for product, collection in zip(product_list, collection_list):+ collection.products.add(product)+variables = {"ids": [graphene.Node.to_global_id("Collection", collection.id)for collection in collection_list]}++ # whenresponse = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products])++ # thencontent = get_graphql_content(response)assert content["data"]["collectionBulkDelete"]["count"] == 3assert not Collection.objects.filter(id__in=[collection.id for collection in collection_list]).exists()+ update_products_discounted_price_task_mock.assert_called_once()+ args = set(update_products_discounted_price_task_mock.call_args.args[0])+ assert args == {product.id for product in product_list}def test_delete_collections_with_images(@@ -929,6 +965,49 @@ def test_delete_product_variants_by_sku(mocked_recalculate_orders_task.assert_not_called()+@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")+@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")+@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_product_variants_by_sku_task_for_recalculate_product_prices_called(+ mocked_recalculate_orders_task,+ product_variant_deleted_webhook_mock,+ update_products_discounted_price_task_mock,+ staff_api_client,+ product_list,+ permission_manage_products,+):+ # given+ variants = [product.variants.first() for product in product_list]+ assert ProductVariantChannelListing.objects.filter(+ variant_id__in=[variant.id for variant in variants]+ ).exists()++ variables = {"skus": [variant.sku for variant in variants]}++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_DELETE_BY_SKU_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()++ # then+ assert content["data"]["productVariantBulkDelete"]["count"] == len(variants)+ assert not ProductVariant.objects.filter(+ id__in=[variant.id for variant in variants]+ ).exists()+ assert (+ product_variant_deleted_webhook_mock.call_count+ == content["data"]["productVariantBulkDelete"]["count"]+ )+ mocked_recalculate_orders_task.assert_not_called()+ update_products_discounted_price_task_mock.assert_called_once()+ args = set(update_products_discounted_price_task_mock.call_args.args[0])+ assert args == {product.id for product in product_list}++PRODUCT_VARIANT_BULK_DELETE_MUTATION = """mutation productVariantBulkDelete($ids: [ID!]!) {productVariantBulkDelete(ids: $ids) {@@ -986,8 +1065,57 @@ def test_delete_product_variants(mocked_recalculate_orders_task.assert_not_called()+@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")+@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")+@patch("saleor.order.tasks.recalculate_orders_task.delay")+def test_delete_product_variants_task_for_recalculate_product_prices_called(+ mocked_recalculate_orders_task,+ product_variant_deleted_webhook_mock,+ update_products_discounted_price_task_mock,+ staff_api_client,+ product_list,+ permission_manage_products,+):+ query = PRODUCT_VARIANT_BULK_DELETE_MUTATION++ variants = [product.variants.first() for product in product_list]+ assert ProductVariantChannelListing.objects.filter(+ variant_id__in=[variant.id for variant in variants]+ ).exists()++ variables = {+ "ids": [+ graphene.Node.to_global_id("ProductVariant", variant.id)+ for variant in variants+ ]+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ flush_post_commit_hooks()++ assert content["data"]["productVariantBulkDelete"]["count"] == len(variants)+ assert not ProductVariant.objects.filter(+ id__in=[variant.id for variant in variants]+ ).exists()+ assert (+ product_variant_deleted_webhook_mock.call_count+ == content["data"]["productVariantBulkDelete"]["count"]+ )+ mocked_recalculate_orders_task.assert_not_called()+ update_products_discounted_price_task_mock.assert_called_once()+ args = set(update_products_discounted_price_task_mock.call_args.args[0])+ assert args == {product.id for product in product_list}+++@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")def test_delete_product_variants_invalid_object_typed_of_given_ids(- staff_api_client, product_variant_list, permission_manage_products, staff_user+ update_products_discounted_price_task_mock,+ staff_api_client,+ product_variant_list,+ permission_manage_products,+ staff_user,):query = PRODUCT_VARIANT_BULK_DELETE_MUTATIONstaff_user.user_permissions.add(permission_manage_products)@@ -1006,6 +1134,7 @@ def test_delete_product_variants_invalid_object_typed_of_given_ids(assert errors[0]["code"] == ProductErrorCode.GRAPHQL_ERROR.nameassert errors[0]["field"] == "ids"assert data["count"] == 0+ update_products_discounted_price_task_mock.assert_not_called()def test_delete_product_variants_removes_checkout_lines(diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.pyindex e2b2159ec2..f195eed98c 100644--- a/saleor/graphql/product/tests/test_category.py+++ b/saleor/graphql/product/tests/test_category.py@@ -1120,11 +1120,14 @@ MUTATION_CATEGORY_DELETE = """"""+@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")@patch("saleor.core.tasks.delete_from_storage_task.delay")def test_category_delete_mutation(delete_from_storage_task_mock,+ update_products_discounted_price_task_mock,staff_api_client,category,+ product_list,media_root,permission_manage_products,):@@ -1134,6 +1137,8 @@ def test_category_delete_mutation(Thumbnail.objects.create(category=category, size=128, image=thumbnail_mock)Thumbnail.objects.create(category=category, size=200, image=thumbnail_mock)+ category.products.add(*product_list)+category_id = category.idvariables = {"id": graphene.Node.to_global_id("Category", category_id)}@@ -1153,6 +1158,10 @@ def test_category_delete_mutation(assert not Thumbnail.objects.filter(category_id=category_id)assert delete_from_storage_task_mock.call_count == 2+ update_products_discounted_price_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_price_task_mock.call_args+ assert set(kwargs["product_ids"]) == {product.id for product in product_list}+@freeze_time("2022-05-12 12:00:00")@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.pyindex b66e1da75f..983e18abce 100644--- a/saleor/graphql/product/tests/test_collection.py+++ b/saleor/graphql/product/tests/test_collection.py@@ -1054,15 +1054,19 @@ DELETE_COLLECTION_MUTATION = """"""+@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")@patch("saleor.plugins.manager.PluginsManager.collection_deleted")def test_delete_collection(deleted_webhook_mock,+ update_products_discounted_prices_task_mock,staff_api_client,collection,+ product_list,permission_manage_products,):# givenquery = DELETE_COLLECTION_MUTATION+ collection.products.set(product_list)collection_id = to_global_id("Collection", collection.id)variables = {"id": collection_id}@@ -1079,6 +1083,44 @@ def test_delete_collection(collection.refresh_from_db()deleted_webhook_mock.assert_called_once()+ update_products_discounted_prices_task_mock.assert_not_called()+++@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")+@patch("saleor.plugins.manager.PluginsManager.collection_deleted")+def test_delete_collection_on_sale(+ deleted_webhook_mock,+ update_products_discounted_prices_task_mock,+ sale,+ product_list,+ staff_api_client,+ collection,+ permission_manage_products,+):+ # given+ query = DELETE_COLLECTION_MUTATION+ collection.products.set(product_list)+ sale.collections.add(collection)++ collection_id = to_global_id("Collection", collection.id)+ variables = {"id": collection_id}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["collectionDelete"]["collection"]+ assert data["name"] == collection.name+ with pytest.raises(collection._meta.model.DoesNotExist):+ collection.refresh_from_db()++ deleted_webhook_mock.assert_called_once()+ update_products_discounted_prices_task_mock.assert_called_once()+ args = set(update_products_discounted_prices_task_mock.call_args.args[0])+ assert args == {product.id for product in product_list}@patch("saleor.core.tasks.delete_from_storage_task.delay")@@ -1124,15 +1166,7 @@ def test_delete_collection_trigger_product_updated_webhook(product_list,permission_manage_products,):- query = """- mutation deleteCollection($id: ID!) {- collectionDelete(id: $id) {- collection {- name- }- }- }- """+ query = DELETE_COLLECTION_MUTATIONcollection.products.add(*product_list)collection_id = to_global_id("Collection", collection.id)variables = {"id": collection_id}@@ -1147,31 +1181,84 @@ def test_delete_collection_trigger_product_updated_webhook(assert len(product_list) == product_updated_mock.call_count-def test_add_products_to_collection(- staff_api_client, collection, product_list, permission_manage_products-):- query = """- mutation collectionAddProducts(- $id: ID!, $products: [ID!]!) {- collectionAddProducts(collectionId: $id, products: $products) {- collection {- products {- totalCount- }+COLLECTION_ADD_PRODUCTS_MUTATION = """+ mutation collectionAddProducts(+ $id: ID!, $products: [ID!]!) {+ collectionAddProducts(collectionId: $id, products: $products) {+ collection {+ products {+ totalCount}}+ errors {+ field+ message+ code+ }}- """+ }+"""+++@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")+def test_add_products_to_collection(+ update_products_discounted_prices_task_mock,+ staff_api_client,+ collection,+ product_list,+ permission_manage_products,+):+ # given+ query = COLLECTION_ADD_PRODUCTS_MUTATION++ collection_id = to_global_id("Collection", collection.id)+ product_ids = [to_global_id("Product", product.pk) for product in product_list]+ products_before = collection.products.count()+ variables = {"id": collection_id, "products": product_ids}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["collectionAddProducts"]["collection"]+ assert data["products"]["totalCount"] == products_before + len(product_ids)+ update_products_discounted_prices_task_mock.assert_not_called()+++@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")+def test_add_products_to_collection_with_sale(+ update_products_discounted_prices_task_mock,+ sale,+ staff_api_client,+ collection,+ product_list,+ permission_manage_products,+):+ # given+ query = COLLECTION_ADD_PRODUCTS_MUTATION++ sale.collections.add(collection)+collection_id = to_global_id("Collection", collection.id)product_ids = [to_global_id("Product", product.pk) for product in product_list]products_before = collection.products.count()variables = {"id": collection_id, "products": product_ids}++ # whenresponse = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products])++ # thencontent = get_graphql_content(response)data = content["data"]["collectionAddProducts"]["collection"]assert data["products"]["totalCount"] == products_before + len(product_ids)+ update_products_discounted_prices_task_mock.assert_called_once()+ args = set(update_products_discounted_prices_task_mock.call_args.args[0])+ assert args == {product.id for product in product_list}@patch("saleor.plugins.manager.PluginsManager.product_updated")@@ -1182,18 +1269,7 @@ def test_add_products_to_collection_trigger_product_updated_webhook(product_list,permission_manage_products,):- query = """- mutation collectionAddProducts(- $id: ID!, $products: [ID!]!) {- collectionAddProducts(collectionId: $id, products: $products) {- collection {- products {- totalCount- }- }- }- }- """+ query = COLLECTION_ADD_PRODUCTS_MUTATIONcollection_id = to_global_id("Collection", collection.id)product_ids = [to_global_id("Product", product.pk) for product in product_list]products_before = collection.products.count()@@ -1207,26 +1283,26 @@ def test_add_products_to_collection_trigger_product_updated_webhook(assert len(product_list) == product_updated_mock.call_count+def test_add_products_to_collection_on_sale_trigger_discounted_price_recalculation(+ staff_api_client, collection, product_list, permission_manage_products+):+ query = COLLECTION_ADD_PRODUCTS_MUTATION+ collection_id = to_global_id("Collection", collection.id)+ product_ids = [to_global_id("Product", product.pk) for product in product_list]+ products_before = collection.products.count()+ variables = {"id": collection_id, "products": product_ids}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ data = content["data"]["collectionAddProducts"]["collection"]+ assert data["products"]["totalCount"] == products_before + len(product_ids)++def test_add_products_to_collection_with_product_without_variants(staff_api_client, collection, product_list, permission_manage_products):- query = """- mutation collectionAddProducts(- $id: ID!, $products: [ID!]!) {- collectionAddProducts(collectionId: $id, products: $products) {- collection {- products {- totalCount- }- }- errors {- field- message- code- }- }- }- """+ query = COLLECTION_ADD_PRODUCTS_MUTATIONproduct_list[0].variants.all().delete()collection_id = to_global_id("Collection", collection.id)product_ids = [to_global_id("Product", product.pk) for product in product_list]@@ -1243,32 +1319,78 @@ def test_add_products_to_collection_with_product_without_variants(assert error["message"] == "Cannot manage products without variants."-def test_remove_products_from_collection(- staff_api_client, collection, product_list, permission_manage_products-):- query = """- mutation collectionRemoveProducts(- $id: ID!, $products: [ID!]!) {- collectionRemoveProducts(collectionId: $id, products: $products) {- collection {- products {- totalCount- }+COLLECTION_REMOVE_PRODUCTS_MUTATION = """+ mutation collectionRemoveProducts(+ $id: ID!, $products: [ID!]!) {+ collectionRemoveProducts(collectionId: $id, products: $products) {+ collection {+ products {+ totalCount}}}- """+ }+"""+++@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")+def test_remove_products_from_collection(+ update_products_discounted_prices_task_mock,+ staff_api_client,+ collection,+ product_list,+ permission_manage_products,+):+ # given+ query = COLLECTION_REMOVE_PRODUCTS_MUTATION+ collection.products.add(*product_list)+ collection_id = to_global_id("Collection", collection.id)+ product_ids = [to_global_id("Product", product.pk) for product in product_list]+ products_before = collection.products.count()+ variables = {"id": collection_id, "products": product_ids}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["collectionRemoveProducts"]["collection"]+ assert data["products"]["totalCount"] == products_before - len(product_ids)+ update_products_discounted_prices_task_mock.assert_not_called()+++@patch("saleor.product.tasks.update_products_discounted_prices_task.delay")+def test_remove_products_from_collection_on_sale(+ update_products_discounted_prices_task_mock,+ sale,+ staff_api_client,+ collection,+ product_list,+ permission_manage_products,+):+ # given+ query = COLLECTION_REMOVE_PRODUCTS_MUTATION+ sale.collections.add(collection)collection.products.add(*product_list)collection_id = to_global_id("Collection", collection.id)product_ids = [to_global_id("Product", product.pk) for product in product_list]products_before = collection.products.count()variables = {"id": collection_id, "products": product_ids}++ # whenresponse = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products])++ # thencontent = get_graphql_content(response)data = content["data"]["collectionRemoveProducts"]["collection"]assert data["products"]["totalCount"] == products_before - len(product_ids)+ update_products_discounted_prices_task_mock.assert_called_once()+ args = set(update_products_discounted_prices_task_mock.call_args.args[0])+ assert args == {product.id for product in product_list}@patch("saleor.plugins.manager.PluginsManager.product_updated")@@ -1279,18 +1401,7 @@ def test_remove_products_from_collection_trigger_product_updated_webhook(product_list,permission_manage_products,):- query = """- mutation collectionRemoveProducts(- $id: ID!, $products: [ID!]!) {- collectionRemoveProducts(collectionId: $id, products: $products) {- collection {- products {- totalCount- }- }- }- }- """+ query = COLLECTION_REMOVE_PRODUCTS_MUTATIONcollection.products.add(*product_list)collection_id = to_global_id("Collection", collection.id)product_ids = [to_global_id("Product", product.pk) for product in product_list]diff --git a/saleor/graphql/product/tests/test_product_channel_listings_queries.py b/saleor/graphql/product/tests/test_product_channel_listings_queries.pyindex 985140dfa2..e51f3e3e27 100644--- a/saleor/graphql/product/tests/test_product_channel_listings_queries.py+++ b/saleor/graphql/product/tests/test_product_channel_listings_queries.py@@ -88,6 +88,46 @@ def test_product_channel_listing_pricing_field()+def test_product_channel_listing_pricing_no_prices(+ address_usa,+ staff_api_client,+ permission_manage_products,+ channel_USD,+ product,+):+ # given++ # Changing the address of a warehouse used by the product to address_usa, so that+ # we can query pricing in two countries: US and PL.+ warehouse = Warehouse.objects.first()+ warehouse.address = address_usa+ warehouse.save()++ country = "PL"+ variables = {+ "id": graphene.Node.to_global_id("Product", product.pk),+ "channel": channel_USD.slug,+ "address": {"country": country},+ }+ product.channel_listings.exclude(channel__slug=channel_USD.slug).delete()+ product.variants.first().channel_listings.update(price_amount=None)++ # when+ response = staff_api_client.post_graphql(+ QUERY_PRICING_ON_PRODUCT_CHANNEL_LISTING,+ variables=variables,+ permissions=(permission_manage_products,),+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ product_data = content["data"]["product"]+ product_channel_listing_data = product_data["channelListings"][0]+ assert product_channel_listing_data["pricing"] is None+ assert product_data["pricing"] is None++QUERY_PRICING_ON_PRODUCT_CHANNEL_LISTING_NO_ADDRESS = """fragment Pricing on ProductPricingInfo {priceRangeUndiscounted {diff --git a/saleor/graphql/product/tests/test_product_discounted_price.py b/saleor/graphql/product/tests/test_product_discounted_price.pyindex 8236881f1a..2043bcacb4 100644--- a/saleor/graphql/product/tests/test_product_discounted_price.py+++ b/saleor/graphql/product/tests/test_product_discounted_price.py@@ -93,10 +93,10 @@ def test_category_delete_updates_discounted_price(@patch("saleor.graphql.product.mutations.collection.collection_add_products"- ".update_products_discounted_prices_of_catalogues_task"+ ".update_products_discounted_prices_task.delay")def test_collection_add_products_updates_discounted_price(- mock_update_products_discounted_prices_of_catalogues,+ mock_update_products_discounted_prices_task,staff_api_client,sale,collection,@@ -130,17 +130,17 @@ def test_collection_add_products_updates_discounted_price(data = content["data"]["collectionAddProducts"]assert data["errors"] == []- mock_update_products_discounted_prices_of_catalogues.delay.assert_called_once_with(- product_ids=[p.pk for p in product_list]- )+ mock_update_products_discounted_prices_task.assert_called_once()+ args = set(mock_update_products_discounted_prices_task.call_args.args[0])+ assert args == {product.id for product in product_list}@patch("saleor.graphql.product.mutations.collection.collection_remove_products"- ".update_products_discounted_prices_of_catalogues_task"+ ".update_products_discounted_prices_task.delay")def test_collection_remove_products_updates_discounted_price(- mock_update_products_discounted_prices_of_catalogues,+ mock_update_products_discounted_prices_task,staff_api_client,sale,collection,@@ -174,15 +174,15 @@ def test_collection_remove_products_updates_discounted_price(data = content["data"]["collectionRemoveProducts"]assert data["errors"] == []- mock_update_products_discounted_prices_of_catalogues.delay.assert_called_once_with(- product_ids=[p.pk for p in product_list]- )+ mock_update_products_discounted_prices_task.assert_called_once()+ args = set(mock_update_products_discounted_prices_task.call_args.args[0])+ assert args == {product.id for product in product_list}@freeze_time("2010-05-31 12:00:01")@patch("saleor.graphql.discount.mutations.sale_create"- ".update_products_discounted_prices_of_discount_task"+ ".update_products_discounted_prices_of_sale_task")def test_sale_create_updates_products_discounted_prices(mock_update_products_discounted_prices_of_catalogues,@@ -234,15 +234,16 @@ def test_sale_create_updates_products_discounted_prices(@patch(- "saleor.graphql.discount.mutations.sale_create"- ".update_products_discounted_prices_of_discount_task"+ "saleor.graphql.discount.mutations.sale_update"+ ".update_products_discounted_prices_of_catalogues_task.delay")def test_sale_update_updates_products_discounted_prices(- mock_update_products_discounted_prices_of_discount,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,permission_manage_discounts,):+ # givenquery = """mutation SaleUpdate($id: ID!, $value: PositiveDecimal) {saleUpdate(id: $id, input: {value: $value}) {@@ -257,25 +258,37 @@ def test_sale_update_updates_products_discounted_prices(}"""variables = {"id": to_global_id("Sale", sale.pk), "value": "99"}++ category_pks = set(sale.categories.values_list("id", flat=True))+ collection_pks = set(sale.collections.values_list("id", flat=True))+ product_pks = set(sale.products.values_list("id", flat=True))+ variant_pks = set(sale.variants.values_list("id", flat=True))++ # whenresponse = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_discounts])++ # thenassert response.status_code == 200content = get_graphql_content(response)assert content["data"]["saleUpdate"]["errors"] == []- mock_update_products_discounted_prices_of_discount.delay.assert_called_once_with(- sale.pk- )+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_pks+ assert set(kwargs["collection_ids"]) == collection_pks+ assert set(kwargs["product_ids"]) == product_pks+ assert set(kwargs["variant_ids"]) == variant_pks@patch(- "saleor.graphql.discount.mutations.sale_create"- ".update_products_discounted_prices_of_discount_task"+ "saleor.graphql.discount.mutations.sale_delete"+ ".update_products_discounted_prices_of_catalogues_task.delay")def test_sale_delete_updates_products_discounted_prices(- mock_update_products_discounted_prices_of_discount,+ update_products_discounted_prices_of_catalogues_task_mock,staff_api_client,sale,permission_manage_discounts,@@ -294,6 +307,11 @@ def test_sale_delete_updates_products_discounted_prices(}"""variables = {"id": to_global_id("Sale", sale.pk)}+ category_ids = set(sale.categories.values_list("id", flat=True))+ collection_ids = set(sale.collections.values_list("id", flat=True))+ product_ids = set(sale.products.values_list("id", flat=True))+ variant_ids = set(sale.variants.values_list("id", flat=True))+response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_discounts])@@ -302,9 +320,12 @@ def test_sale_delete_updates_products_discounted_prices(content = get_graphql_content(response)assert content["data"]["saleDelete"]["errors"] == []- mock_update_products_discounted_prices_of_discount.delay.assert_called_once_with(- sale.pk- )+ update_products_discounted_prices_of_catalogues_task_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_of_catalogues_task_mock.call_args+ assert set(kwargs["category_ids"]) == category_ids+ assert set(kwargs["collection_ids"]) == collection_ids+ assert set(kwargs["product_ids"]) == product_ids+ assert set(kwargs["variant_ids"]) == variant_ids@patch(diff --git a/saleor/graphql/product/tests/test_variant_channel_listing_update.py b/saleor/graphql/product/tests/test_variant_channel_listing_update.pyindex e293d11d4c..27f7f4968e 100644--- a/saleor/graphql/product/tests/test_variant_channel_listing_update.py+++ b/saleor/graphql/product/tests/test_variant_channel_listing_update.py@@ -182,11 +182,17 @@ def test_variant_channel_listing_update_with_too_many_decimal_places_in_price(assert error["code"] == ProductErrorCode.INVALID.name+@patch("saleor.product.tasks.update_product_discounted_price_task.delay")def test_variant_channel_listing_update_as_staff_user(- staff_api_client, product, permission_manage_products, channel_USD, channel_PLN+ update_product_discounted_price_task_mock,+ staff_api_client,+ product,+ permission_manage_products,+ channel_USD,+ channel_PLN,):# given- ProductChannelListing.objects.create(+ pln_channel_listing = ProductChannelListing.objects.create(product=product,channel=channel_PLN,is_published=True,@@ -240,6 +246,11 @@ def test_variant_channel_listing_update_as_staff_user(assert channel_pln_data["price"]["amount"] == second_priceassert channel_pln_data["costPrice"]["amount"] == second_priceassert channel_pln_data["channel"]["slug"] == channel_PLN.slug+ usd_channel_listing = variant.channel_listings.get(channel=channel_USD)+ pln_channel_listing = variant.channel_listings.get(channel=channel_PLN)+ assert usd_channel_listing.discounted_price_amount == price+ assert pln_channel_listing.discounted_price_amount == second_price+ update_product_discounted_price_task_mock.assert_called_once_with(product.id)def test_variant_channel_listing_update_by_sku(diff --git a/saleor/graphql/product/tests/test_variant_pricing.py b/saleor/graphql/product/tests/test_variant_pricing.pyindex 3919c45e02..c52d1c35ed 100644--- a/saleor/graphql/product/tests/test_variant_pricing.py+++ b/saleor/graphql/product/tests/test_variant_pricing.py@@ -56,12 +56,20 @@ query ($channel: String, $address: AddressInput) {def test_get_variant_pricing_on_sale(api_client, sale, product, channel_USD):- price = product.variants.first().channel_listings.get().price+ # given+ variant_listing = product.variants.first().channel_listings.get()+ price = variant_listing.pricesale_discounted_value = sale.channel_listings.get().discount_valuediscounted_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"}}++ # whenresponse = api_client.post_graphql(QUERY_GET_VARIANT_PRICING, variables)++ # thencontent = get_graphql_content(response)pricing = content["data"]["products"]["edges"][0]["node"]["variants"][0]["pricing"]@@ -133,13 +141,8 @@ def test_variant_pricing(variant_channel_listing = variant.channel_listings.get()pricing = get_variant_availability(- variant=variant,variant_channel_listing=variant_channel_listing,- product=product,product_channel_listing=product_channel_listing,- collections=[],- discounts=[],- channel=channel_USD,tax_rate=tax_rate,tax_calculation_strategy=tc.tax_calculation_strategy,prices_entered_with_tax=tc.prices_entered_with_tax,@@ -155,13 +158,8 @@ def test_variant_pricing(settings.OPENEXCHANGERATES_API_KEY = "fake-key"pricing = get_variant_availability(- variant=variant,variant_channel_listing=variant_channel_listing,- product=product,product_channel_listing=product_channel_listing,- collections=[],- discounts=[],- channel=channel_USD,local_currency="PLN",tax_rate=tax_rate,tax_calculation_strategy=tc.tax_calculation_strategy,@@ -170,13 +168,8 @@ def test_variant_pricing(assert pricing.price_local_currency.currency == "PLN" # type: ignorepricing = get_variant_availability(- variant=variant,variant_channel_listing=variant_channel_listing,- product=product,product_channel_listing=product_channel_listing,- collections=[],- discounts=[],- channel=channel_USD,tax_rate=tax_rate,tax_calculation_strategy=tc.tax_calculation_strategy,prices_entered_with_tax=tc.prices_entered_with_tax,@@ -186,6 +179,43 @@ def test_variant_pricing(assert pricing.price_undiscounted.tax.amount+def test_variant_pricing_no_prices(variant, channel_USD):+ # given+ product = variant.product+ tax_class = product.tax_class or product.product_type.tax_class++ tc = channel_USD.tax_configuration+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES+ tc.charge_taxes = True+ tc.prices_entered_with_tax = False+ tc.save()++ tax_rate = Decimal(TAX_RATE_PL)+ country = "PL"+ tax_class.country_rates.update_or_create(rate=tax_rate, country=country)++ product_channel_listing = product.channel_listings.get()+ variant_channel_listing = variant.channel_listings.get()++ variant_channel_listing.price_amount = None+ variant_channel_listing.discounted_price_amount = None+ variant_channel_listing.save(+ update_fields=["price_amount", "discounted_price_amount"]+ )++ # when+ pricing = get_variant_availability(+ variant_channel_listing=variant_channel_listing,+ product_channel_listing=product_channel_listing,+ tax_rate=tax_rate,+ tax_calculation_strategy=tc.tax_calculation_strategy,+ prices_entered_with_tax=tc.prices_entered_with_tax,+ )++ # then+ assert pricing is None++QUERY_GET_PRODUCT_VARIANTS_PRICING = """query getProductVariants($id: ID!, $channel: String, $address: AddressInput) {product(id: $id, channel: $channel) {@@ -249,6 +279,7 @@ def test_product_variant_without_price_as_user(stock,channel_USD,):+ # givenvariant.channel_listings.filter(channel=channel_USD).update(price_amount=None)product_id = graphene.Node.to_global_id("Product", variant.product.id)variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)@@ -258,9 +289,12 @@ def test_product_variant_without_price_as_user("address": {"country": "US"},}+ # whenresponse = user_api_client.post_graphql(QUERY_GET_PRODUCT_VARIANTS_PRICING, variables)++ # thencontent = get_graphql_content(response)variants_data = content["data"]["product"]["variants"]diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex e2f700c822..9eddffd036 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -28,7 +28,6 @@ from ...core.fields import PermissionsFieldfrom ...core.scalars import Datefrom ...core.tracing import traced_resolverfrom ...core.types import BaseObjectType, ModelObjectType-from ...discount.dataloaders import DiscountsByDateTimeLoaderfrom ...tax.dataloaders import (TaxClassByProductIdLoader,TaxClassCountryRateByTaxClassIDLoader,@@ -37,7 +36,6 @@ from ...tax.dataloaders import (TaxConfigurationPerCountryByTaxConfigurationIDLoader,)from ..dataloaders import (- CollectionsByProductIdLoader,ProductByIdLoader,ProductVariantsByProductIdLoader,VariantChannelListingByVariantIdAndChannelSlugLoader,@@ -216,12 +214,9 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):channel = ChannelByIdLoader(context).load(root.channel_id)product = ProductByIdLoader(context).load(root.product_id)- variants = ProductVariantsByProductIdLoader(context).load(root.product_id)- collections = CollectionsByProductIdLoader(context).load(root.product_id)- discounts = DiscountsByDateTimeLoader(context).load(info.context.request_time)def load_tax_configuration(data):- channel, product, variants, collections, discounts = data+ channel, product = datacountry_code = address_country or channel.default_country.codedef load_tax_country_exceptions(tax_config):@@ -269,13 +264,8 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):prices_entered_with_tax = tax_config.prices_entered_with_taxavailability = get_product_availability(- product=product,product_channel_listing=root,- variants=variants,variants_channel_listing=variants_channel_listing,- collections=collections,- discounts=discounts,- channel=channel,local_currency=local_currency,prices_entered_with_tax=prices_entered_with_tax,tax_calculation_strategy=tax_calculation_strategy,@@ -317,9 +307,7 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):.then(load_tax_country_exceptions))- return Promise.all([channel, product, variants, collections, discounts]).then(- load_tax_configuration- )+ return Promise.all([channel, product]).then(load_tax_configuration)class PreorderThreshold(BaseObjectType):@@ -356,7 +344,7 @@ class ProductVariantChannelListing()class Meta:- description = "Represents product varaint channel listing."+ description = "Represents product variant channel listing."model = models.ProductVariantChannelListinginterfaces = [graphene.relay.Node]diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 679f295dfd..760379bb67 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -85,7 +85,6 @@ from ...core.types import ()from ...core.utils import from_global_id_or_errorfrom ...core.validators import validate_one_of_args_is_in_query-from ...discount.dataloaders import DiscountsByDateTimeLoaderfrom ...meta.types import ObjectWithMetadatafrom ...order.dataloaders import (OrderByIdLoader,@@ -567,31 +566,23 @@ class ProductVariant(ChannelContextTypeWithMetadata[models.ProductVariant]):channel_slug = str(root.channel_slug)context = info.context- product = ProductByIdLoader(context).load(root.node.product_id)product_channel_listing = ProductChannelListingByProductIdAndChannelSlugLoader(context).load((root.node.product_id, channel_slug))variant_channel_listing = VariantChannelListingByVariantIdAndChannelSlugLoader(context).load((root.node.id, channel_slug))- collections = CollectionsByProductIdLoader(context).load(root.node.product_id)channel = ChannelBySlugLoader(context).load(channel_slug)- discounts = DiscountsByDateTimeLoader(context).load(info.context.request_time)tax_class = TaxClassByVariantIdLoader(context).load(root.node.id)- manager = get_plugin_manager_promise(info.context)address_country = address.country if address is not None else Nonedef load_tax_configuration(data):(- product,product_channel_listing,variant_channel_listing,- collections,channel,tax_class,- discounts,- manager,) = dataif not variant_channel_listing or not product_channel_listing:@@ -627,19 +618,18 @@ class ProductVariant(ChannelContextTypeWithMetadata[models.ProductVariant]):)availability = get_variant_availability(- variant=root.node,variant_channel_listing=variant_channel_listing,- product=product,product_channel_listing=product_channel_listing,- collections=collections,- discounts=discounts,- channel=channel,local_currency=local_currency,prices_entered_with_tax=tax_config.prices_entered_with_tax,tax_calculation_strategy=tax_calculation_strategy,tax_rate=tax_rate,)- return VariantPricingInfo(**asdict(availability))+ return (+ VariantPricingInfo(**asdict(availability))+ if availability+ else None+ )country_rates = (TaxClassCountryRateByTaxClassIDLoader(context).load(@@ -669,14 +659,10 @@ class ProductVariant(ChannelContextTypeWithMetadata[models.ProductVariant]):return Promise.all([- product,product_channel_listing,variant_channel_listing,- collections,channel,tax_class,- discounts,- manager,]).then(load_tax_configuration)@@ -1079,24 +1065,18 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):product_channel_listing = ProductChannelListingByProductIdAndChannelSlugLoader(context).load((root.node.id, channel_slug))- variants = ProductVariantsByProductIdLoader(context).load(root.node.id)variants_channel_listing = (VariantsChannelListingByProductIdAndChannelSlugLoader(context).load((root.node.id, channel_slug)))- collections = CollectionsByProductIdLoader(context).load(root.node.id)- discounts = DiscountsByDateTimeLoader(context).load(context.request_time)tax_class = TaxClassByProductIdLoader(context).load(root.node.id)def load_tax_configuration(data):(channel,product_channel_listing,- variants,variants_channel_listing,- collections,- discounts,tax_class,) = data@@ -1136,13 +1116,8 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):)availability = get_product_availability(- product=root.node,product_channel_listing=product_channel_listing,- variants=variants,variants_channel_listing=variants_channel_listing,- collections=collections,- discounts=discounts,- channel=channel,local_currency=local_currency,prices_entered_with_tax=tax_config.prices_entered_with_tax,tax_calculation_strategy=tax_calculation_strategy,@@ -1183,10 +1158,7 @@ class Product(ChannelContextTypeWithMetadata[models.Product]):[channel,product_channel_listing,- variants,variants_channel_listing,- collections,- discounts,tax_class,]).then(load_tax_configuration)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 6b666c56bc..a2273ccbad 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -6785,7 +6785,7 @@ type ProductVariant implements Node & ObjectWithMetadata @doc(category: "ProductexternalReference: String}-"""Represents product varaint channel listing."""+"""Represents product variant channel listing."""type ProductVariantChannelListing implements Node @doc(category: "Products") {id: ID!channel: Channel!diff --git a/saleor/product/management/commands/update_all_products_discounted_prices.py b/saleor/product/management/commands/update_all_products_discounted_prices.pyindex 427a08fe5e..b22d2d274f 100644--- a/saleor/product/management/commands/update_all_products_discounted_prices.py+++ b/saleor/product/management/commands/update_all_products_discounted_prices.py@@ -4,7 +4,7 @@ from django.core.management.base import BaseCommandfrom ....discount.utils import fetch_active_discountsfrom ...models import Product-from ...utils.variant_prices import update_product_discounted_price+from ...utils.variant_prices import update_products_discounted_pricelogger = logging.getLogger(__name__)@@ -20,4 +20,4 @@ class Command(BaseCommand):qs = Product.objects.all()for product in qs.iterator():self.stdout.write(f"Updating product PK: {product.pk}")- update_product_discounted_price(product, discounts=discounts)+ update_products_discounted_price([product], discounts=discounts)diff --git a/saleor/product/migrations/0182_productvariantchannellisting_discounted_price_amount.py b/saleor/product/migrations/0182_productvariantchannellisting_discounted_price_amount.pynew file mode 100644index 0000000000..dba276c8d3--- /dev/null+++ b/saleor/product/migrations/0182_productvariantchannellisting_discounted_price_amount.py@@ -0,0 +1,19 @@+# Generated by Django 3.2.18 on 2023-04-25 09:53++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("product", "0181_merge_20230417_1323"),+ ]++ operations = [+ migrations.AddField(+ model_name="productvariantchannellisting",+ name="discounted_price_amount",+ field=models.DecimalField(+ blank=True, decimal_places=3, max_digits=12, null=True+ ),+ ),+ ]diff --git a/saleor/product/migrations/0183_calculate_discounted_prices.py b/saleor/product/migrations/0183_calculate_discounted_prices.pynew file mode 100644index 0000000000..eb971b5b6d--- /dev/null+++ b/saleor/product/migrations/0183_calculate_discounted_prices.py@@ -0,0 +1,402 @@+# Generated by Django 3.2.18 on 2023-05-05 07:46++from django.db import migrations+from django.db.models import Exists, OuterRef, Q+from collections import defaultdict+from django.utils import timezone+from collections import namedtuple+from prices import Money, fixed_discount, percentage_discount+from functools import partial+from decimal import ROUND_HALF_UP+import mptt+import mptt.managers+++BATCH_SIZE = 500++DiscountInfo = namedtuple(+ "DiscountInfo",+ [+ "sale",+ "channel_listings",+ "product_ids",+ "category_ids",+ "collection_ids",+ "variants_ids",+ ],+)+++def calculate_variants_discounted_price(apps, schema_editor):+ Product = apps.get_model("product", "Product")+ ProductVariant = apps.get_model("product", "ProductVariant")+ CollectionProduct = apps.get_model("product", "CollectionProduct")+ ProductChannelListing = apps.get_model("product", "ProductChannelListing")+ ProductVariantChannelListing = apps.get_model(+ "product", "ProductVariantChannelListing"+ )+ SaleChannelListing = apps.get_model("discount", "SaleChannelListing")+ manager = mptt.managers.TreeManager()+ Category = apps.get_model("product", "Category")+ manager.model = Category+ mptt.register(Category, order_insertion_by=["id"])+ Category.tree = manager+ Sale = apps.get_model("discount", "Sale")+ discounts = fetch_discounts(Sale, SaleChannelListing, Category)+ update_discounted_prices_task(+ Product,+ CollectionProduct,+ ProductChannelListing,+ ProductVariantChannelListing,+ ProductVariant,+ discounts,+ )+++def fetch_discounts(sale_model, sale_listing_model, category_model):+ date = timezone.now()+ sales = list(+ sale_model.objects.filter(+ Q(end_date__isnull=True) | Q(end_date__gte=date), start_date__lte=date+ )+ )+ pks = {s.pk for s in sales}+ collections = fetch_collections(sale_model, pks)+ channel_listings = fetch_sale_channel_listings(sale_listing_model, pks)+ products = fetch_products(sale_model, pks)+ categories = fetch_categories(sale_model, category_model, pks)+ variants = fetch_variants(sale_model, pks)++ return [+ DiscountInfo(+ sale=sale,+ category_ids=categories[sale.pk],+ channel_listings=channel_listings[sale.pk],+ collection_ids=collections[sale.pk],+ product_ids=products[sale.pk],+ variants_ids=variants[sale.pk],+ )+ for sale in sales+ ]+++def fetch_collections(sale_model, sale_pks):+ collections = (+ sale_model.collections.through.objects.filter(sale_id__in=sale_pks)+ .order_by("id")+ .values_list("sale_id", "collection_id")+ )+ collection_map = defaultdict(set)+ for sale_pk, collection_pk in collections:+ collection_map[sale_pk].add(collection_pk)+ return collection_map+++def fetch_products(sale_model, sale_pks):+ products = (+ sale_model.products.through.objects.filter(sale_id__in=sale_pks)+ .order_by("id")+ .values_list("sale_id", "product_id")+ )+ product_map = defaultdict(set)+ for sale_pk, product_pk in products:+ product_map[sale_pk].add(product_pk)+ return product_map+++def fetch_variants(+ sale_model,+ sale_pks,+):+ variants = (+ sale_model.variants.through.objects.filter(sale_id__in=sale_pks)+ .order_by("id")+ .values_list("sale_id", "productvariant_id")+ )+ variants_map = defaultdict(set)+ for sale_pk, variant_pk in variants:+ variants_map[sale_pk].add(variant_pk)+ return variants_map+++def fetch_sale_channel_listings(+ sale_listing_model,+ sale_pks,+):+ channel_listings = sale_listing_model.objects.filter(sale_id__in=sale_pks)+ channel_listings_map = defaultdict(dict)+ for channel_listing in channel_listings:+ sale_id_row = channel_listings_map[channel_listing.sale_id]+ sale_id_row[channel_listing.channel_id] = channel_listing+ return channel_listings_map+++def fetch_categories(+ sale_model,+ category_model,+ sale_pks,+):+ categories = (+ sale_model.categories.through.objects.filter(sale_id__in=sale_pks)+ .order_by("id")+ .values_list("sale_id", "category_id")+ )+ category_map = defaultdict(set)+ for sale_pk, category_pk in categories:+ category_map[sale_pk].add(category_pk)+ subcategory_map = defaultdict(set)+ for sale_pk, category_pks in category_map.items():+ subcategory_map[sale_pk] = set(+ category_model.tree.filter(pk__in=category_pks)+ .get_descendants(include_self=True)+ .values_list("pk", flat=True)+ )+ return subcategory_map+++def update_discounted_prices_task(+ product_model,+ collection_product_model,+ product_listing_model,+ variant_listing_model,+ variant_model,+ discounts,+ start_pk: int = 0,+):+ products = list(+ product_model.objects.filter(pk__gt=start_pk)+ .prefetch_related("channel_listings", "collections")+ .order_by("pk")[:BATCH_SIZE]+ )++ if products:+ update_products_discounted_price(+ product_model,+ collection_product_model,+ product_listing_model,+ variant_listing_model,+ variant_model,+ products,+ discounts,+ )+ update_discounted_prices_task(+ product_model,+ collection_product_model,+ product_listing_model,+ variant_listing_model,+ variant_model,+ discounts,+ start_pk=products[-1].pk,+ )+++def update_products_discounted_price(+ product_model,+ collection_product_model,+ product_listing_model,+ variant_listing_model,+ variant_model,+ products,+ discounts,+):+ """Update Products and ProductVariants discounted prices.++ The discounted price is the minimal price of the product/variant based on active+ sales that are applied to a given product.+ If there is no applied sale, the discounted price for the product is equal to the+ cheapest variant price, in the case of the variant it's equal to the variant price.+ """+ product_ids = [product.id for product in products]+ product_qs = product_model.objects.filter(id__in=product_ids)+ collection_products = collection_product_model.objects.filter(+ Exists(product_qs.filter(id=OuterRef("product_id")))+ )+ product_to_collection_ids_map = defaultdict(set)+ for collection_id, product_id in collection_products.values_list(+ "collection_id", "product_id"+ ):+ product_to_collection_ids_map[product_id].add(collection_id)++ product_to_variant_listings_per_channel_map = (+ _get_product_to_variant_channel_listings_per_channel_map(+ product_model, variant_model, variant_listing_model, product_ids+ )+ )++ changed_products_listings_to_update = []+ changed_variants_listings_to_update = []+ product_channel_listings = product_listing_model.objects.filter(+ Exists(product_qs.filter(id=OuterRef("product_id")))+ )+ for product_channel_listing in product_channel_listings:+ product_id = product_channel_listing.product_id+ channel_id = product_channel_listing.channel_id+ variant_listings = product_to_variant_listings_per_channel_map[product_id][+ channel_id+ ]+ if not variant_listings:+ continue+ collection_ids = product_to_collection_ids_map[product_id]+ (+ discounted_variants_price,+ variant_listings_to_update,+ ) = _get_discounted_variants_prices(+ variant_listings,+ product_channel_listing.product,+ collection_ids,+ discounts,+ product_channel_listing.channel_id,+ )++ product_discounted_price = min(discounted_variants_price)+ changed_variants_listings_to_update.extend(variant_listings_to_update)++ # check if the product discounted_price has changed+ if (+ product_channel_listing.discounted_price_amount+ != product_discounted_price.amount+ ):+ product_channel_listing.discounted_price_amount = (+ product_discounted_price.amount+ )+ changed_products_listings_to_update.append(product_channel_listing)++ if changed_products_listings_to_update:+ product_listing_model.objects.bulk_update(+ changed_products_listings_to_update, ["discounted_price_amount"]+ )+ if changed_variants_listings_to_update:+ variant_listing_model.objects.bulk_update(+ changed_variants_listings_to_update, ["discounted_price_amount"]+ )+++def _get_product_to_variant_channel_listings_per_channel_map(+ product_model,+ variant_model,+ variant_listing_model,+ product_ids,+):+ products = product_model.objects.filter(id__in=product_ids)+ variants = variant_model.objects.filter(+ Exists(products.filter(id=OuterRef("product_id")))+ )+ variant_channel_listings = variant_listing_model.objects.filter(+ Exists(variants.filter(id=OuterRef("variant_id"))), price_amount__isnull=False+ )+ variant_to_product_id = {+ variant_id: product_id+ for variant_id, product_id in variants.values_list("id", "product_id")+ }++ price_data = defaultdict(lambda: defaultdict(list))+ for variant_channel_listings in variant_channel_listings:+ product_id = variant_to_product_id[variant_channel_listings.variant_id]+ price_data[product_id][variant_channel_listings.channel_id].append(+ variant_channel_listings+ )+ return price_data+++def _get_discounted_variants_prices(+ variant_listings,+ product,+ collection_ids,+ discounts,+ channel_id,+):+ variants_listings_to_update = []+ discounted_variants_price = []+ for variant_listing in variant_listings:+ discounted_variant_price = Money(+ variant_listing.price_amount, variant_listing.currency+ )+ if discounts:+ discounted_variant_price = get_minimal_price(+ product=product,+ price=discounted_variant_price,+ collection_ids=collection_ids,+ discounts=discounts,+ channel_id=channel_id,+ variant_id=variant_listing.variant_id,+ )+ if variant_listing.discounted_price_amount != discounted_variant_price.amount:+ variant_listing.discounted_price_amount = discounted_variant_price.amount+ variants_listings_to_update.append(variant_listing)+ discounted_variants_price.append(discounted_variant_price)+ return discounted_variants_price, variants_listings_to_update+++def get_minimal_price(+ product,+ price,+ collection_ids,+ discounts,+ channel_id,+ variant_id,+):+ """Return a sale_id and minimum product's price."""+ available_discounts = [+ discount+ for discount in get_product_discounts(+ product=product,+ collection_ids=collection_ids,+ discounts=discounts,+ channel_id=channel_id,+ variant_id=variant_id,+ )+ if discount+ ]+ if not available_discounts:+ return price++ min_price = min([discount(price) for discount in available_discounts])+ return min_price+++def get_product_discounts(+ product,+ collection_ids,+ discounts,+ channel_id,+ variant_id,+):+ """Return sale ids, discount values for all discounts applicable to a product."""+ for discount in discounts:+ is_product_on_sale = (+ product.id in discount.product_ids+ or product.category_id in discount.category_ids+ or bool(collection_ids.intersection(discount.collection_ids))+ )+ is_variant_on_sale = variant_id and variant_id in discount.variants_ids+ if is_product_on_sale or is_variant_on_sale:+ sale_channel_listing = discount.channel_listings.get(channel_id)+ yield get_discount(discount.sale, sale_channel_listing)+++def get_discount(sale, sale_channel_listing):+ if not sale_channel_listing:+ return+ if sale.type == "fixed":+ discount_amount = Money(+ sale_channel_listing.discount_value, sale_channel_listing.currency+ )+ return partial(fixed_discount, discount=discount_amount)+ if sale.type == "percentage":+ return partial(+ percentage_discount,+ percentage=sale_channel_listing.discount_value,+ rounding=ROUND_HALF_UP,+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("product", "0182_productvariantchannellisting_discounted_price_amount"),+ ]++ operations = [+ migrations.RunPython(+ calculate_variants_discounted_price, migrations.RunPython.noop+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 0f449b636b..0d9fe487ab 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -656,11 +656,12 @@ class ProductVariant(SortableModel, ModelWithMetadata, ModelWithExternalReferencprice_override: Optional["Decimal"] = None,) -> "Money":price = self.get_base_price(channel_listing, price_override)+ collection_ids = {collection.id for collection in collections}return calculate_discounted_price(product=product,price=price,discounts=discounts,- collections=collections,+ collection_ids=collection_ids,channel=channel,variant_id=self.id,)@@ -777,6 +778,16 @@ class ProductVariantChannelListing(models.Model):)cost_price = MoneyField(amount_field="cost_price_amount", currency_field="currency")+ discounted_price_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ blank=True,+ null=True,+ )+ discounted_price = MoneyField(+ amount_field="discounted_price_amount", currency_field="currency"+ )+preorder_quantity_threshold = models.IntegerField(blank=True, null=True)objects = ProductVariantChannelListingManager()diff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex 8a429f389d..4542be117a 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -14,10 +14,10 @@ from ..warehouse.management import deactivate_preorder_for_variantfrom .models import Product, ProductType, ProductVariantfrom .search import PRODUCTS_BATCH_SIZE, update_products_search_vectorfrom .utils.variant_prices import (- update_product_discounted_price,+ update_products_discounted_price,update_products_discounted_prices,update_products_discounted_prices_of_catalogues,- update_products_discounted_prices_of_discount,+ update_products_discounted_prices_of_sale,)from .utils.variants import generate_and_set_variant_name@@ -83,7 +83,7 @@ def update_product_discounted_price_task(product_pk: int):except ObjectDoesNotExist:logging.warning(f"Cannot find product with id: {product_pk}.")return- update_product_discounted_price(product)+ update_products_discounted_price([product])@app.task@@ -99,13 +99,13 @@ def update_products_discounted_prices_of_catalogues_task(@app.task-def update_products_discounted_prices_of_discount_task(discount_pk: int):+def update_products_discounted_prices_of_sale_task(discount_pk: int):try:discount = Sale.objects.get(pk=discount_pk)except ObjectDoesNotExist:logging.warning(f"Cannot find discount with id: {discount_pk}.")return- update_products_discounted_prices_of_discount(discount)+ update_products_discounted_prices_of_sale(discount)@app.taskdiff --git a/saleor/product/tests/test_product_availability.py b/saleor/product/tests/test_product_availability.pyindex a8bc0d9b8b..0db79d68ba 100644--- a/saleor/product/tests/test_product_availability.py+++ b/saleor/product/tests/test_product_availability.py@@ -32,13 +32,8 @@ def test_availability(stock, monkeypatch, settings, channel_USD):)taxed_price = TaxedMoney(Money("10.0", "USD"), Money("12.30", "USD"))availability = get_product_availability(- product=product,product_channel_listing=product_channel_listing,- variants=product.variants.all(),variants_channel_listing=variants_channel_listing,- channel=channel_USD,- collections=[],- discounts=[],tax_rate=tax_rate,tax_calculation_strategy=tc.tax_calculation_strategy,prices_entered_with_tax=tc.prices_entered_with_tax,@@ -54,13 +49,8 @@ def test_availability(stock, monkeypatch, settings, channel_USD):settings.DEFAULT_COUNTRY = "PL"settings.OPENEXCHANGERATES_API_KEY = "fake-key"availability = get_product_availability(- product=product,product_channel_listing=product_channel_listing,- variants=variants,variants_channel_listing=variants_channel_listing,- collections=[],- discounts=[],- channel=channel_USD,local_currency="PLN",tax_rate=tax_rate,tax_calculation_strategy=tc.tax_calculation_strategy,@@ -69,13 +59,8 @@ def test_availability(stock, monkeypatch, settings, channel_USD):assert availability.price_range_local_currency.start.currency == "PLN"availability = get_product_availability(- product=product,product_channel_listing=product_channel_listing,- variants=variants,variants_channel_listing=variants_channel_listing,- collections=[],- discounts=[],- channel=channel_USD,tax_rate=tax_rate,tax_calculation_strategy=tc.tax_calculation_strategy,prices_entered_with_tax=tc.prices_entered_with_tax,@@ -98,17 +83,13 @@ def test_availability_with_all_variant_channel_listings(stock, channel_USD):)[variant1_channel_listing, variant2_channel_listing] = variants_channel_listingvariant2_channel_listing.price_amount = Decimal(15)+ variant2_channel_listing.discounted_price_amount = Decimal(15)variant2_channel_listing.save()# whenavailability = get_product_availability(- product=product,product_channel_listing=product_channel_listing,- variants=variants,variants_channel_listing=variants_channel_listing,- channel=channel_USD,- collections=[],- discounts=[],prices_entered_with_tax=tax_config.prices_entered_with_tax,tax_calculation_strategy=tax_config.tax_calculation_strategy,tax_rate=Decimal(0),@@ -120,6 +101,42 @@ def test_availability_with_all_variant_channel_listings(stock, channel_USD):assert price_range.stop.gross.amount == variant2_channel_listing.price_amount+def test_availability_no_prices(stock, channel_USD):+ # given+ product = stock.product_variant.product+ tax_class = product.tax_class or product.product_type.tax_class++ tc = channel_USD.tax_configuration+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES+ tc.charge_taxes = True+ tc.prices_entered_with_tax = False+ tc.save()++ tax_rate = Decimal(23)+ country = "PL"+ tax_class.country_rates.update_or_create(rate=tax_rate, country=country)++ product_channel_listing = product.channel_listings.first()+ variants = product.variants.all()+ variants_channel_listing = models.ProductVariantChannelListing.objects.filter(+ variant__in=variants+ )+ variants_channel_listing.update(price_amount=None)++ # when+ availability = get_product_availability(+ product_channel_listing=product_channel_listing,+ variants_channel_listing=variants_channel_listing,+ tax_rate=tax_rate,+ tax_calculation_strategy=tc.tax_calculation_strategy,+ prices_entered_with_tax=tc.prices_entered_with_tax,+ )++ # then+ assert availability.price_range is None+ assert availability.price_range_undiscounted is None++def test_availability_with_missing_variant_channel_listings(stock, channel_USD):# givenproduct = stock.product_variant.product@@ -134,13 +151,8 @@ def test_availability_with_missing_variant_channel_listings(stock, channel_USD):# whenavailability = get_product_availability(- product=product,product_channel_listing=product_channel_listing,- variants=variants,variants_channel_listing=variants_channel_listing,- channel=channel_USD,- collections=[],- discounts=[],prices_entered_with_tax=channel_USD.tax_configuration.prices_entered_with_tax,tax_calculation_strategy="TAX_APP",tax_rate=Decimal(0),@@ -163,13 +175,8 @@ def test_availability_without_variant_channel_listings(stock, channel_USD):# whenavailability = get_product_availability(- product=product,product_channel_listing=product_channel_listing,- variants=variants,variants_channel_listing=[],- channel=channel_USD,- collections=[],- discounts=[],tax_rate=Decimal(0),tax_calculation_strategy="TAX_APP",prices_entered_with_tax=True,diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.pyindex 73c71fa8c5..e2f7bb5484 100644--- a/saleor/product/tests/test_product_minimal_variant_price.py+++ b/saleor/product/tests/test_product_minimal_variant_price.py@@ -3,11 +3,12 @@ from unittest.mock import patchfrom django.core.management import call_commandfrom prices import Money+from ...discount.models import Sale, SaleChannelListingfrom ..tasks import (update_products_discounted_prices_of_catalogues,update_products_discounted_prices_task,)-from ..utils.variant_prices import update_product_discounted_price+from ..utils.variant_prices import update_products_discounted_pricedef test_update_product_discounted_price(product, channel_USD):@@ -20,10 +21,45 @@ def test_update_product_discounted_price(product, channel_USD):assert product_channel_listing.discounted_price == Money("10", "USD")- update_product_discounted_price(product)+ update_products_discounted_price([product])product_channel_listing.refresh_from_db()+ variant_channel_listing.refresh_from_db()assert product_channel_listing.discounted_price == variant_channel_listing.price+ assert variant_channel_listing.discounted_price == variant_channel_listing.price+++def test_update_product_discounted_price_discount_on_variant(product, channel_USD):+ # given+ variant = product.variants.first()+ sale = Sale.objects.create(name="Test sale")+ discount_value = 5+ SaleChannelListing.objects.create(+ sale=sale,+ channel=channel_USD,+ discount_value=discount_value,+ currency=channel_USD.currency_code,+ )+ sale.variants.add(variant)++ variant_channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)+ product_channel_listing = product.channel_listings.get(channel_id=channel_USD.id)+ variant_channel_listing.price = Money("9.99", "USD")+ variant_channel_listing.discounted_price = Money("9.99", "USD")+ variant_channel_listing.save()+ product_channel_listing.refresh_from_db()++ assert product_channel_listing.discounted_price == Money("10", "USD")++ # when+ update_products_discounted_price([product])++ # then+ expected_price_amount = variant_channel_listing.price.amount - discount_value+ product_channel_listing.refresh_from_db()+ variant_channel_listing.refresh_from_db()+ assert product_channel_listing.discounted_price_amount == expected_price_amount+ assert variant_channel_listing.discounted_price_amount == expected_price_amountdef test_update_product_discounted_price_without_price(@@ -38,9 +74,10 @@ def test_update_product_discounted_price_without_price(assert product_channel_listing.discounted_price == Money("10", "USD")- update_product_discounted_price(product)+ update_products_discounted_price([product])product_channel_listing.refresh_from_db()+ variant_channel_listing.refresh_from_db()assert product_channel_listing.discounted_price == variant_channel_listing.priceassert second_product_channel_listing.discounted_price is None@@ -60,12 +97,15 @@ def test_update_products_discounted_prices_of_catalogues_for_product(update_products_discounted_prices_of_catalogues(product_ids=[product.pk])product_channel_listing.refresh_from_db()+ variant_channel_listing.refresh_from_db()assert product_channel_listing.discounted_price == variant_channel_listing.price+ assert variant_channel_listing.discounted_price == variant_channel_listing.pricedef test_update_products_discounted_prices_of_catalogues_for_category(category, product, channel_USD):+ # givenvariant = product.variants.first()variant_channel_listing = variant.channel_listings.get(channel=channel_USD,@@ -79,9 +119,15 @@ def test_update_products_discounted_prices_of_catalogues_for_category(product_channel_listing.refresh_from_db()assert product_channel_listing.discounted_price == Money("10", "USD")++ # whenupdate_products_discounted_prices_of_catalogues(category_ids=[product.category_id])++ # thenproduct_channel_listing.refresh_from_db()+ variant_channel_listing.refresh_from_db()assert product_channel_listing.discounted_price == variant_channel_listing.price+ assert variant_channel_listing.discounted_price == variant_channel_listing.pricedef test_update_products_discounted_prices_of_catalogues_for_collection(@@ -101,7 +147,35 @@ def test_update_products_discounted_prices_of_catalogues_for_collection(update_products_discounted_prices_of_catalogues(collection_ids=[collection.pk])product_channel_listing.refresh_from_db()+ variant_channel_listing.refresh_from_db()+ assert product_channel_listing.discounted_price == variant_channel_listing.price+ assert variant_channel_listing.discounted_price == variant_channel_listing.price+++def test_update_products_discounted_prices_of_catalogues_for_variants(+ collection, product, channel_USD+):+ # given+ variant = product.variants.first()+ variant_channel_listing = variant.channel_listings.get(+ channel=channel_USD,+ variant=variant,+ )+ variant_channel_listing.price = Money("0.79", "USD")+ product_channel_listing = product.channel_listings.get(channel_id=channel_USD.id)+ variant_channel_listing.save()+ product_channel_listing.refresh_from_db()+ collection.products.add(product)+ assert product_channel_listing.discounted_price == Money("10", "USD")++ # when+ update_products_discounted_prices_of_catalogues(variant_ids=[variant.pk])++ # then+ product_channel_listing.refresh_from_db()+ variant_channel_listing.refresh_from_db()assert product_channel_listing.discounted_price == variant_channel_listing.price+ assert variant_channel_listing.discounted_price == variant_channel_listing.pricedef test_update_products_discounted_prices_task(product_list):@@ -127,7 +201,7 @@ def test_update_products_discounted_prices_task(product_list):@patch("saleor.product.management.commands"".update_all_products_discounted_prices"- ".update_product_discounted_price"+ ".update_products_discounted_price")def test_management_commmand_update_all_products_discounted_price(mock_update_product_discounted_price, product_list@@ -135,4 +209,4 @@ def test_management_commmand_update_all_products_discounted_price(call_command("update_all_products_discounted_prices")call_args_list = mock_update_product_discounted_price.call_args_listfor (args, kwargs), product in zip(call_args_list, product_list):- assert args[0] == product+ assert args[0] == [product]diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.pyindex 91bbbffc9d..d054baf1ec 100644--- a/saleor/product/tests/test_tasks.py+++ b/saleor/product/tests/test_tasks.py@@ -7,25 +7,44 @@ from django.utils import timezonefrom ..tasks import (_get_preorder_variants_to_clean,update_product_discounted_price_task,- update_products_discounted_prices_of_discount_task,+ update_products_discounted_prices_of_sale_task,update_products_search_vector_task,update_variants_names,)-@patch("saleor.product.tasks.update_products_discounted_prices_of_discount")-def test_update_products_discounted_prices_of_discount_task(- update_product_prices_mock, sale+@patch("saleor.product.utils.variant_prices." "update_products_discounted_prices")+def test_update_products_discounted_prices_of_sale_task(+ update_products_discounted_prices_mock,+ new_sale,+ product_list,+ product,+ category,+ collection,):+ # given+ new_sale.products.add(product)+ 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())+# when- update_products_discounted_prices_of_discount_task(sale.id)+ update_products_discounted_prices_of_sale_task(new_sale.id)# then- update_product_prices_mock.assert_called_once_with(sale)+ update_products_discounted_prices_mock.assert_called_once()+ args, kwargs = update_products_discounted_prices_mock.call_args++ expected_products = [product] + product_list+ assert len(args[0]) == len(expected_products)+ assert {product.id for product in args[0]} == {+ instance.id for instance in expected_products+ }-@patch("saleor.product.tasks.update_products_discounted_prices_of_discount")-def test_update_products_discounted_prices_of_discount_task_discount_does_not_exist(+@patch("saleor.product.tasks.update_products_discounted_prices_of_sale")+def test_update_products_discounted_prices_of_sale_task_discount_does_not_exist(update_product_prices_mock, caplog):# given@@ -33,23 +52,23 @@ def test_update_products_discounted_prices_of_discount_task_discount_does_not_exdiscount_id = -1# when- update_products_discounted_prices_of_discount_task(discount_id)+ update_products_discounted_prices_of_sale_task(discount_id)# thenupdate_product_prices_mock.assert_not_called()assert f"Cannot find discount with id: {discount_id}" in caplog.text-@patch("saleor.product.tasks.update_product_discounted_price")+@patch("saleor.product.tasks.update_products_discounted_price")def test_update_product_discounted_price_task(update_product_price_mock, product):# whenupdate_product_discounted_price_task(product.id)# then- update_product_price_mock.assert_called_once_with(product)+ update_product_price_mock.assert_called_once_with([product])-@patch("saleor.product.tasks.update_product_discounted_price")+@patch("saleor.product.tasks.update_products_discounted_price")def test_update_product_discounted_price_task_product_does_not_exist(update_product_price_mock, caplog):@@ -78,7 +97,7 @@ def test_update_variants_names(assert {arg.pk for arg in args[1]} == {size_attribute.pk}-@patch("saleor.product.tasks.update_products_discounted_prices_of_discount")+@patch("saleor.product.tasks.update_products_discounted_prices_of_sale")def test_update_variants_names_product_type_does_not_exist(update_variants_names_mock, caplog):diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.pyindex bcec720ae1..63f8bf44f6 100644--- a/saleor/product/utils/availability.py+++ b/saleor/product/utils/availability.py@@ -1,20 +1,11 @@from dataclasses import dataclassfrom decimal import Decimal-from typing import Iterable, List, Optional, Tuple+from typing import List, Optional, Tuplefrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange-from ...channel.models import Channelfrom ...core.utils import to_local_currency-from ...discount import DiscountInfo-from ...discount.utils import calculate_discounted_price-from ...product.models import (- Collection,- Product,- ProductChannelListing,- ProductVariant,- ProductVariantChannelListing,-)+from ...product.models import ProductChannelListing, ProductVariantChannelListingfrom ...tax import TaxCalculationStrategyfrom ...tax.calculations import calculate_flat_rate_tax@@ -84,55 +75,26 @@ def _get_product_price_range(return price_range_local, discount_local_currency-def get_variant_price(- *,- variant: ProductVariant,- variant_channel_listing: ProductVariantChannelListing,- product: Product,- collections: Iterable[Collection],- discounts: Iterable[DiscountInfo],- channel: Channel-):- return calculate_discounted_price(- product=product,- price=variant_channel_listing.price,- collections=collections,- discounts=discounts,- channel=channel,- variant_id=variant.id,- )--def get_product_price_range(*,- product: Product,- variants: Iterable[ProductVariant],variants_channel_listing: List[ProductVariantChannelListing],- collections: Iterable[Collection],- discounts: Iterable[DiscountInfo],- channel: Channel,+ discounted: bool,) -> Optional[MoneyRange]:- if variants:- variants_channel_listing_dict = {- channel_listing.variant_id: channel_listing- for channel_listing in variants_channel_listing- if channel_listing- }- prices = []- for variant in variants:- variant_channel_listing = variants_channel_listing_dict.get(variant.id)- if variant_channel_listing:- price = get_variant_price(- variant=variant,- variant_channel_listing=variant_channel_listing,- product=product,- collections=collections,- discounts=discounts,- channel=channel,- )- prices.append(price)- if prices:- return MoneyRange(min(prices), max(prices))+ """Return the range of product prices based on product variants prices.++ When discounted parameter is True, the range of discounted prices is provided.+ """+ prices = []+ for channel_listing in variants_channel_listing:+ if channel_listing.price:+ price = (+ channel_listing.discounted_price+ if discounted+ else channel_listing.price+ )+ prices.append(price)+ if prices:+ return MoneyRange(min(prices), max(prices))return None@@ -153,13 +115,8 @@ def _calculate_product_price_with_taxes(def get_product_availability(*,- product: Product,product_channel_listing: Optional[ProductChannelListing],- variants: Iterable[ProductVariant],variants_channel_listing: List[ProductVariantChannelListing],- collections: Iterable[Collection],- discounts: Iterable[DiscountInfo],- channel: Channel,local_currency: Optional[str] = None,prices_entered_with_tax: bool,tax_calculation_strategy: str,@@ -167,12 +124,7 @@ def get_product_availability() -> ProductAvailability:discounted: Optional[TaxedMoneyRange] = Nonediscounted_net_range = get_product_price_range(- product=product,- variants=variants,- variants_channel_listing=variants_channel_listing,- collections=collections,- discounts=discounts,- channel=channel,+ variants_channel_listing=variants_channel_listing, discounted=True)if discounted_net_range is not None:discounted = TaxedMoneyRange(@@ -192,12 +144,8 @@ def get_product_availability(undiscounted: Optional[TaxedMoneyRange] = Noneundiscounted_net_range = get_product_price_range(- product=product,- variants=variants,variants_channel_listing=variants_channel_listing,- collections=collections,- discounts=[],- channel=channel,+ discounted=False,)if undiscounted_net_range is not None:undiscounted = TaxedMoneyRange(@@ -241,40 +189,22 @@ def get_product_availability(def get_variant_availability(*,- variant: ProductVariant,variant_channel_listing: ProductVariantChannelListing,- product: Product,product_channel_listing: Optional[ProductChannelListing],- collections: Iterable[Collection],- discounts: Iterable[DiscountInfo],- channel: Channel,local_currency: Optional[str] = None,prices_entered_with_tax: bool,tax_calculation_strategy: str,tax_rate: Decimal-) -> VariantAvailability:- discounted_price = get_variant_price(- variant=variant,- variant_channel_listing=variant_channel_listing,- product=product,- collections=collections,- discounts=discounts,- channel=channel,- )+) -> Optional[VariantAvailability]:+ if variant_channel_listing.price is None:+ return Nonediscounted_price_taxed = _calculate_product_price_with_taxes(- discounted_price,+ variant_channel_listing.discounted_price,tax_rate,tax_calculation_strategy,prices_entered_with_tax,)- undiscounted_price = get_variant_price(- variant=variant,- variant_channel_listing=variant_channel_listing,- product=product,- collections=collections,- discounts=[],- channel=channel,- )+ undiscounted_price = variant_channel_listing.priceundiscounted_price_taxed = _calculate_product_price_with_taxes(undiscounted_price,tax_rate,diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.pyindex 3c9780a7a6..ca92c12d15 100644--- a/saleor/product/utils/variant_prices.py+++ b/saleor/product/utils/variant_prices.py@@ -1,67 +1,143 @@-import operatorfrom collections import defaultdict-from functools import reduce-from typing import List+from typing import Dict, Iterable, List, Set, Tuple+from django.db.models import Exists, OuterReffrom django.db.models.query_utils import Qfrom prices import Money+from ...channel.models import Channel+from ...discount import DiscountInfo+from ...discount.models import Salefrom ...discount.utils import calculate_discounted_price, fetch_active_discounts-from ..models import Product, ProductChannelListing, ProductVariantChannelListing---def _get_variant_prices_in_channels_dict(product):- prices_dict = defaultdict(list)- for variant_channel_listing in ProductVariantChannelListing.objects.filter(- variant__product_id=product, price_amount__isnull=False+from ..models import (+ Category,+ CollectionProduct,+ Product,+ ProductChannelListing,+ ProductVariant,+ ProductVariantChannelListing,+)+++def update_products_discounted_price(products: Iterable[Product], discounts=None):+ """Update Products and ProductVariants discounted prices.++ The discounted price is the minimal price of the product/variant based on active+ sales that are applied to a given product.+ If there is no applied sale, the discounted price for the product is equal to the+ cheapest variant price, in the case of the variant it's equal to the variant price.+ """+ if discounts is None:+ discounts = fetch_active_discounts()+ product_ids = [product.id for product in products]+ product_qs = Product.objects.filter(id__in=product_ids)+ collection_products = CollectionProduct.objects.filter(+ Exists(product_qs.filter(id=OuterRef("product_id")))+ )+ product_to_collection_ids_map = defaultdict(set)+ for collection_id, product_id in collection_products.values_list(+ "collection_id", "product_id"):- channel_id = variant_channel_listing.channel_id- prices_dict[channel_id].append(variant_channel_listing.price)- return prices_dict---def _get_product_discounted_price(- variant_prices, product, collections, discounts, channel-) -> Money:- discounted_variants_price: List[Money] = []- for variant_price in variant_prices:- discounted_variant_price = calculate_discounted_price(- product=product,- price=variant_price,- collections=collections,- discounts=discounts,- channel=channel,- )- discounted_variants_price.append(discounted_variant_price)- return min(discounted_variants_price)+ product_to_collection_ids_map[product_id].add(collection_id)+ product_to_variant_listings_per_channel_map = (+ _get_product_to_variant_channel_listings_per_channel_map(product_ids)+ )-def update_product_discounted_price(product, discounts=None):- if discounts is None:- discounts = fetch_active_discounts()- collections = list(product.collections.all())- variant_prices_in_channels_dict = _get_variant_prices_in_channels_dict(product)- changed_products_channels_to_update = []- for product_channel_listing in product.channel_listings.all():+ changed_products_listings_to_update = []+ changed_variants_listings_to_update = []+ product_channel_listings = ProductChannelListing.objects.filter(+ Exists(product_qs.filter(id=OuterRef("product_id")))+ )+ for product_channel_listing in product_channel_listings:+ product_id = product_channel_listing.product_idchannel_id = product_channel_listing.channel_id- variant_prices_dict = variant_prices_in_channels_dict.get(channel_id)- if not variant_prices_dict:+ variant_listings = product_to_variant_listings_per_channel_map[product_id][+ channel_id+ ]+ if not variant_listings:continue- product_discounted_price = _get_product_discounted_price(- variant_prices_dict,- product,- collections,+ collection_ids = product_to_collection_ids_map[product_id]+ (+ discounted_variants_price,+ variant_listings_to_update,+ ) = _get_discounted_variants_prices(+ variant_listings,+ product_channel_listing.product,+ collection_ids,discounts,product_channel_listing.channel,)++ product_discounted_price = min(discounted_variants_price)+ changed_variants_listings_to_update.extend(variant_listings_to_update)++ # check if the product discounted_price has changedif product_channel_listing.discounted_price != product_discounted_price:product_channel_listing.discounted_price_amount = (product_discounted_price.amount)- changed_products_channels_to_update.append(product_channel_listing)- ProductChannelListing.objects.bulk_update(- changed_products_channels_to_update, ["discounted_price_amount"]+ changed_products_listings_to_update.append(product_channel_listing)++ if changed_products_listings_to_update:+ ProductChannelListing.objects.bulk_update(+ changed_products_listings_to_update, ["discounted_price_amount"]+ )+ if changed_variants_listings_to_update:+ ProductVariantChannelListing.objects.bulk_update(+ changed_variants_listings_to_update, ["discounted_price_amount"]+ )+++def _get_product_to_variant_channel_listings_per_channel_map(+ product_ids: Iterable[int],+):+ products = Product.objects.filter(id__in=product_ids)+ variants = ProductVariant.objects.filter(+ Exists(products.filter(id=OuterRef("product_id")))+ )+ variant_channel_listings = ProductVariantChannelListing.objects.filter(+ Exists(variants.filter(id=OuterRef("variant_id"))), price_amount__isnull=False)+ variant_to_product_id = {+ variant_id: product_id+ for variant_id, product_id in variants.values_list("id", "product_id")+ }++ price_data: Dict[int, Dict[int, List[Money]]] = defaultdict(+ lambda: defaultdict(list)+ )+ for variant_channel_listings in variant_channel_listings:+ product_id = variant_to_product_id[variant_channel_listings.variant_id]+ price_data[product_id][variant_channel_listings.channel_id].append(+ variant_channel_listings+ )+ return price_data+++def _get_discounted_variants_prices(+ variant_listings: List[ProductVariantChannelListing],+ product: Product,+ collection_ids: Set[int],+ discounts: List[DiscountInfo],+ channel: Channel,+) -> Tuple[Money, List[ProductVariantChannelListing]]:+ variants_listings_to_update: List[ProductVariantChannelListing] = []+ discounted_variants_price: List[Money] = []+ for variant_listing in variant_listings:+ discounted_variant_price = calculate_discounted_price(+ product=product,+ price=variant_listing.price,+ collection_ids=collection_ids,+ discounts=discounts,+ channel=channel,+ variant_id=variant_listing.variant_id,+ )+ if variant_listing.discounted_price != discounted_variant_price:+ variant_listing.discounted_price_amount = discounted_variant_price.amount+ variants_listings_to_update.append(variant_listing)+ discounted_variants_price.append(discounted_variant_price)+ return discounted_variants_price, variants_listings_to_updatedef _products_in_batches(products_qs):@@ -94,36 +170,42 @@ def update_products_discounted_prices(products, discounts=None):discounts = fetch_active_discounts()for product_batch in _products_in_batches(products):- for product in product_batch:- update_product_discounted_price(product, discounts)+ update_products_discounted_price(product_batch)def update_products_discounted_prices_of_catalogues(product_ids=None, category_ids=None, collection_ids=None, variant_ids=None):- # Building the matching products query- q_list = []+ lookup = Q()if product_ids:- q_list.append(Q(pk__in=product_ids))+ lookup |= Q(pk__in=product_ids)if category_ids:- q_list.append(Q(category_id__in=category_ids))+ categories = Category.objects.filter(id__in=category_ids)+ lookup |= Q(Exists(categories.filter(id=OuterRef("category_id"))))if collection_ids:- q_list.append(Q(collectionproduct__collection_id__in=collection_ids))- # Asserting that the function was called with some ids+ collection_products = CollectionProduct.objects.filter(+ collection_id__in=collection_ids+ )+ lookup |= Q(Exists(collection_products.filter(product_id=OuterRef("id"))))if variant_ids:- q_list.append(Q(variants__id__in=variant_ids))- if q_list:- # Querying the products- q_or = reduce(operator.or_, q_list)- products = Product.objects.filter(q_or).distinct()+ lookup |= Q(Exists(ProductVariant.objects.filter(product_id=OuterRef("id"))))++ if lookup:+ products = Product.objects.filter(lookup)update_products_discounted_prices(products)-def update_products_discounted_prices_of_discount(discount):- update_products_discounted_prices_of_catalogues(- product_ids=discount.products.all().values_list("id", flat=True),- category_ids=discount.categories.all().values_list("id", flat=True),- collection_ids=discount.collections.all().values_list("id", flat=True),- variant_ids=discount.variants.all().values_list("id", flat=True),+def update_products_discounted_prices_of_sale(sale: Sale):+ """Recalculate discounted prices of related sale products."""+ product_lookup = Q()+ product_lookup |= Q(Exists(sale.variants.filter(product_id=OuterRef("id"))))+ product_lookup |= Q(Exists(sale.categories.filter(id=OuterRef("category_id"))))+ collection_products = CollectionProduct.objects.filter(+ Exists(sale.collections.filter(id=OuterRef("collection_id"))))+ product_lookup |= Q(Exists(collection_products.filter(product_id=OuterRef("id"))))++ products = sale.products.all() | Product.objects.filter(product_lookup)++ update_products_discounted_prices(products)diff --git a/saleor/settings.py b/saleor/settings.pyindex 50840a1614..c228ee7e61 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -596,8 +596,8 @@ CELERY_BEAT_SCHEDULE = {"task": "saleor.csv.tasks.delete_old_export_files","schedule": crontab(hour=1, minute=0),},- "send-sale-toggle-notifications": {- "task": "saleor.discount.tasks.send_sale_toggle_notifications",+ "handle-sale-toggle": {+ "task": "saleor.discount.tasks.handle_sale_toggle","schedule": initiated_sale_webhook_schedule,},"update-products-search-vectors": {diff --git a/saleor/static/populatedb_data.json b/saleor/static/populatedb_data.jsonindex 1961848c7f..6c949ac692 100644--- a/saleor/static/populatedb_data.json+++ b/saleor/static/populatedb_data.json@@ -3878,6 +3878,7 @@"channel": 2,"currency": "PLN","price_amount": "40.000",+ "discounted_price_amount": "40.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3890,6 +3891,7 @@"channel": 1,"currency": "USD","price_amount": "10.000",+ "discounted_price_amount": "10.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3902,6 +3904,7 @@"channel": 2,"currency": "PLN","price_amount": "240.000",+ "discounted_price_amount": "240.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3914,6 +3917,7 @@"channel": 1,"currency": "USD","price_amount": "80.000",+ "discounted_price_amount": "80.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3926,6 +3930,7 @@"channel": 2,"currency": "PLN","price_amount": "240.000",+ "discounted_price_amount": "240.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3938,6 +3943,7 @@"channel": 2,"currency": "PLN","price_amount": "240.000",+ "discounted_price_amount": "240.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3950,6 +3956,7 @@"channel": 2,"currency": "PLN","price_amount": "240.000",+ "discounted_price_amount": "240.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3962,6 +3969,7 @@"channel": 2,"currency": "PLN","price_amount": "240.000",+ "discounted_price_amount": "240.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3974,6 +3982,7 @@"channel": 2,"currency": "PLN","price_amount": "240.000",+ "discounted_price_amount": "240.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3986,6 +3995,7 @@"channel": 2,"currency": "PLN","price_amount": "240.000",+ "discounted_price_amount": "240.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -3998,6 +4008,7 @@"channel": 1,"currency": "USD","price_amount": "80.000",+ "discounted_price_amount": "80.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4010,6 +4021,7 @@"channel": 1,"currency": "USD","price_amount": "80.000",+ "discounted_price_amount": "80.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4022,6 +4034,7 @@"channel": 1,"currency": "USD","price_amount": "80.000",+ "discounted_price_amount": "80.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4034,6 +4047,7 @@"channel": 1,"currency": "USD","price_amount": "80.000",+ "discounted_price_amount": "80.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4046,6 +4060,7 @@"channel": 1,"currency": "USD","price_amount": "80.000",+ "discounted_price_amount": "80.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4058,6 +4073,7 @@"channel": 1,"currency": "USD","price_amount": "80.000",+ "discounted_price_amount": "80.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4070,6 +4086,7 @@"channel": 2,"currency": "PLN","price_amount": "230.000",+ "discounted_price_amount": "230.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4082,6 +4099,7 @@"channel": 1,"currency": "USD","price_amount": "75.000",+ "discounted_price_amount": "75.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4094,6 +4112,7 @@"channel": 2,"currency": "PLN","price_amount": "230.000",+ "discounted_price_amount": "230.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4106,6 +4125,7 @@"channel": 1,"currency": "USD","price_amount": "75.000",+ "discounted_price_amount": "75.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4118,6 +4138,7 @@"channel": 2,"currency": "PLN","price_amount": "230.000",+ "discounted_price_amount": "230.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4130,6 +4151,7 @@"channel": 1,"currency": "USD","price_amount": "75.000",+ "discounted_price_amount": "75.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4142,6 +4164,7 @@"channel": 2,"currency": "PLN","price_amount": "420.000",+ "discounted_price_amount": "420.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4154,6 +4177,7 @@"channel": 1,"currency": "USD","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4166,6 +4190,7 @@"channel": 2,"currency": "PLN","price_amount": "420.000",+ "discounted_price_amount": "420.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4178,6 +4203,7 @@"channel": 1,"currency": "USD","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4190,6 +4216,7 @@"channel": 2,"currency": "PLN","price_amount": "420.000",+ "discounted_price_amount": "420.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4202,6 +4229,7 @@"channel": 1,"currency": "USD","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4214,6 +4242,7 @@"channel": 2,"currency": "PLN","price_amount": "420.000",+ "discounted_price_amount": "420.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4226,6 +4255,7 @@"channel": 1,"currency": "USD","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4238,6 +4268,7 @@"channel": 2,"currency": "PLN","price_amount": "420.000",+ "discounted_price_amount": "420.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4250,6 +4281,7 @@"channel": 1,"currency": "USD","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4262,6 +4294,7 @@"channel": 2,"currency": "PLN","price_amount": "209.960",+ "discounted_price_amount": "209.960","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4274,6 +4307,7 @@"channel": 1,"currency": "USD","price_amount": "50.000",+ "discounted_price_amount": "50.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4286,6 +4320,7 @@"channel": 2,"currency": "PLN","price_amount": "209.960",+ "discounted_price_amount": "209.960","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4298,6 +4333,7 @@"channel": 1,"currency": "USD","price_amount": "50.000",+ "discounted_price_amount": "50.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4310,6 +4346,7 @@"channel": 2,"currency": "PLN","price_amount": "209.960",+ "discounted_price_amount": "209.960","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4322,6 +4359,7 @@"channel": 1,"currency": "USD","price_amount": "50.000",+ "discounted_price_amount": "50.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4334,6 +4372,7 @@"channel": 2,"currency": "PLN","price_amount": "209.960",+ "discounted_price_amount": "209.960","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4346,6 +4385,7 @@"channel": 1,"currency": "USD","price_amount": "50.000",+ "discounted_price_amount": "50.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4358,6 +4398,7 @@"channel": 2,"currency": "PLN","price_amount": "209.960",+ "discounted_price_amount": "209.960","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4370,6 +4411,7 @@"channel": 1,"currency": "USD","price_amount": "50.000",+ "discounted_price_amount": "50.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4382,6 +4424,7 @@"channel": 2,"currency": "PLN","price_amount": "100.000",+ "discounted_price_amount": "100.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4394,6 +4437,7 @@"channel": 1,"currency": "USD","price_amount": "30.000",+ "discounted_price_amount": "30.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4406,6 +4450,7 @@"channel": 2,"currency": "PLN","price_amount": "120.000",+ "discounted_price_amount": "120.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4418,6 +4463,7 @@"channel": 1,"currency": "USD","price_amount": "35.000",+ "discounted_price_amount": "35.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4430,6 +4476,7 @@"channel": 2,"currency": "PLN","price_amount": "120.000",+ "discounted_price_amount": "120.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4442,6 +4489,7 @@"channel": 1,"currency": "USD","price_amount": "35.000",+ "discounted_price_amount": "35.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4454,6 +4502,7 @@"channel": 2,"currency": "PLN","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4466,6 +4515,7 @@"channel": 1,"currency": "USD","price_amount": "20.000",+ "discounted_price_amount": "20.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4478,6 +4528,7 @@"channel": 2,"currency": "PLN","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4490,6 +4541,7 @@"channel": 1,"currency": "USD","price_amount": "20.000",+ "discounted_price_amount": "20.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4502,6 +4554,7 @@"channel": 2,"currency": "PLN","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4514,6 +4567,7 @@"channel": 1,"currency": "USD","price_amount": "20.000",+ "discounted_price_amount": "20.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4526,6 +4580,7 @@"channel": 2,"currency": "PLN","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4538,6 +4593,7 @@"channel": 1,"currency": "USD","price_amount": "20.000",+ "discounted_price_amount": "20.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4550,6 +4606,7 @@"channel": 2,"currency": "PLN","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4562,6 +4619,7 @@"channel": 1,"currency": "USD","price_amount": "20.000",+ "discounted_price_amount": "20.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4574,6 +4632,7 @@"channel": 2,"currency": "PLN","price_amount": "200.000",+ "discounted_price_amount": "200.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4586,6 +4645,7 @@"channel": 1,"currency": "USD","price_amount": "40.000",+ "discounted_price_amount": "40.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4598,6 +4658,7 @@"channel": 2,"currency": "PLN","price_amount": "200.000",+ "discounted_price_amount": "200.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4610,6 +4671,7 @@"channel": 1,"currency": "USD","price_amount": "40.000",+ "discounted_price_amount": "40.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4622,6 +4684,7 @@"channel": 2,"currency": "PLN","price_amount": "200.000",+ "discounted_price_amount": "200.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4634,6 +4697,7 @@"channel": 1,"currency": "USD","price_amount": "40.000",+ "discounted_price_amount": "40.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4646,6 +4710,7 @@"channel": 2,"currency": "PLN","price_amount": "200.000",+ "discounted_price_amount": "200.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4658,6 +4723,7 @@"channel": 1,"currency": "USD","price_amount": "40.000",+ "discounted_price_amount": "40.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4670,6 +4736,7 @@"channel": 2,"currency": "PLN","price_amount": "200.000",+ "discounted_price_amount": "200.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4682,6 +4749,7 @@"channel": 1,"currency": "USD","price_amount": "40.000",+ "discounted_price_amount": "40.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4694,6 +4762,7 @@"channel": 2,"currency": "PLN","price_amount": "150.000",+ "discounted_price_amount": "150.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4706,6 +4775,7 @@"channel": 1,"currency": "USD","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4718,6 +4788,7 @@"channel": 2,"currency": "PLN","price_amount": "150.000",+ "discounted_price_amount": "150.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4730,6 +4801,7 @@"channel": 1,"currency": "USD","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4742,6 +4814,7 @@"channel": 2,"currency": "PLN","price_amount": "150.000",+ "discounted_price_amount": "150.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4754,6 +4827,7 @@"channel": 1,"currency": "USD","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4766,6 +4840,7 @@"channel": 2,"currency": "PLN","price_amount": "150.000",+ "discounted_price_amount": "150.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4778,6 +4853,7 @@"channel": 1,"currency": "USD","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4790,6 +4866,7 @@"channel": 2,"currency": "PLN","price_amount": "150.000",+ "discounted_price_amount": "150.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4802,6 +4879,7 @@"channel": 1,"currency": "USD","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4814,6 +4892,7 @@"channel": 2,"currency": "PLN","price_amount": "150.000",+ "discounted_price_amount": "150.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4826,6 +4905,7 @@"channel": 1,"currency": "USD","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4838,6 +4918,7 @@"channel": 2,"currency": "PLN","price_amount": "150.000",+ "discounted_price_amount": "150.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4850,6 +4931,7 @@"channel": 1,"currency": "USD","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4862,6 +4944,7 @@"channel": 2,"currency": "PLN","price_amount": "150.000",+ "discounted_price_amount": "150.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4874,6 +4957,7 @@"channel": 1,"currency": "USD","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4886,6 +4970,7 @@"channel": 2,"currency": "PLN","price_amount": "150.000",+ "discounted_price_amount": "150.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4898,6 +4983,7 @@"channel": 1,"currency": "USD","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4910,6 +4996,7 @@"channel": 2,"currency": "PLN","price_amount": "50.000",+ "discounted_price_amount": "50.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4922,6 +5009,7 @@"channel": 1,"currency": "USD","price_amount": "10.000",+ "discounted_price_amount": "10.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4934,6 +5022,7 @@"channel": 2,"currency": "PLN","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4946,6 +5035,7 @@"channel": 1,"currency": "USD","price_amount": "20.000",+ "discounted_price_amount": "20.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4958,6 +5048,7 @@"channel": 2,"currency": "PLN","price_amount": "60.000",+ "discounted_price_amount": "60.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4970,6 +5061,7 @@"channel": 1,"currency": "USD","price_amount": "15.000",+ "discounted_price_amount": "15.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4982,6 +5074,7 @@"channel": 2,"currency": "PLN","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -4994,6 +5087,7 @@"channel": 1,"currency": "USD","price_amount": "10.000",+ "discounted_price_amount": "10.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5006,6 +5100,7 @@"channel": 2,"currency": "PLN","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5018,6 +5113,7 @@"channel": 1,"currency": "USD","price_amount": "10.000",+ "discounted_price_amount": "10.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5030,6 +5126,7 @@"channel": 2,"currency": "PLN","price_amount": "45.000",+ "discounted_price_amount": "45.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5042,6 +5139,7 @@"channel": 1,"currency": "USD","price_amount": "10.000",+ "discounted_price_amount": "10.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5054,6 +5152,7 @@"channel": 2,"currency": "PLN","price_amount": "29.990",+ "discounted_price_amount": "29.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5066,6 +5165,7 @@"channel": 1,"currency": "USD","price_amount": "8.990",+ "discounted_price_amount": "8.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5078,6 +5178,7 @@"channel": 2,"currency": "PLN","price_amount": "29.990",+ "discounted_price_amount": "29.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5090,6 +5191,7 @@"channel": 1,"currency": "USD","price_amount": "8.990",+ "discounted_price_amount": "8.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5102,6 +5204,7 @@"channel": 2,"currency": "PLN","price_amount": "29.990",+ "discounted_price_amount": "29.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5114,6 +5217,7 @@"channel": 1,"currency": "USD","price_amount": "8.990",+ "discounted_price_amount": "8.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5126,6 +5230,7 @@"channel": 2,"currency": "PLN","price_amount": "29.990",+ "discounted_price_amount": "29.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5138,6 +5243,7 @@"channel": 1,"currency": "USD","price_amount": "8.990",+ "discounted_price_amount": "8.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5150,6 +5256,7 @@"channel": 2,"currency": "PLN","price_amount": "9.990",+ "discounted_price_amount": "9.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5162,6 +5269,7 @@"channel": 1,"currency": "USD","price_amount": "2.000",+ "discounted_price_amount": "2.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5174,6 +5282,7 @@"channel": 2,"currency": "PLN","price_amount": "9.990",+ "discounted_price_amount": "9.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5186,6 +5295,7 @@"channel": 1,"currency": "USD","price_amount": "2.000",+ "discounted_price_amount": "2.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5198,6 +5308,7 @@"channel": 2,"currency": "PLN","price_amount": "29.990",+ "discounted_price_amount": "29.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5210,6 +5321,7 @@"channel": 1,"currency": "USD","price_amount": "11.990",+ "discounted_price_amount": "11.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5222,6 +5334,7 @@"channel": 2,"currency": "PLN","price_amount": "70.000",+ "discounted_price_amount": "70.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5234,6 +5347,7 @@"channel": 1,"currency": "USD","price_amount": "18.000",+ "discounted_price_amount": "18.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5246,6 +5360,7 @@"channel": 2,"currency": "PLN","price_amount": "5.990",+ "discounted_price_amount": "5.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5258,6 +5373,7 @@"channel": 1,"currency": "USD","price_amount": "1.990",+ "discounted_price_amount": "1.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5270,6 +5386,7 @@"channel": 2,"currency": "PLN","price_amount": "5.990",+ "discounted_price_amount": "5.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5282,6 +5399,7 @@"channel": 1,"currency": "USD","price_amount": "1.990",+ "discounted_price_amount": "1.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5294,6 +5412,7 @@"channel": 2,"currency": "PLN","price_amount": "5.990",+ "discounted_price_amount": "5.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5306,6 +5425,7 @@"channel": 1,"currency": "USD","price_amount": "1.990",+ "discounted_price_amount": "1.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5318,6 +5438,7 @@"channel": 2,"currency": "PLN","price_amount": "5.990",+ "discounted_price_amount": "5.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5330,6 +5451,7 @@"channel": 1,"currency": "USD","price_amount": "1.990",+ "discounted_price_amount": "1.990","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5342,6 +5464,7 @@"channel": 2,"currency": "PLN","price_amount": "90.000",+ "discounted_price_amount": "90.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5354,6 +5477,7 @@"channel": 1,"currency": "USD","price_amount": "17.000",+ "discounted_price_amount": "17.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5366,6 +5490,7 @@"channel": 2,"currency": "PLN","price_amount": "120.000",+ "discounted_price_amount": "120.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5378,6 +5503,7 @@"channel": 1,"currency": "USD","price_amount": "25.000",+ "discounted_price_amount": "25.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5390,6 +5516,7 @@"channel": 2,"currency": "PLN","price_amount": "120.000",+ "discounted_price_amount": "120.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5402,6 +5529,7 @@"channel": 1,"currency": "USD","price_amount": "25.000",+ "discounted_price_amount": "25.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5414,6 +5542,7 @@"channel": 2,"currency": "PLN","price_amount": "450.000",+ "discounted_price_amount": "450.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5426,6 +5555,7 @@"channel": 1,"currency": "USD","price_amount": "100.000",+ "discounted_price_amount": "100.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5438,6 +5568,7 @@"channel": 2,"currency": "PLN","price_amount": "130.000",+ "discounted_price_amount": "130.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5450,6 +5581,7 @@"channel": 1,"currency": "USD","price_amount": "30.000",+ "discounted_price_amount": "30.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5462,6 +5594,7 @@"channel": 2,"currency": "PLN","price_amount": "130.000",+ "discounted_price_amount": "130.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5474,6 +5607,7 @@"channel": 1,"currency": "USD","price_amount": "30.000",+ "discounted_price_amount": "30.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5486,6 +5620,7 @@"channel": 2,"currency": "PLN","price_amount": "130.000",+ "discounted_price_amount": "130.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5498,6 +5633,7 @@"channel": 1,"currency": "USD","price_amount": "30.000",+ "discounted_price_amount": "30.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5510,6 +5646,7 @@"channel": 2,"currency": "PLN","price_amount": "130.000",+ "discounted_price_amount": "130.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5522,6 +5659,7 @@"channel": 1,"currency": "USD","price_amount": "30.000",+ "discounted_price_amount": "30.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5534,6 +5672,7 @@"channel": 2,"currency": "PLN","price_amount": "130.000",+ "discounted_price_amount": "130.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5546,6 +5685,7 @@"channel": 1,"currency": "USD","price_amount": "30.000",+ "discounted_price_amount": "30.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5558,6 +5698,7 @@"channel": 2,"currency": "PLN","price_amount": "230.000",+ "discounted_price_amount": "230.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5570,6 +5711,7 @@"channel": 1,"currency": "USD","price_amount": "50.000",+ "discounted_price_amount": "50.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5582,6 +5724,7 @@"channel": 2,"currency": "PLN","price_amount": "2300.000",+ "discounted_price_amount": "2300.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5594,6 +5737,7 @@"channel": 1,"currency": "USD","price_amount": "500.000",+ "discounted_price_amount": "500.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5606,6 +5750,7 @@"channel": 2,"currency": "PLN","price_amount": "230.000",+ "discounted_price_amount": "230.000","cost_price_amount": null,"preorder_quantity_threshold": null}@@ -5618,6 +5763,7 @@"channel": 1,"currency": "USD","price_amount": "50.000",+ "discounted_price_amount": "50.000","cost_price_amount": null,"preorder_quantity_threshold": null}diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 6b0b6612d6..e569579cd0 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -2216,6 +2216,7 @@ def product(product_type, category, warehouse, channel_USD, default_tax_class):variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2255,6 +2256,7 @@ def shippable_gift_card_product(variant=variant,channel=channel_USD,price_amount=Decimal(100),+ discounted_price_amount=Decimal(100),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2289,6 +2291,7 @@ def product_price_0(category, warehouse, channel_USD):variant=variant,channel=channel_USD,price_amount=Decimal(0),+ discounted_price_amount=Decimal(0),cost_price_amount=Decimal(0),currency=channel_USD.currency_code,)@@ -2312,6 +2315,7 @@ def product_in_channel_JPY(product, channel_JPY, warehouse_JPY):variant=variant,channel=channel_JPY,price_amount=Decimal(1200),+ discounted_price_amount=Decimal(1200),cost_price_amount=Decimal(300),currency=channel_JPY.currency_code,)@@ -2348,6 +2352,7 @@ def non_shippable_gift_card_product(variant=variant,channel=channel_USD,price_amount=Decimal(250),+ discounted_price_amount=Decimal(250),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2389,6 +2394,7 @@ def product_with_rich_text_attribute(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2418,6 +2424,7 @@ def product_available_in_many_channels(product, channel_PLN, channel_USD):variant=variant,channel=channel_PLN,price_amount=Decimal(50),+ discounted_price_amount=Decimal(50),cost_price_amount=Decimal(1),currency=channel_PLN.currency_code,)@@ -2444,6 +2451,7 @@ def product_with_single_variant(product_type, category, warehouse, channel_USD):variant=variant,channel=channel_USD,price_amount=Decimal(1.99),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2481,6 +2489,7 @@ def product_with_two_variants(product_type, category, warehouse, channel_USD):variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2539,6 +2548,7 @@ def product_with_variant_with_two_attributes(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2601,6 +2611,7 @@ def product_with_variant_with_external_media(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2651,6 +2662,7 @@ def product_with_variant_with_file_attribute(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2709,6 +2721,7 @@ def product_with_default_variant(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2748,6 +2761,7 @@ def variant_without_inventory_tracking(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2764,6 +2778,7 @@ def variant(product, channel_USD) -> ProductVariant:variant=product_variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2798,6 +2813,7 @@ def preorder_variant_global_threshold(product, channel_USD):variant=product_variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2813,6 +2829,7 @@ def preorder_variant_channel_threshold(product, channel_USD):variant=product_variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,preorder_quantity_threshold=10,@@ -2861,6 +2878,7 @@ def preorder_variant_with_end_date(product, channel_USD):variant=product_variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2891,6 +2909,7 @@ def gift_card_shippable_variant(shippable_gift_card_product, channel_USD, warehovariant=product_variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2912,6 +2931,7 @@ def gift_card_non_shippable_variant(variant=product_variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -2940,6 +2960,7 @@ def product_variant_list(product, channel_USD, channel_PLN):channel=channel_USD,cost_price_amount=Decimal(1),price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),currency=channel_USD.currency_code,),ProductVariantChannelListing(@@ -2947,6 +2968,7 @@ def product_variant_list(product, channel_USD, channel_PLN):channel=channel_USD,cost_price_amount=Decimal(1),price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),currency=channel_USD.currency_code,),ProductVariantChannelListing(@@ -2954,6 +2976,7 @@ def product_variant_list(product, channel_USD, channel_PLN):channel=channel_PLN,cost_price_amount=Decimal(1),price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),currency=channel_PLN.currency_code,),ProductVariantChannelListing(@@ -2961,6 +2984,7 @@ def product_variant_list(product, channel_USD, channel_PLN):channel=channel_USD,cost_price_amount=Decimal(1),price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),currency=channel_USD.currency_code,),]@@ -2995,6 +3019,7 @@ def product_without_shipping(category, warehouse, channel_USD):variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -3112,6 +3137,7 @@ def product_list(channel=channel_USD,cost_price_amount=Decimal(1),price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),currency=channel_USD.currency_code,),ProductVariantChannelListing(@@ -3119,6 +3145,7 @@ def product_list(channel=channel_USD,cost_price_amount=Decimal(1),price_amount=Decimal(20),+ discounted_price_amount=Decimal(20),currency=channel_USD.currency_code,),ProductVariantChannelListing(@@ -3126,6 +3153,7 @@ def product_list(channel=channel_USD,cost_price_amount=Decimal(1),price_amount=Decimal(30),+ discounted_price_amount=Decimal(30),currency=channel_USD.currency_code,),]@@ -3411,6 +3439,7 @@ def unavailable_product_with_variant(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -4043,6 +4072,7 @@ def order_with_lines(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)@@ -4095,6 +4125,7 @@ def order_with_lines(variant=variant,channel=channel_USD,price_amount=Decimal(20),+ discounted_price_amount=Decimal(20),cost_price_amount=Decimal(2),currency=channel_USD.currency_code,)@@ -4328,6 +4359,7 @@ def order_with_lines_channel_PLN(variant=variant,channel=channel_PLN,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_PLN.currency_code,)@@ -4379,6 +4411,7 @@ def order_with_lines_channel_PLN(variant=variant,channel=channel_PLN,price_amount=Decimal(20),+ discounted_price_amount=Decimal(20),cost_price_amount=Decimal(2),currency=channel_PLN.currency_code,)@@ -4497,6 +4530,7 @@ def order_with_preorder_lines(variant=variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,preorder_quantity_threshold=10,@@ -5827,6 +5861,7 @@ def digital_content(category, media_root, warehouse, channel_USD) -> DigitalContvariant=product_variant,channel=channel_USD,price_amount=Decimal(10),+ discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),currency=channel_USD.currency_code,)