Skip to content

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

Make sale per variant (#8064)

Paweł Kucharski4f52e40d1fce
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 03f27d06ca..d65a32f987 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Improve draft orders and orders webhooks by @jakubkuc
- Fix cursor-based pagination in products search - #8011 by @rafalp
- Extend `accountRegister` mutation to consume first & last name - #8184 by @piotrgrundas
+- Introduce sales / vouchers per product variant - #8064 by @kuchichan
# 3.0.0 [Unreleased]
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 6494ac68f9..52a92525e8 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -746,6 +746,9 @@ def create_fake_sale():
)
for product in Product.objects.all().order_by("?")[:4]:
sale.products.add(product)
+
+ for variant in ProductVariant.objects.all().order_by("?")[:2]:
+ sale.variants.add(variant)
return sale
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
index a3588cf6e6..11bc143191 100644
--- a/saleor/discount/__init__.py
+++ b/saleor/discount/__init__.py
@@ -43,3 +43,4 @@ class DiscountInfo:
product_ids: Union[List[int], Set[int]]
category_ids: Union[List[int], Set[int]]
collection_ids: Union[List[int], Set[int]]
+ variants_ids: Union[List[int], Set[int]]
diff --git a/saleor/discount/migrations/0030_discount_variants.py b/saleor/discount/migrations/0030_discount_variants.py
new file mode 100644
index 0000000000..40b2f120a1
--- /dev/null
+++ b/saleor/discount/migrations/0030_discount_variants.py
@@ -0,0 +1,22 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0147_auto_20210817_1015"),
+ ("discount", "0029_merge_0028_alter_voucher_code_0028_auto_20210817_1015"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sale",
+ name="variants",
+ field=models.ManyToManyField(blank=True, to="product.ProductVariant"),
+ ),
+ migrations.AddField(
+ model_name="voucher",
+ name="variants",
+ field=models.ManyToManyField(blank=True, to="product.ProductVariant"),
+ ),
+ ]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index ef391e14ef..56f4530bb1 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -85,6 +85,7 @@ class Voucher(ModelWithMetadata):
countries = CountryField(multiple=True, blank=True)
min_checkout_items_quantity = models.PositiveIntegerField(null=True, blank=True)
products = models.ManyToManyField("product.Product", blank=True)
+ variants = models.ManyToManyField("product.ProductVariant", blank=True)
collections = models.ManyToManyField("product.Collection", blank=True)
categories = models.ManyToManyField("product.Category", blank=True)
@@ -247,9 +248,10 @@ class Sale(ModelWithMetadata):
choices=DiscountValueType.CHOICES,
default=DiscountValueType.FIXED,
)
- products = models.ManyToManyField("product.Product", blank=True)
categories = models.ManyToManyField("product.Category", blank=True)
collections = models.ManyToManyField("product.Collection", blank=True)
+ products = models.ManyToManyField("product.Product", blank=True)
+ variants = models.ManyToManyField("product.ProductVariant", blank=True)
start_date = models.DateTimeField(default=timezone.now)
end_date = models.DateTimeField(null=True, blank=True)
diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.py
index 325e53ee89..f35216408e 100644
--- a/saleor/discount/tests/test_discounts.py
+++ b/saleor/discount/tests/test_discounts.py
@@ -107,6 +107,74 @@ def test_valid_voucher_min_checkout_items_quantity(voucher):
)
[email protected]_db(transaction=True)
+def test_discount_for_variants_is_applied_to_single_variant(product, channel_USD):
+ discount_value = 5
+ variant = product.variants.get()
+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
+ sale = Sale.objects.create(type=DiscountValueType.FIXED)
+ sale_channel_listing = SaleChannelListing.objects.create(
+ sale=sale,
+ discount_value=discount_value,
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ )
+ old_price = variant.get_price(
+ product, [], channel_USD, variant_channel_listing, discounts=[]
+ )
+
+ discount_info = DiscountInfo(
+ sale=sale,
+ channel_listings={channel_USD.slug: sale_channel_listing},
+ product_ids=set(),
+ category_ids=set(),
+ collection_ids=set(),
+ variants_ids={variant.id},
+ )
+
+ new_price = variant.get_price(
+ product, [], channel_USD, variant_channel_listing, discounts=[discount_info]
+ )
+
+ assert new_price == old_price - Money(discount_value, "USD")
+
+
[email protected]_db(transaction=True)
+def test_discount_for_variants_are_not_applied_twice_for_variant_assigned_to_product(
+ product, channel_USD
+):
+ discount_value = 5
+ variant = product.variants.get()
+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
+ sale = Sale.objects.create(type=DiscountValueType.FIXED)
+ sale_channel_listing = SaleChannelListing.objects.create(
+ sale=sale,
+ discount_value=discount_value,
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ )
+ old_price = variant.get_price(
+ product, [], channel_USD, variant_channel_listing, discounts=[]
+ )
+
+ discount_info = DiscountInfo(
+ sale=sale,
+ channel_listings={channel_USD.slug: sale_channel_listing},
+ product_ids={product.id},
+ category_ids=set(),
+ collection_ids=set(),
+ variants_ids={variant.id},
+ )
+
+ new_price = variant.get_price(
+ product, [], channel_USD, variant_channel_listing, discounts=[discount_info]
+ )
+
+ assert new_price == old_price - Money(discount_value, "USD")
+
+
@pytest.mark.integration
@pytest.mark.django_db(transaction=True)
def test_variant_discounts(product, channel_USD):
@@ -124,6 +192,7 @@ def test_variant_discounts(product, channel_USD):
product_ids={product.id},
category_ids=set(),
collection_ids=set(),
+ variants_ids=set(),
)
sale = Sale.objects.create(type=DiscountValueType.FIXED)
sale_channel_listing = SaleChannelListing.objects.create(
@@ -138,6 +207,7 @@ def test_variant_discounts(product, channel_USD):
product_ids={product.id},
category_ids=set(),
collection_ids=set(),
+ variants_ids=set(),
)
high_sale = Sale.objects.create(type=DiscountValueType.FIXED)
high_sale_channel_listing = SaleChannelListing.objects.create(
@@ -152,6 +222,7 @@ def test_variant_discounts(product, channel_USD):
product_ids={product.id},
category_ids=set(),
collection_ids=set(),
+ variants_ids=set(),
)
variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
final_price = variant.get_price(
@@ -164,6 +235,85 @@ def test_variant_discounts(product, channel_USD):
assert final_price == Money(0, "USD")
[email protected]_db(transaction=True)
+def test_discount_for_variants_when_sale_for_specific_variants_only(
+ product, channel_USD
+):
+ discount_value = 5
+ variant = ProductVariant.objects.create(product=product, sku="456")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(20),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
+ )
+ variant = ProductVariant.objects.create(product=product, sku="789")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(20),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
+ )
+ product.refresh_from_db()
+
+ all_variants = product.variants.all()
+ first_variant, *rest_variants = all_variants
+
+ first_variant_channel_listing = first_variant.channel_listings.get(
+ channel=channel_USD
+ )
+ sale = Sale.objects.create(type=DiscountValueType.FIXED)
+ sale_channel_listing = SaleChannelListing.objects.create(
+ sale=sale,
+ discount_value=discount_value,
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ )
+
+ old_price = first_variant.get_price(
+ product, [], channel_USD, first_variant_channel_listing, discounts=[]
+ )
+
+ old_price_for_applied_variants = []
+
+ for variant in rest_variants:
+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
+ old_price_for_applied_variants.append(
+ variant.get_price(
+ product, [], channel_USD, variant_channel_listing, discounts=[]
+ )
+ )
+
+ discount = DiscountInfo(
+ sale=sale,
+ channel_listings={channel_USD.slug: sale_channel_listing},
+ product_ids=set(),
+ category_ids=set(),
+ collection_ids=set(),
+ variants_ids={variant.id for variant in rest_variants},
+ )
+
+ new_price = first_variant.get_price(
+ product, [], channel_USD, first_variant_channel_listing, discounts=[discount]
+ )
+
+ new_price_for_applied_variants = []
+ for variant in rest_variants:
+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
+ new_price_for_applied_variants.append(
+ variant.get_price(
+ product, [], channel_USD, variant_channel_listing, discounts=[discount]
+ )
+ )
+
+ assert new_price == old_price
+ for p1, p2 in zip(new_price_for_applied_variants, old_price_for_applied_variants):
+ assert p1 == p2 - Money(discount_value, "USD")
+
+
@pytest.mark.integration
@pytest.mark.django_db(transaction=True)
def test_percentage_discounts(product, channel_USD):
@@ -181,6 +331,7 @@ def test_percentage_discounts(product, channel_USD):
product_ids={product.id},
category_ids=set(),
collection_ids=set(),
+ variants_ids=set(),
)
variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
final_price = variant.get_price(
@@ -309,6 +460,7 @@ def test_sale_applies_to_correct_products(product_type, category, channel_USD):
product_ids={product.id},
category_ids=set(),
collection_ids=set(),
+ variants_ids=set(),
)
product_discount = get_product_discount_on_sale(
variant.product, set(), discount, channel_USD
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 7058909fb7..2d211542fe 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -55,6 +55,7 @@ def get_product_discount_on_sale(
product_collections: Set[int],
discount: DiscountInfo,
channel: "Channel",
+ variant_id: Optional[int] = None,
):
"""Return discount value if product is on sale or raise NotApplicable."""
is_product_on_sale = (
@@ -62,7 +63,8 @@ def get_product_discount_on_sale(
or product.category_id in discount.category_ids
or product_collections.intersection(discount.collection_ids)
)
- if is_product_on_sale:
+ 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.slug)
return discount.sale.get_discount(sale_channel_listing) # type: ignore
raise NotApplicable("Discount not applicable for this product")
@@ -73,14 +75,15 @@ def get_product_discounts(
product: "Product",
collections: Iterable["Collection"],
discounts: Iterable[DiscountInfo],
- channel: "Channel"
+ channel: "Channel",
+ variant_id: Optional[int] = None
) -> Money:
"""Return discount values for all discounts applicable to a product."""
product_collections = set(pc.id for pc in collections)
for discount in discounts or []:
try:
yield get_product_discount_on_sale(
- product, product_collections, discount, channel
+ product, product_collections, discount, channel, variant_id=variant_id
)
except NotApplicable:
pass
@@ -92,7 +95,8 @@ def calculate_discounted_price(
price: Money,
collections: Iterable["Collection"],
discounts: Optional[Iterable[DiscountInfo]],
- channel: "Channel"
+ channel: "Channel",
+ variant_id: Optional[int] = None
) -> Money:
"""Return minimum product's price of all prices with discounts applied."""
if discounts:
@@ -102,6 +106,7 @@ def calculate_discounted_price(
collections=collections,
discounts=discounts,
channel=channel,
+ variant_id=variant_id,
)
)
if discount_prices:
@@ -222,6 +227,18 @@ def fetch_products(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
return product_map
+def fetch_variants(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
+ variants = (
+ Sale.variants.through.objects.filter(sale_id__in=sale_pks)
+ .order_by("id")
+ .values_list("sale_id", "productvariant_id")
+ )
+ variants_map: Dict[int, Set[int]] = 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_pks: Iterable[str],
):
@@ -242,6 +259,7 @@ def fetch_discounts(date: datetime.date) -> List[DiscountInfo]:
channel_listings = fetch_sale_channel_listings(pks)
products = fetch_products(pks)
categories = fetch_categories(pks)
+ variants = fetch_variants(pks)
return [
DiscountInfo(
@@ -250,6 +268,7 @@ def fetch_discounts(date: datetime.date) -> List[DiscountInfo]:
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
]
diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
index 1bae1b428c..de159dae31 100644
--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
@@ -137,6 +137,7 @@ def test_checkout_totals_use_discounts(
product_ids={product.id},
category_ids=set(),
collection_ids=set(),
+ variants_ids=set(),
)
]
diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.py
index 20d305c428..2ef57fb46d 100644
--- a/saleor/graphql/discount/dataloaders.py
+++ b/saleor/graphql/discount/dataloaders.py
@@ -15,6 +15,7 @@ from ...discount.utils import (
fetch_collections,
fetch_products,
fetch_sale_channel_listings,
+ fetch_variants,
)
from ..core.dataloaders import DataLoader
@@ -32,6 +33,7 @@ class DiscountsByDateTimeLoader(DataLoader):
channel_listings = fetch_sale_channel_listings(pks)
products = fetch_products(pks)
categories = fetch_categories(pks)
+ variants = fetch_variants(pks)
return [
[
@@ -41,6 +43,7 @@ class DiscountsByDateTimeLoader(DataLoader):
category_ids=categories[sale.pk],
collection_ids=collections[sale.pk],
product_ids=products[sale.pk],
+ variants_ids=variants[sale.pk],
)
for sale in sales_map[datetime]
]
diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.py
index 3e2f7772e1..eb1605bd21 100644
--- a/saleor/graphql/discount/mutations.py
+++ b/saleor/graphql/discount/mutations.py
@@ -17,11 +17,12 @@ from ...product.tasks import (
from ...product.utils import get_products_ids_without_variants
from ..channel import ChannelContext
from ..channel.mutations import BaseChannelListingMutation
+from ..core.descriptions import ADDED_IN_31
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.scalars import PositiveDecimal
from ..core.types.common import DiscountError
from ..core.validators import validate_end_is_after_start, validate_price_precision
-from ..product.types import Category, Collection, Product
+from ..product.types import Category, Collection, Product, ProductVariant
from .enums import DiscountValueTypeEnum, VoucherTypeEnum
from .types import Sale, Voucher
@@ -45,6 +46,11 @@ class CatalogueInput(graphene.InputObjectType):
description="Collections related to the discount.",
name="collections",
)
+ variants = graphene.List(
+ graphene.ID,
+ description=f"{ADDED_IN_31} Product variant related to the discount.",
+ name="variants",
+ )
class BaseDiscountCatalogueMutation(BaseMutation):
@@ -52,11 +58,12 @@ class BaseDiscountCatalogueMutation(BaseMutation):
abstract = True
@classmethod
- def recalculate_discounted_prices(cls, products, categories, collections):
+ def recalculate_discounted_prices(cls, products, categories, collections, variants):
update_products_discounted_prices_of_catalogues_task.delay(
product_ids=[p.pk for p in products],
category_ids=[c.pk for c in categories],
collection_ids=[c.pk for c in collections],
+ variant_ids=[v.pk for v in variants],
)
@classmethod
@@ -74,8 +81,12 @@ class BaseDiscountCatalogueMutation(BaseMutation):
if collections:
collections = cls.get_nodes_or_error(collections, "collections", Collection)
node.collections.add(*collections)
+ variants = input.get("variants", [])
+ if variants:
+ 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)
+ cls.recalculate_discounted_prices(products, categories, collections, variants)
@classmethod
def clean_product(cls, products):
@@ -105,8 +116,12 @@ class BaseDiscountCatalogueMutation(BaseMutation):
if collections:
collections = cls.get_nodes_or_error(collections, "collections", Collection)
node.collections.remove(*collections)
+ variants = input.get("variants", [])
+ if variants:
+ variants = cls.get_nodes_or_error(variants, "variants", ProductVariant)
+ node.variants.remove(*variants)
# Updated the db entries, recalculating discounts of affected products
- cls.recalculate_discounted_prices(products, categories, collections)
+ cls.recalculate_discounted_prices(products, categories, collections, variants)
class VoucherInput(graphene.InputObjectType):
@@ -127,6 +142,11 @@ class VoucherInput(graphene.InputObjectType):
products = graphene.List(
graphene.ID, description="Products discounted by the voucher.", name="products"
)
+ variants = graphene.List(
+ graphene.ID,
+ description=f"{ADDED_IN_31} Variants discounted by the voucher.",
+ name="variants",
+ )
collections = graphene.List(
graphene.ID,
description="Collections discounted by the voucher.",
@@ -486,6 +506,11 @@ class SaleInput(graphene.InputObjectType):
products = graphene.List(
graphene.ID, description="Products related to the discount.", name="products"
)
+ variants = graphene.List(
+ graphene.ID,
+ descriptions=f"{ADDED_IN_31} Product variant related to the discount.",
+ name="variants",
+ )
categories = graphene.List(
graphene.ID,
description="Categories related to the discount.",
diff --git a/saleor/graphql/discount/tests/benchmark/test_sales.py b/saleor/graphql/discount/tests/benchmark/test_sales.py
index a773a7c4bf..41f3e1d628 100644
--- a/saleor/graphql/discount/tests/benchmark/test_sales.py
+++ b/saleor/graphql/discount/tests/benchmark/test_sales.py
@@ -63,6 +63,13 @@ query GetSales($channel: String){
}
}
}
+ variants(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
channelListings {
id
discountValue
diff --git a/saleor/graphql/discount/tests/benchmark/test_vouchers.py b/saleor/graphql/discount/tests/benchmark/test_vouchers.py
index 84b603d5fb..82e6ce5e73 100644
--- a/saleor/graphql/discount/tests/benchmark/test_vouchers.py
+++ b/saleor/graphql/discount/tests/benchmark/test_vouchers.py
@@ -81,6 +81,13 @@ query GetVouchers($channel: String){
}
}
}
+ variants(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
channelListings {
id
discountValue
diff --git a/saleor/graphql/discount/tests/test_discount.py b/saleor/graphql/discount/tests/test_discount.py
index 99fa2349f6..a49a01a12b 100644
--- a/saleor/graphql/discount/tests/test_discount.py
+++ b/saleor/graphql/discount/tests/test_discount.py
@@ -681,6 +681,7 @@ def test_voucher_add_catalogues(
category,
product,
collection,
+ product_variant_list,
permission_manage_discounts,
):
query = """
@@ -700,12 +701,17 @@ def test_voucher_add_catalogues(
product_id = graphene.Node.to_global_id("Product", product.id)
collection_id = graphene.Node.to_global_id("Collection", collection.id)
category_id = graphene.Node.to_global_id("Category", category.id)
+ variant_ids = [
+ graphene.Node.to_global_id("ProductVariant", variant.id)
+ for variant in product_variant_list
+ ]
variables = {
"id": graphene.Node.to_global_id("Voucher", voucher.id),
"input": {
"products": [product_id],
"collections": [collection_id],
"categories": [category_id],
+ "variants": variant_ids,
},
}
@@ -719,6 +725,7 @@ def test_voucher_add_catalogues(
assert product in voucher.products.all()
assert category in voucher.categories.all()
assert collection in voucher.collections.all()
+ assert set(product_variant_list) == set(voucher.variants.all())
def test_voucher_add_catalogues_with_product_without_variant(
@@ -772,11 +779,13 @@ def test_voucher_remove_catalogues(
category,
product,
collection,
+ product_variant_list,
permission_manage_discounts,
):
voucher.products.add(product)
voucher.collections.add(collection)
voucher.categories.add(category)
+ voucher.variants.add(*product_variant_list)
query = """
mutation voucherCataloguesRemove($id: ID!, $input: CatalogueInput!) {
@@ -795,12 +804,17 @@ def test_voucher_remove_catalogues(
product_id = graphene.Node.to_global_id("Product", product.id)
collection_id = graphene.Node.to_global_id("Collection", collection.id)
category_id = graphene.Node.to_global_id("Category", category.id)
+ variant_ids = [
+ graphene.Node.to_global_id("ProductVariant", variant.id)
+ for variant in product_variant_list
+ ]
variables = {
"id": graphene.Node.to_global_id("Voucher", voucher.id),
"input": {
"products": [product_id],
"collections": [collection_id],
"categories": [category_id],
+ "variants": variant_ids,
},
}
@@ -809,11 +823,13 @@ def test_voucher_remove_catalogues(
)
content = get_graphql_content(response)
data = content["data"]["voucherCataloguesRemove"]
+ voucher_variants = list(voucher.variants.all())
assert not data["errors"]
assert product not in voucher.products.all()
assert category not in voucher.categories.all()
assert collection not in voucher.collections.all()
+ assert not any(v in voucher_variants for v in product_variant_list)
def test_voucher_add_no_catalogues(
@@ -835,7 +851,7 @@ def test_voucher_add_no_catalogues(
"""
variables = {
"id": graphene.Node.to_global_id("Voucher", voucher.id),
- "input": {"products": [], "collections": [], "categories": []},
+ "input": {"products": [], "collections": [], "categories": [], "variants": []},
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_discounts]
@@ -847,6 +863,7 @@ def test_voucher_add_no_catalogues(
assert not voucher.products.exists()
assert not voucher.categories.exists()
assert not voucher.collections.exists()
+ assert not voucher.variants.exists()
def test_voucher_remove_no_catalogues(
@@ -855,11 +872,13 @@ def test_voucher_remove_no_catalogues(
category,
product,
collection,
+ product_variant_list,
permission_manage_discounts,
):
voucher.products.add(product)
voucher.collections.add(collection)
voucher.categories.add(category)
+ voucher.variants.add(*product_variant_list)
query = """
mutation voucherCataloguesAdd($id: ID!, $input: CatalogueInput!) {
@@ -877,7 +896,7 @@ def test_voucher_remove_no_catalogues(
"""
variables = {
"id": graphene.Node.to_global_id("Voucher", voucher.id),
- "input": {"products": [], "collections": [], "categories": []},
+ "input": {"products": [], "collections": [], "categories": [], "variants": []},
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_discounts]
@@ -889,6 +908,7 @@ def test_voucher_remove_no_catalogues(
assert voucher.products.exists()
assert voucher.categories.exists()
assert voucher.collections.exists()
+ assert voucher.variants.exists()
def test_create_sale(staff_api_client, permission_manage_discounts):
@@ -1039,7 +1059,13 @@ def test_sale_delete_mutation(staff_api_client, sale, permission_manage_discount
def test_sale_add_catalogues(
- staff_api_client, sale, category, product, collection, permission_manage_discounts
+ staff_api_client,
+ sale,
+ category,
+ product,
+ collection,
+ product_variant_list,
+ permission_manage_discounts,
):
query = """
mutation saleCataloguesAdd($id: ID!, $input: CatalogueInput!) {
@@ -1058,12 +1084,17 @@ def test_sale_add_catalogues(
product_id = graphene.Node.to_global_id("Product", product.id)
collection_id = graphene.Node.to_global_id("Collection", collection.id)
category_id = graphene.Node.to_global_id("Category", category.id)
+ variant_ids = [
+ graphene.Node.to_global_id("ProductVariant", variant.id)
+ for variant in product_variant_list
+ ]
variables = {
"id": graphene.Node.to_global_id("Sale", sale.id),
"input": {
"products": [product_id],
"collections": [collection_id],
"categories": [category_id],
+ "variants": variant_ids,
},
}
@@ -1077,6 +1108,7 @@ def test_sale_add_catalogues(
assert product in sale.products.all()
assert category in sale.categories.all()
assert collection in sale.collections.all()
+ assert set(product_variant_list) == set(sale.variants.all())
def test_sale_add_catalogues_with_product_without_variants(
@@ -1100,6 +1132,7 @@ def test_sale_add_catalogues_with_product_without_variants(
product_id = graphene.Node.to_global_id("Product", product.id)
collection_id = graphene.Node.to_global_id("Collection", collection.id)
category_id = graphene.Node.to_global_id("Category", category.id)
+
variables = {
"id": graphene.Node.to_global_id("Sale", sale.id),
"input": {
@@ -1120,11 +1153,18 @@ def test_sale_add_catalogues_with_product_without_variants(
def test_sale_remove_catalogues(
- staff_api_client, sale, category, product, collection, permission_manage_discounts
+ staff_api_client,
+ sale,
+ category,
+ product,
+ collection,
+ product_variant_list,
+ permission_manage_discounts,
):
sale.products.add(product)
sale.collections.add(collection)
sale.categories.add(category)
+ sale.variants.add(*product_variant_list)
query = """
mutation saleCataloguesRemove($id: ID!, $input: CatalogueInput!) {
@@ -1143,12 +1183,17 @@ def test_sale_remove_catalogues(
product_id = graphene.Node.to_global_id("Product", product.id)
collection_id = graphene.Node.to_global_id("Collection", collection.id)
category_id = graphene.Node.to_global_id("Category", category.id)
+ variant_ids = [
+ graphene.Node.to_global_id("ProductVariant", variant.id)
+ for variant in product_variant_list
+ ]
variables = {
"id": graphene.Node.to_global_id("Sale", sale.id),
"input": {
"products": [product_id],
"collections": [collection_id],
"categories": [category_id],
+ "variants": variant_ids,
},
}
@@ -1157,11 +1202,13 @@ def test_sale_remove_catalogues(
)
content = get_graphql_content(response)
data = content["data"]["saleCataloguesRemove"]
+ product_variants = list(sale.variants.all())
assert not data["errors"]
assert product not in sale.products.all()
assert category not in sale.categories.all()
assert collection not in sale.collections.all()
+ assert not any(v in product_variants for v in product_variant_list)
def test_sale_add_no_catalogues(
@@ -1183,7 +1230,7 @@ def test_sale_add_no_catalogues(
"""
variables = {
"id": graphene.Node.to_global_id("Sale", new_sale.id),
- "input": {"products": [], "collections": [], "categories": []},
+ "input": {"products": [], "collections": [], "categories": [], "variants": []},
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_discounts]
@@ -1195,14 +1242,22 @@ def test_sale_add_no_catalogues(
assert not new_sale.products.exists()
assert not new_sale.categories.exists()
assert not new_sale.collections.exists()
+ assert not new_sale.variants.exists()
def test_sale_remove_no_catalogues(
- staff_api_client, sale, category, product, collection, permission_manage_discounts
+ staff_api_client,
+ sale,
+ category,
+ product,
+ collection,
+ product_variant_list,
+ permission_manage_discounts,
):
sale.products.add(product)
sale.collections.add(collection)
sale.categories.add(category)
+ sale.variants.add(*product_variant_list)
query = """
mutation saleCataloguesAdd($id: ID!, $input: CatalogueInput!) {
@@ -1220,7 +1275,7 @@ def test_sale_remove_no_catalogues(
"""
variables = {
"id": graphene.Node.to_global_id("Sale", sale.id),
- "input": {"products": [], "collections": [], "categories": []},
+ "input": {"products": [], "collections": [], "categories": [], "variants": []},
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_discounts]
@@ -1232,6 +1287,7 @@ def test_sale_remove_no_catalogues(
assert sale.products.exists()
assert sale.categories.exists()
assert sale.collections.exists()
+ assert sale.variants.exists()
@pytest.mark.parametrize(
diff --git a/saleor/graphql/discount/types.py b/saleor/graphql/discount/types.py
index 4d9c9440b4..f69ce55261 100644
--- a/saleor/graphql/discount/types.py
+++ b/saleor/graphql/discount/types.py
@@ -11,6 +11,7 @@ from ..channel.types import (
)
from ..core import types
from ..core.connection import CountableDjangoObjectType
+from ..core.descriptions import ADDED_IN_31
from ..core.fields import (
ChannelContextFilterConnectionField,
ChannelQsContext,
@@ -20,7 +21,7 @@ from ..core.scalars import PositiveDecimal
from ..core.types import Money
from ..decorators import permission_required
from ..meta.types import ObjectWithMetadata
-from ..product.types import Category, Collection, Product
+from ..product.types import Category, Collection, Product, ProductVariant
from ..translations.fields import TranslationField
from ..translations.types import SaleTranslation, VoucherTranslation
from .dataloaders import (
@@ -54,6 +55,10 @@ class Sale(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
products = ChannelContextFilterConnectionField(
Product, description="List of products this sale applies to."
)
+ variants = ChannelContextFilterConnectionField(
+ ProductVariant,
+ description=f"{ADDED_IN_31} List of product variants this sale applies to.",
+ )
translation = TranslationField(
SaleTranslation,
type_name="sale",
@@ -97,6 +102,12 @@ class Sale(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
qs = root.node.products.all()
return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
+ @staticmethod
+ @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
+ def resolve_variants(root: ChannelContext[models.Sale], info, **_kwargs):
+ qs = root.node.variants.all()
+ return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
+
@staticmethod
def resolve_discount_value(root: ChannelContext[models.Sale], info, **_kwargs):
if not root.channel_slug:
@@ -150,6 +161,10 @@ class Voucher(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
products = ChannelContextFilterConnectionField(
Product, description="List of products this voucher applies to."
)
+ variants = ChannelContextFilterConnectionField(
+ ProductVariant,
+ description=f"{ADDED_IN_31} List of product variants this voucher applies to.",
+ )
countries = graphene.List(
types.CountryDisplay,
description="List of countries available for the shipping voucher.",
@@ -217,6 +232,12 @@ class Voucher(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
qs = root.node.products.all()
return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
+ @staticmethod
+ @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
+ def resolve_variants(root: ChannelContext[models.Voucher], info, **_kwargs):
+ qs = root.node.variants.all()
+ return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
+
@staticmethod
def resolve_countries(root: ChannelContext[models.Voucher], *_args, **_kwargs):
return [
diff --git a/saleor/graphql/product/tests/test_product_discounted_price.py b/saleor/graphql/product/tests/test_product_discounted_price.py
index 2bfc8a4269..f1bf860830 100644
--- a/saleor/graphql/product/tests/test_product_discounted_price.py
+++ b/saleor/graphql/product/tests/test_product_discounted_price.py
@@ -315,6 +315,7 @@ def test_sale_add_catalogues_updates_products_discounted_prices(
product,
category,
collection,
+ product_variant_list,
permission_manage_discounts,
):
query = """
@@ -334,12 +335,16 @@ def test_sale_add_catalogues_updates_products_discounted_prices(
product_id = to_global_id("Product", product.pk)
collection_id = to_global_id("Collection", collection.pk)
category_id = to_global_id("Category", category.pk)
+ variant_ids = [
+ to_global_id("ProductVariant", variant.pk) for variant in product_variant_list
+ ]
variables = {
"id": sale_id,
"input": {
"products": [product_id],
"collections": [collection_id],
"categories": [category_id],
+ "variants": variant_ids,
},
}
@@ -355,6 +360,7 @@ def test_sale_add_catalogues_updates_products_discounted_prices(
product_ids=[product.pk],
category_ids=[category.pk],
collection_ids=[collection.pk],
+ variant_ids=[variant.pk for variant in product_variant_list],
)
@@ -369,11 +375,16 @@ def test_sale_remove_catalogues_updates_products_discounted_prices(
product,
category,
collection,
+ product_variant_list,
permission_manage_discounts,
):
assert product in sale.products.all()
assert category in sale.categories.all()
assert collection in sale.collections.all()
+
+ sale.variants.add(*product_variant_list)
+
+ assert all(variant in sale.variants.all() for variant in product_variant_list)
query = """
mutation SaleCataloguesRemove($id: ID!, $input: CatalogueInput!) {
saleCataloguesRemove(id: $id, input: $input) {
@@ -391,12 +402,16 @@ def test_sale_remove_catalogues_updates_products_discounted_prices(
product_id = to_global_id("Product", product.pk)
collection_id = to_global_id("Collection", collection.pk)
category_id = to_global_id("Category", category.pk)
+ variant_ids = [
+ to_global_id("ProductVariant", variant.pk) for variant in product_variant_list
+ ]
variables = {
"id": sale_id,
"input": {
"products": [product_id],
"collections": [collection_id],
"categories": [category_id],
+ "variants": variant_ids,
},
}
@@ -412,4 +427,5 @@ def test_sale_remove_catalogues_updates_products_discounted_prices(
product_ids=[product.pk],
category_ids=[category.pk],
collection_ids=[collection.pk],
+ variant_ids=[variant.pk for variant in product_variant_list],
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index eef49c3c65..ae2194c021 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -802,6 +802,7 @@ input CatalogueInput {
products: [ID]
categories: [ID]
collections: [ID]
+ variants: [ID]
}
type Category implements Node & ObjectWithMetadata {
@@ -5906,6 +5907,7 @@ type Sale implements Node & ObjectWithMetadata {
categories(before: String, after: String, first: Int, last: Int): CategoryCountableConnection
collections(before: String, after: String, first: Int, last: Int): CollectionCountableConnection
products(before: String, after: String, first: Int, last: Int): ProductCountableConnection
+ variants(before: String, after: String, first: Int, last: Int): ProductVariantCountableConnection
translation(languageCode: LanguageCodeEnum!): SaleTranslation
channelListings: [SaleChannelListing!]
discountValue: Float
@@ -5983,6 +5985,7 @@ input SaleInput {
type: DiscountValueTypeEnum
value: PositiveDecimal
products: [ID]
+ variants: [ID]
categories: [ID]
collections: [ID]
startDate: DateTime
@@ -6864,6 +6867,7 @@ type Voucher implements Node & ObjectWithMetadata {
categories(before: String, after: String, first: Int, last: Int): CategoryCountableConnection
collections(before: String, after: String, first: Int, last: Int): CollectionCountableConnection
products(before: String, after: String, first: Int, last: Int): ProductCountableConnection
+ variants(before: String, after: String, first: Int, last: Int): ProductVariantCountableConnection
countries: [CountryDisplay]
translation(languageCode: LanguageCodeEnum!): VoucherTranslation
discountValue: Float
@@ -6955,6 +6959,7 @@ input VoucherInput {
endDate: DateTime
discountValueType: DiscountValueTypeEnum
products: [ID]
+ variants: [ID]
collections: [ID]
categories: [ID]
minCheckoutItemsQuantity: Int
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 6484d10c6a..94eca323a4 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -571,12 +571,14 @@ class ProductVariant(SortableModel, ModelWithMetadata):
channel_listing: "ProductVariantChannelListing",
discounts: Optional[Iterable[DiscountInfo]] = None,
) -> "Money":
+
return calculate_discounted_price(
product=product,
price=channel_listing.price,
discounts=discounts,
collections=collections,
channel=channel,
+ variant_id=self.id,
)
def get_weight(self):
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index b25b514d24..acc2f6163d 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -65,9 +65,10 @@ def update_products_discounted_prices_of_catalogues_task(
product_ids: Optional[List[int]] = None,
category_ids: Optional[List[int]] = None,
collection_ids: Optional[List[int]] = None,
+ variant_ids: Optional[List[int]] = None,
):
update_products_discounted_prices_of_catalogues(
- product_ids, category_ids, collection_ids
+ product_ids, category_ids, collection_ids, variant_ids
)
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index 7eef8b87be..4924a2df02 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -99,6 +99,7 @@ def get_variant_price(
collections=collections,
discounts=discounts,
channel=channel,
+ variant_id=variant.id,
)
diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.py
index 4ccff93243..7330d28269 100644
--- a/saleor/product/utils/variant_prices.py
+++ b/saleor/product/utils/variant_prices.py
@@ -73,7 +73,7 @@ def update_products_discounted_prices(products, discounts=None):
def update_products_discounted_prices_of_catalogues(
- product_ids=None, category_ids=None, collection_ids=None
+ product_ids=None, category_ids=None, collection_ids=None, variant_ids=None
):
# Building the matching products query
q_list = []
@@ -84,6 +84,8 @@ def update_products_discounted_prices_of_catalogues(
if collection_ids:
q_list.append(Q(collectionproduct__collection_id__in=collection_ids))
# Asserting that the function was called with some ids
+ 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)
@@ -97,4 +99,5 @@ def update_products_discounted_prices_of_discount(discount):
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),
)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 984f637ae9..4f5d189dac 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -3644,6 +3644,7 @@ def discount_info(category, collection, sale, channel_USD):
product_ids=set(),
category_ids={category.id}, # assumes this category does not have children
collection_ids={collection.id},
+ variants_ids=set(),
)