Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Implement price prior to promotion (for EU Omnibus Directive) (#17202)
delemeator34c345c14fd8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eaefe8c79b..196381dc4b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,6 +30,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add `productVariants` field to `Product` instead of `variants`. Mark `Product.variants` as deprecated - #16998 by @kadewu- Fix checkout `line.undiscountedTotalPrice` and `line.undiscountedUnitPrice` calculation. - #17193 by @IKarbowiak- Return the normalized price in case the checkout prices are not expired, otherwise fetch the price from variant channel listing.+- Add prior price fields to `VariantPricingInfo`, `ProductPricingInfo` and `CheckoutLine` - #17202 by @delemeator- Fix undiscounted price taxation inside an order calculations when the Avatax plugin is used - #17253 by @zedzior### Webhooksdiff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex 32d418c0b0..6db52be724 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -298,6 +298,23 @@ def update_undiscounted_unit_price_for_lines(lines: Iterable["CheckoutLineInfo"]line_info.line.undiscounted_unit_price = line_info.undiscounted_unit_price+def update_prior_unit_price_for_lines(lines: Iterable["CheckoutLineInfo"]):+ """Update line prior unit price amount.++ Prior unit price stores the price of the variant before promotion.+ """+ for line_info in lines:+ listing = line_info.channel_listing+ if not listing:+ continue++ # Updating amount instead of Money to avoid overriding currency with None+ if listing.prior_price_amount is None:+ line_info.line.prior_unit_price_amount = None+ else:+ line_info.line.prior_unit_price_amount = line_info.prior_unit_price_amount++def _fetch_checkout_prices_if_expired(checkout_info: "CheckoutInfo",manager: "PluginsManager",@@ -340,6 +357,7 @@ def _fetch_checkout_prices_if_expired(lines = cast(list, lines)update_undiscounted_unit_price_for_lines(lines)+ update_prior_unit_price_for_lines(lines)create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines, database_connection_name@@ -439,6 +457,7 @@ def _fetch_checkout_prices_if_expired("total_price_gross_amount","tax_rate","undiscounted_unit_price_amount",+ "prior_unit_price_amount",],)return checkout_info, linesdiff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 8e68f69b29..64aa94247f 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -1,6 +1,7 @@import itertoolsfrom collections.abc import Iterablefrom dataclasses import dataclass, field+from decimal import Decimalfrom functools import cached_property, singledispatchfrom typing import TYPE_CHECKING, Any, Optional, Unionfrom uuid import UUID@@ -89,6 +90,13 @@ class CheckoutLineInfo(LineInfo):)return self.line.undiscounted_unit_price+ @cached_property+ def prior_unit_price_amount(self) -> Decimal | None:+ """Provide prior unit price."""+ if self.channel_listing and self.channel_listing.price is not None:+ return self.variant.get_prior_price_amount(self.channel_listing)+ return self.line.prior_unit_price_amount+@dataclassclass CheckoutInfo:diff --git a/saleor/checkout/migrations/0074_checkoutline_prior_unit_price_amount.py b/saleor/checkout/migrations/0074_checkoutline_prior_unit_price_amount.pynew file mode 100644index 0000000000..9f0299dc05--- /dev/null+++ b/saleor/checkout/migrations/0074_checkoutline_prior_unit_price_amount.py@@ -0,0 +1,19 @@+# Generated by Django 4.2.16 on 2024-12-22 11:53++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0073_merge_20241107_1646"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkoutline",+ name="prior_unit_price_amount",+ field=models.DecimalField(+ blank=True, decimal_places=3, max_digits=12, null=True+ ),+ ),+ ]diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex 89259af802..c99820f0fe 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -313,6 +313,17 @@ class CheckoutLine(ModelWithMetadata):currency_field="currency",)+ prior_unit_price_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ blank=True,+ null=True,+ )++ prior_unit_price = MoneyField(+ amount_field="prior_unit_price_amount", currency_field="currency"+ )+total_price_net_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,diff --git a/saleor/checkout/tests/fixtures/checkout_with_discount.py b/saleor/checkout/tests/fixtures/checkout_with_discount.pyindex 12f5ee1e24..e7d920f3d3 100644--- a/saleor/checkout/tests/fixtures/checkout_with_discount.py+++ b/saleor/checkout/tests/fixtures/checkout_with_discount.py@@ -22,6 +22,8 @@ def checkout_with_item_on_promotion(checkout_with_item):variant = line.variantreward_value = Decimal("5")+ reward_value_prior = Decimal("2")+rule = promotion.rules.create(catalogue_predicate={"productPredicate": {@@ -38,7 +40,12 @@ def checkout_with_item_on_promotion(checkout_with_item):variant_channel_listing.discounted_price_amount = (variant_channel_listing.price_amount - reward_value)- variant_channel_listing.save(update_fields=["discounted_price_amount"])+ variant_channel_listing.prior_price_amount = (+ variant_channel_listing.price_amount - reward_value_prior+ )+ variant_channel_listing.save(+ update_fields=["discounted_price_amount", "prior_price_amount"]+ )variant_channel_listing.variantlistingpromotionrule.create(promotion_rule=rule,diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.pyindex db0df00ede..4fdc178245 100644--- a/saleor/checkout/tests/test_calculations.py+++ b/saleor/checkout/tests/test_calculations.py@@ -23,6 +23,7 @@ from ...plugins.avatax.plugin import AvataxPluginfrom ...plugins.avatax.tests.conftest import plugin_configuration # noqa: F401from ...plugins.manager import get_plugins_managerfrom ...plugins.tests.sample_plugins import PluginSample+from ...product.models import ProductVariantChannelListingfrom ...tax import TaxCalculationStrategyfrom ...tax.calculations.checkout import update_checkout_prices_with_flat_ratesfrom ..base_calculations import (@@ -1030,3 +1031,74 @@ def test_fetch_order_data_plugin_tax_data_price_overflow(assert checkout.tax_error == TaxDataErrorMessage.OVERFLOWassert TaxDataErrorMessage.OVERFLOW in caplog.textassert caplog.records[0].checkout_id == to_global_id_or_none(checkout)+++def test_fetch_checkout_with_prior_price_change(+ fetch_kwargs,+ checkout_with_items,+):+ # given+ checkout_with_items.price_expiration = timezone.now()+ checkout_with_items.save(update_fields=["price_expiration"])+ line = checkout_with_items.lines.first()+ listing = ProductVariantChannelListing.objects.filter(+ variant=line.variant, channel=checkout_with_items.channel+ ).first()+ new_prior_price_amount = Decimal(7)+ assert listing is not None+ assert listing.prior_price_amount != new_prior_price_amount+ listing.prior_price_amount = new_prior_price_amount+ listing.save(update_fields=["prior_price_amount"])++ manager = get_plugins_manager(allow_replica=False)+ lines_info, _ = fetch_checkout_lines(checkout_with_items)++ fetch_kwargs = {+ "checkout_info": fetch_checkout_info(checkout_with_items, lines_info, manager),+ "manager": manager,+ "lines": lines_info,+ "address": checkout_with_items.shipping_address+ or checkout_with_items.billing_address,+ }++ # when+ fetch_checkout_data(**fetch_kwargs)++ # then+ line.refresh_from_db()+ assert line.prior_unit_price_amount == new_prior_price_amount+++def test_fetch_checkout_with_prior_price_none(+ fetch_kwargs,+ checkout_with_items,+):+ # given+ checkout_with_items.price_expiration = timezone.now()+ checkout_with_items.save(update_fields=["price_expiration"])+ line = checkout_with_items.lines.first()+ listing = ProductVariantChannelListing.objects.filter(+ variant=line.variant, channel=checkout_with_items.channel+ ).first()+ assert listing is not None+ listing.prior_price_amount = None+ listing.save(update_fields=["prior_price_amount"])++ manager = get_plugins_manager(allow_replica=False)+ lines_info, _ = fetch_checkout_lines(checkout_with_items)++ fetch_kwargs = {+ "checkout_info": fetch_checkout_info(checkout_with_items, lines_info, manager),+ "manager": manager,+ "lines": lines_info,+ "address": checkout_with_items.shipping_address+ or checkout_with_items.billing_address,+ }++ # when+ fetch_checkout_data(**fetch_kwargs)++ # then+ line.refresh_from_db()+ assert line.prior_unit_price_amount is None+ assert line.currency is not Nonediff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex d15b48be0b..dcc2df5c2a 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -234,6 +234,7 @@ def add_variant_to_checkout(variant_price_amount = variant.get_base_price(variant_channel_listing, price_override).amount+ variant_prior_price_amount = variant.get_prior_price_amount(variant_channel_listing)new_quantity, line = check_variant_in_stock(checkout,@@ -250,6 +251,7 @@ def add_variant_to_checkout(quantity=quantity,price_override=price_override,undiscounted_unit_price_amount=variant_price_amount,+ prior_unit_price_amount=variant_prior_price_amount,)return checkout@@ -266,6 +268,7 @@ def add_variant_to_checkout(currency=checkout.currency,price_override=price_override,undiscounted_unit_price_amount=variant_price_amount,+ prior_unit_price_amount=variant_prior_price_amount,)elif new_quantity > 0:line.quantity = new_quantity@@ -418,9 +421,11 @@ def _append_line_to_create(new_variant_listing_map: dict[int, "product_models.ProductVariantChannelListing"],):if line_data.quantity > 0:+ variant_listing = new_variant_listing_map.get(variant.id)variant_price_amount = variant.get_base_price(- new_variant_listing_map.get(variant.id), line_data.custom_price+ variant_listing, line_data.custom_price).amount+ variant_prior_price_amount = variant.get_prior_price_amount(variant_listing)checkout_line = CheckoutLine(checkout=checkout,variant=variant,@@ -428,6 +433,7 @@ def _append_line_to_create(currency=checkout.currency,price_override=line_data.custom_price,undiscounted_unit_price_amount=variant_price_amount,+ prior_unit_price_amount=variant_prior_price_amount,)if line_data.metadata_list:checkout_line.store_value_in_metadata(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex 986e3127fa..f6b5ab0a33 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -61,6 +61,12 @@ mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {undiscountedUnitPrice {amount}+ priorTotalPrice {+ amount+ }+ priorUnitPrice {+ amount+ }quantityvariant {id@@ -2008,3 +2014,35 @@ def test_checkout_lines_add_when_line_deleted(user_api_client, checkout_with_ite).first()assert newly_created_checkout_lineassert newly_created_checkout_line.id != line.id+++def test_checkout_lines_add_with_prior_price(+ user_api_client,+ checkout,+ stock,+):+ # given+ variant = stock.product_variant+ variant_channel_listing = variant.channel_listings.first()++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 2}],+ "channelSlug": variant_channel_listing.channel.slug,+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # then+ checkout = get_graphql_content(response)["data"]["checkoutLinesAdd"]["checkout"]+ assert (+ checkout["lines"][0]["priorUnitPrice"]["amount"]+ == variant_channel_listing.prior_price_amount+ )+ assert (+ checkout["lines"][0]["priorTotalPrice"]["amount"]+ == variant_channel_listing.prior_price_amount * 2+ )diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex fb3d320ae2..5af5de7941 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -1776,6 +1776,16 @@ query getCheckout($id: ID) {amount}}+ priceUndiscounted {+ gross {+ amount+ }+ }+ pricePrior {+ gross {+ amount+ }+ }}product {id@@ -1788,6 +1798,11 @@ query getCheckout($id: ID) {amount}}+ discountPrior {+ gross{+ amount+ }+ }priceRange{start{gross{@@ -1812,6 +1827,18 @@ query getCheckout($id: ID) {}}}+ priceRangePrior{+ start{+ gross{+ amount+ }+ }+ stop{+ gross{+ amount+ }+ }+ }}}}@@ -1824,6 +1851,10 @@ query getCheckout($id: ID) {amountcurrency}+ priorUnitPrice {+ amount+ currency+ }totalPrice {currencygross {@@ -1834,6 +1865,10 @@ query getCheckout($id: ID) {amountcurrency}+ priorTotalPrice {+ amount+ currency+ }problems {... on CheckoutLineProblemVariantNotAvailable {__typename@@ -2170,6 +2205,14 @@ def test_checkout_prices_with_promotion()assert line_total_price.gross.amount < undiscounted_total_price+ assert data["lines"][0]["priorUnitPrice"] is not None+ prior_unit_price_amount = (+ line_info.variant.get_prior_price_amount(line_info.channel_listing) or 0+ )+ prior_total_price = prior_unit_price_amount * line_info.line.quantity+ assert data["lines"][0]["priorUnitPrice"]["amount"] == prior_unit_price_amount+ assert data["lines"][0]["priorTotalPrice"]["amount"] == prior_total_price+@pytest.mark.parametrize(("channel_listing_model", "listing_filter_field"),diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 37fcd2d61b..104da899d9 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -9,6 +9,7 @@ from ...checkout import calculations, models, problemsfrom ...checkout.calculations import fetch_checkout_datafrom ...checkout.utils import get_valid_collection_points_for_checkoutfrom ...core.db.connection import allow_writer_in_context+from ...core.prices import quantize_pricefrom ...core.taxes import zero_money, zero_taxed_moneyfrom ...graphql.core.context import get_database_connection_namefrom ...payment.interface import ListStoredPaymentMethodsRequestData@@ -215,6 +216,11 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):description="The unit price of the checkout line, without discounts.",required=True,)+ prior_unit_price = graphene.Field(+ Money,+ description="The unit price of the checkout line prior to promotion."+ + ADDED_IN_321,+ )total_price = BaseField(TaxedMoney,description="The sum of the checkout line price, taxes and discounts.",@@ -231,6 +237,11 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):description="The sum of the checkout line price, without discounts.",required=True,)+ prior_total_price = graphene.Field(+ Money,+ description="The sum of the checkout line price prior to promotion."+ + ADDED_IN_321,+ )requires_shipping = graphene.Boolean(description="Indicates whether the item need to be delivered.",required=True,@@ -422,6 +433,19 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):.then(with_checkout))+ @staticmethod+ def resolve_prior_total_price(+ root: models.CheckoutLine, info: ResolveInfo+ ) -> Money | None:+ if root.prior_unit_price is None:+ return None++ quantized_amount = quantize_price(+ root.prior_unit_price.amount * root.quantity, root.currency+ )++ return Money(amount=quantized_amount, currency=root.currency)+@staticmethoddef resolve_requires_shipping(root: models.CheckoutLine, info: ResolveInfo):def is_shipping_required(product_type):diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.pyindex 3a43655e80..329fa6bcab 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py@@ -360,6 +360,7 @@ class ProductVariantBulkCreate(BaseMutation):cls,price,cost_price,+ prior_price,currency_code,channel_id,variant_index,@@ -390,6 +391,17 @@ class ProductVariantBulkCreate(BaseMutation):index_error_map,path_prefix,)+ clean_price(+ prior_price,+ "prior_price",+ currency_code,+ channel_id,+ variant_index,+ listing_index,+ errors,+ index_error_map,+ path_prefix,+ )@classmethoddef clean_channel_listings(@@ -469,11 +481,13 @@ class ProductVariantBulkCreate(BaseMutation):]price = channel_listing.get("price")cost_price = channel_listing.get("cost_price")+ prior_price = channel_listing.get("prior_price")currency_code = channel_listing["channel"].currency_codecls.clean_prices(price,cost_price,+ prior_price,currency_code,channel_id,variant_index,@@ -810,6 +824,7 @@ class ProductVariantBulkCreate(BaseMutation):# value will be calculated asynchronously in the celery taskdiscounted_price_amount=listing_data["price"],cost_price_amount=listing_data.get("cost_price"),+ prior_price_amount=listing_data.get("prior_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_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.pyindex af88048052..a6e90f5f8c 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py@@ -64,6 +64,7 @@ class ChannelListingUpdateInput(BaseInputObjectType):channel_listing = graphene.ID(required=True, description="ID of a channel listing.")price = PositiveDecimal(description="Price of the particular variant in channel.")cost_price = PositiveDecimal(description="Cost price of the variant in channel.")+ prior_price = PositiveDecimal(description="Price of the variant before discount.")preorder_threshold = graphene.Int(description="The threshold for preorder variant in channel.")@@ -174,6 +175,7 @@ class ProductVariantBulkUpdate(BaseMutation):cls,price,cost_price,+ prior_price,currency_code,channel_id,variant_index,@@ -203,6 +205,17 @@ class ProductVariantBulkUpdate(BaseMutation):index_error_map,path_prefix,)+ clean_price(+ prior_price,+ "prior_price",+ currency_code,+ channel_id,+ variant_index,+ listing_index,+ None,+ index_error_map,+ path_prefix,+ )@classmethoddef clean_channel_listings(@@ -243,6 +256,7 @@ class ProductVariantBulkUpdate(BaseMutation):channel_listing = listings_global_id_to_instance_map[listing_id]price = listing_data.get("price")cost_price = listing_data.get("cost_price")+ prior_price = listing_data.get("prior_price")currency_code = channel_listing.currencychannel_id = channel_listing.channel_iderrors_count_before_prices = len(index_error_map[variant_index])@@ -250,6 +264,7 @@ class ProductVariantBulkUpdate(BaseMutation):cls.clean_prices(price,cost_price,+ prior_price,currency_code,channel_id,variant_index,@@ -610,6 +625,7 @@ class ProductVariantBulkUpdate(BaseMutation):# value will be calculated asynchronously in the celery taskdiscounted_price_amount=listing_data["price"],cost_price_amount=listing_data.get("cost_price"),+ prior_price_amount=listing_data.get("prior_price"),currency=listing_data["channel"].currency_code,preorder_quantity_threshold=listing_data.get("preorder_threshold"),)@@ -630,6 +646,8 @@ class ProductVariantBulkUpdate(BaseMutation):listing.discounted_price_amount = listing_data["price"]if "cost_price" in listing_data:listing.cost_price_amount = listing_data["cost_price"]+ if "prior_price" in listing_data:+ listing.prior_price_amount = listing_data["prior_price"]listings_to_update.append(listing)@classmethod@@ -700,6 +718,7 @@ class ProductVariantBulkUpdate(BaseMutation):"price_amount","discounted_price_amount","cost_price_amount",+ "prior_price_amount","preorder_quantity_threshold",],)diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.pyindex ac3f5616db..5f396fc1ed 100644--- a/saleor/graphql/product/mutations/channels.py+++ b/saleor/graphql/product/mutations/channels.py@@ -22,7 +22,7 @@ from ...channel import ChannelContextfrom ...channel.mutations import BaseChannelListingMutationfrom ...channel.types import Channelfrom ...core import ResolveInfo-from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.descriptions import ADDED_IN_321, DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.mutations import BaseMutationfrom ...core.scalars import Date, DateTime, PositiveDecimal@@ -386,6 +386,11 @@ class ProductVariantChannelListingAddInput(BaseInputObjectType):required=True, description="Price of the particular variant in channel.")cost_price = PositiveDecimal(description="Cost price of the variant in channel.")+ prior_price = PositiveDecimal(+ description="Previous price of the variant in channel. Useful for providing "+ "promotion information required by customer protection laws such as EU Omnibus "+ "directive." + ADDED_IN_321+ )preorder_threshold = graphene.Int(description="The threshold for preorder variant in channel.")@@ -496,11 +501,15 @@ class ProductVariantChannelListingUpdate(BaseMutation):for channel_listing_data in cleaned_input:price = channel_listing_data.get("price")cost_price = channel_listing_data.get("cost_price")+ prior_price = channel_listing_data.get("prior_price")channel_id = channel_listing_data["channel_id"]currency_code = channel_listing_data["channel"].currency_codecls.clean_price(price, "price", currency_code, channel_id, errors)cls.clean_price(cost_price, "cost_price", currency_code, channel_id, errors)+ cls.clean_price(+ prior_price, "prior_price", currency_code, channel_id, errors+ )return cleaned_input@@ -521,6 +530,10 @@ class ProductVariantChannelListingUpdate(BaseMutation):defaults["cost_price_amount"] = channel_listing_data.get("cost_price", None)+ if "prior_price" in channel_listing_data.keys():+ defaults["prior_price_amount"] = channel_listing_data.get(+ "prior_price", None+ )if "preorder_threshold" in channel_listing_data.keys():defaults["preorder_quantity_threshold"] = channel_listing_data.get("preorder_threshold", Nonediff --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 1b7958ad60..0c73bfe6ff 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@@ -63,6 +63,10 @@ PRODUCT_VARIANT_BULK_UPDATE_MUTATION = """currencyamount}+ priorPrice {+ currency+ amount+ }preorderThreshold {quantity}@@ -838,3 +842,72 @@ def test_generate_pre_save_payloads(pre_save_payload = mocked_call_event.call_args[1]["pre_save_payloads"]assert payload_key in pre_save_payloadassert request_time.isoformat() == pre_save_payload[payload_key]["issuedAt"]+++def test_product_variant_bulk_update_channel_listings_input_with_prior_price(+ staff_api_client,+ variant,+ permission_manage_products,+ channel_PLN,+):+ # given++ product = variant.product+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ ProductChannelListing.objects.create(product=product, channel=channel_PLN)+ existing_variant_listing = variant.channel_listings.get()++ assert variant.channel_listings.count() == 1+ product_id = graphene.Node.to_global_id("Product", product.pk)++ new_price_for_existing_variant_listing = 50.0+ new_prior_price_for_existing_variant_listing = 42.0+ not_existing_variant_listing_price = 20.0+ not_existing_variant_listing_prior_price = 24.0++ variants = [+ {+ "id": variant_id,+ "channelListings": {+ "update": [+ {+ "price": new_price_for_existing_variant_listing,+ "priorPrice": new_prior_price_for_existing_variant_listing,+ "channelListing": graphene.Node.to_global_id(+ "ProductVariantChannelListing", existing_variant_listing.id+ ),+ }+ ],+ "create": [+ {+ "price": not_existing_variant_listing_price,+ "priorPrice": not_existing_variant_listing_prior_price,+ "channelId": graphene.Node.to_global_id(+ "Channel", channel_PLN.pk+ ),+ }+ ],+ },+ },+ ]++ # when+ variables = {"productId": product_id, "variants": variants}+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables+ )+ get_graphql_content(response, ignore_errors=True)++ # then+ existing_variant_listing.refresh_from_db()+ assert (+ existing_variant_listing.prior_price_amount+ == new_prior_price_for_existing_variant_listing+ )+ new_variant_listing = variant.channel_listings.get(channel=channel_PLN)+ assert (+ new_variant_listing.prior_price_amount+ == not_existing_variant_listing_prior_price+ )diff --git a/saleor/graphql/product/tests/test_product_pricing.py b/saleor/graphql/product/tests/test_product_pricing.pyindex 184ab08700..6c89cd5b8a 100644--- a/saleor/graphql/product/tests/test_product_pricing.py+++ b/saleor/graphql/product/tests/test_product_pricing.py@@ -44,6 +44,14 @@ FRAGMENT_PRICING = (...Price}}+ priceRangePrior {+ start {+ ...Price+ }+ stop {+ ...Price+ }+ }}"""+ FRAGMENT_PRICEdiff --git a/saleor/graphql/product/tests/test_product_prior_price.py b/saleor/graphql/product/tests/test_product_prior_price.pynew file mode 100644index 0000000000..dd42b4db02--- /dev/null+++ b/saleor/graphql/product/tests/test_product_prior_price.py@@ -0,0 +1,41 @@+import graphene++from ...tests.utils import get_graphql_content+++def test_product_prior_price(api_client, product, channel_USD):+ # given+ query = """+ query ProductWithPriorPrice($id: ID!, $channel: String!) {+ product(id: $id, channel: $channel) {+ pricing {+ priceRangePrior {+ start {+ gross {+ amount+ currency+ }+ }+ }+ }+ }+ }+ """+ variant = product.variants.first()+ variables = {+ "id": graphene.Node.to_global_id("Product", product.id),+ "channel": channel_USD.slug,+ }++ # when+ response = api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["product"]+ price_range = data["pricing"]["priceRangePrior"]+ assert price_range is not None+ assert (+ price_range["start"]["gross"]["amount"]+ == variant.channel_listings.first().prior_price_amount+ )diff --git a/saleor/graphql/product/tests/test_variant_channel_listing_update.py b/saleor/graphql/product/tests/test_variant_channel_listing_update.pyindex 20f8749c68..75b0d30d71 100644--- a/saleor/graphql/product/tests/test_variant_channel_listing_update.py+++ b/saleor/graphql/product/tests/test_variant_channel_listing_update.py@@ -1,6 +1,7 @@from unittest.mock import patchimport graphene+import pytestfrom ....product.error_codes import ProductErrorCodefrom ....product.models import ProductChannelListing@@ -35,6 +36,10 @@ mutation UpdateProductVariantChannelListing(amountcurrency}+ priorPrice {+ amount+ currency+ }costPrice {amountcurrency@@ -617,3 +622,36 @@ def test_variant_channel_listing_update_preorder(channel_pln_data["preorderThreshold"]["quantity"]== preorder_threshold_channel_pln)++[email protected]("prior_price", [1.5, 0])+def test_variant_channel_listing_update_with_prior_price(+ staff_api_client, product, permission_manage_products, channel_USD, prior_price+):+ # given+ price = 1.0+ variant = product.variants.get()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": variant_id,+ "input": [+ {"channelId": channel_usd_id, "priorPrice": prior_price, "price": price}+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_products,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["productVariantChannelListingUpdate"]+ variant_data = data["variant"]+ assert not data["errors"]+ assert variant_data["id"] == variant_id+ assert variant_data["channelListings"][0]["priorPrice"]["currency"] == "USD"+ assert variant_data["channelListings"][0]["priorPrice"]["amount"] == prior_pricediff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex 7d75bb8941..19ccc10d77 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -21,7 +21,7 @@ from ....tax.utils import (from ...account import types as account_typesfrom ...channel.dataloaders import ChannelByIdLoaderfrom ...channel.types import Channel-from ...core.descriptions import DEPRECATED_IN_3X_FIELD+from ...core.descriptions import ADDED_IN_321, DEPRECATED_IN_3X_FIELDfrom ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.fields import PermissionsFieldfrom ...core.scalars import Date, DateTime@@ -350,6 +350,11 @@ class ProductVariantChannelListing()price = graphene.Field(Money, description="The price of the variant.")cost_price = graphene.Field(Money, description="Cost price of the variant.")+ prior_price = graphene.Field(+ Money,+ description="Prior price of the variant used for discount calculations."+ + ADDED_IN_321,+ )margin = PermissionsField(graphene.Int,description="Gross margin percentage value.",diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex a923aba6a0..aa53daf456 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -167,6 +167,14 @@ class BasePricingInfo(BaseObjectType):discount = graphene.Field(TaxedMoney, description="The discount amount if in sale (null otherwise).")+ discount_prior = graphene.Field(+ TaxedMoney,+ description=(+ "The discount amount compared to prior price. Null if product "+ "is not on sale or prior price was not provided in VariantChannelListing"+ + ADDED_IN_321+ ),+ )# deprecateddiscount_local_currency = graphene.Field(@@ -187,6 +195,9 @@ class VariantPricingInfo(BasePricingInfo):price_undiscounted = graphene.Field(TaxedMoney, description="The price without any discount.")+ price_prior = graphene.Field(+ TaxedMoney, description="The price prior to discount." + ADDED_IN_321+ )# deprecateddiscount_local_currency = graphene.Field(@@ -218,6 +229,10 @@ class ProductPricingInfo(BasePricingInfo):TaxedMoneyRange,description="The undiscounted price range of the product variants.",)+ price_range_prior = graphene.Field(+ TaxedMoneyRange,+ description="The prior price range of the product variants." + ADDED_IN_321,+ )# deprecatedprice_range_local_currency = graphene.Field(diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 8f13a4e9a4..6d0de58a3f 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -7175,6 +7175,13 @@ type ProductVariantChannelListing implements Node @doc(category: "Products") {"""Cost price of the variant."""costPrice: Money+ """+ Prior price of the variant used for discount calculations.++ Added in Saleor 3.21.+ """+ priorPrice: Money+"""Gross margin percentage value.@@ -7203,6 +7210,13 @@ type VariantPricingInfo @doc(category: "Products") {"""The discount amount if in sale (null otherwise)."""discount: TaxedMoney+ """+ The discount amount compared to prior price. Null if product is not on sale or prior price was not provided in VariantChannelListing++ Added in Saleor 3.21.+ """+ discountPrior: TaxedMoney+"""The discount amount in the local currency."""discountLocalCurrency: TaxedMoney @deprecated(reason: "This field will be removed in Saleor 4.0. Always returns `null`.")@@ -7212,6 +7226,13 @@ type VariantPricingInfo @doc(category: "Products") {"""The price without any discount."""priceUndiscounted: TaxedMoney+ """+ The price prior to discount.++ Added in Saleor 3.21.+ """+ pricePrior: TaxedMoney+"""The discounted price in the local currency."""priceLocalCurrency: TaxedMoney @deprecated(reason: "This field will be removed in Saleor 4.0. Always returns `null`.")}@@ -7584,6 +7605,13 @@ type ProductPricingInfo @doc(category: "Products") {"""The discount amount if in sale (null otherwise)."""discount: TaxedMoney+ """+ The discount amount compared to prior price. Null if product is not on sale or prior price was not provided in VariantChannelListing++ Added in Saleor 3.21.+ """+ discountPrior: TaxedMoney+"""The discount amount in the local currency."""discountLocalCurrency: TaxedMoney @deprecated(reason: "This field will be removed in Saleor 4.0. Always returns `null`.")@@ -7596,6 +7624,13 @@ type ProductPricingInfo @doc(category: "Products") {"""The undiscounted price range of the product variants."""priceRangeUndiscounted: TaxedMoneyRange+ """+ The prior price range of the product variants.++ Added in Saleor 3.21.+ """+ priceRangePrior: TaxedMoneyRange+"""The discounted price range of the product variants in the local currency."""@@ -10385,6 +10420,13 @@ type CheckoutLine implements Node & ObjectWithMetadata @doc(category: "Checkout""""The unit price of the checkout line, without discounts."""undiscountedUnitPrice: Money!+ """+ The unit price of the checkout line prior to promotion.++ Added in Saleor 3.21.+ """+ priorUnitPrice: Money+"""The sum of the checkout line price, taxes and discounts.@@ -10396,6 +10438,13 @@ type CheckoutLine implements Node & ObjectWithMetadata @doc(category: "Checkout""""The sum of the checkout line price, without discounts."""undiscountedTotalPrice: Money!+ """+ The sum of the checkout line price prior to promotion.++ Added in Saleor 3.21.+ """+ priorTotalPrice: Money+"""Indicates whether the item need to be delivered."""requiresShipping: Boolean!@@ -21080,6 +21129,13 @@ input ProductVariantChannelListingAddInput @doc(category: "Products") {"""Cost price of the variant in channel."""costPrice: PositiveDecimal+ """+ Previous price of the variant in channel. Useful for providing promotion information required by customer protection laws such as EU Omnibus directive.++ Added in Saleor 3.21.+ """+ priorPrice: PositiveDecimal+"""The threshold for preorder variant in channel."""preorderThreshold: Int}@@ -21916,6 +21972,9 @@ input ChannelListingUpdateInput @doc(category: "Products") {"""Cost price of the variant in channel."""costPrice: PositiveDecimal+ """Price of the variant before discount."""+ priorPrice: PositiveDecimal+"""The threshold for preorder variant in channel."""preorderThreshold: Int}diff --git a/saleor/product/migrations/0197_productvariantchannellisting_prior_price_amount.py b/saleor/product/migrations/0197_productvariantchannellisting_prior_price_amount.pynew file mode 100644index 0000000000..3f1312ec48--- /dev/null+++ b/saleor/product/migrations/0197_productvariantchannellisting_prior_price_amount.py@@ -0,0 +1,19 @@+# Generated by Django 4.2.16 on 2024-12-21 11:42++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("product", "0196_slug_unique_constraint"),+ ]++ operations = [+ migrations.AddField(+ model_name="productvariantchannellisting",+ name="prior_price_amount",+ field=models.DecimalField(+ blank=True, decimal_places=3, max_digits=12, null=True+ ),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 00d5d092f7..a3abb51767 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -418,6 +418,15 @@ class ProductVariant(SortableModel, ModelWithMetadata, ModelWithExternalReferencprice=price, rules=rules, currency=channel_listing.currency)+ def get_prior_price_amount(+ self,+ channel_listing: Optional["ProductVariantChannelListing"],+ ) -> Decimal | None:+ if channel_listing is None or channel_listing.prior_price is None:+ return None++ return channel_listing.prior_price.amount+def get_weight(self):return self.weight or self.product.weight or self.product.product_type.weight@@ -526,6 +535,16 @@ class ProductVariantChannelListing(models.Model):)cost_price = MoneyField(amount_field="cost_price_amount", currency_field="currency")+ prior_price_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ blank=True,+ null=True,+ )+ prior_price = MoneyField(+ amount_field="prior_price_amount", currency_field="currency"+ )+discounted_price_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,diff --git a/saleor/product/tests/fixtures/product.py b/saleor/product/tests/fixtures/product.pyindex 7256e14f03..642e119b19 100644--- a/saleor/product/tests/fixtures/product.py+++ b/saleor/product/tests/fixtures/product.py@@ -86,6 +86,7 @@ def product(product_type, category, warehouse, channel_USD, default_tax_class):price_amount=Decimal(10),discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),+ prior_price_amount=Decimal(8),currency=channel_USD.currency_code,)Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=10)diff --git a/saleor/product/tests/fixtures/variant.py b/saleor/product/tests/fixtures/variant.pyindex dfaea75098..9812c9175f 100644--- a/saleor/product/tests/fixtures/variant.py+++ b/saleor/product/tests/fixtures/variant.py@@ -62,6 +62,7 @@ def variant(product, channel_USD) -> ProductVariant:price_amount=Decimal(10),discounted_price_amount=Decimal(10),cost_price_amount=Decimal(1),+ prior_price_amount=Decimal(8),currency=channel_USD.currency_code,)return product_variantdiff --git a/saleor/product/tests/test_product_availability.py b/saleor/product/tests/test_product_availability.pyindex 95cecffd10..fdec30db39 100644--- a/saleor/product/tests/test_product_availability.py+++ b/saleor/product/tests/test_product_availability.py@@ -1,6 +1,7 @@import datetimefrom decimal import Decimal+import pytestfrom django.utils import timezonefrom freezegun import freeze_timefrom prices import Money, TaxedMoney, TaxedMoneyRange@@ -431,3 +432,72 @@ def test_filter_not_published_product_without_assigned_channel(not_available_products_pln = models.Product.objects.not_published(channel_PLN)assert not_available_products_pln.count() == 1+++def test_availability_with_prior_price(product, channel_USD):+ # given+ price = 20+ discounted_price = 10+ prior_price = 15++ product_channel_listing = product.channel_listings.get()+ variant = product.variants.first()+ variant_channel_listing = variant.channel_listings.get()+ variant_channel_listing.prior_price_amount = Decimal(prior_price)+ variant_channel_listing.price_amount = Decimal(price)+ variant_channel_listing.discounted_price_amount = Decimal(discounted_price)+ variant_channel_listing.save()++ # when+ availability = get_product_availability(+ product_channel_listing=product_channel_listing,+ variants_channel_listing=[variant_channel_listing],+ tax_rate=Decimal(19),+ tax_calculation_strategy="TAX_APP",+ prices_entered_with_tax=True,+ )++ # then+ assert availability.price_range_prior is not None+ assert (+ availability.price_range_prior.start.gross.amount+ == variant_channel_listing.prior_price_amount+ )++ assert availability.discount_prior is not None+ assert availability.discount_prior.gross.amount == prior_price - discounted_price+ assert availability.discount is not None+ assert availability.discount.gross.amount == price - discounted_price++[email protected]("prior_price", [Decimal(10), Decimal(5), Decimal(0)])+def test_availability_with_negative_prior_discount(product, channel_USD, prior_price):+ # given+ price = 20+ discounted_price = 10++ product_channel_listing = product.channel_listings.get()+ variant = product.variants.first()+ variant_channel_listing = variant.channel_listings.get()+ variant_channel_listing.prior_price_amount = Decimal(prior_price)+ variant_channel_listing.price_amount = Decimal(price)+ variant_channel_listing.discounted_price_amount = Decimal(discounted_price)+ variant_channel_listing.save()++ # when+ availability = get_product_availability(+ product_channel_listing=product_channel_listing,+ variants_channel_listing=[variant_channel_listing],+ tax_rate=Decimal(19),+ tax_calculation_strategy="TAX_APP",+ prices_entered_with_tax=True,+ )++ # then+ assert availability.price_range_prior is not None+ assert (+ availability.price_range_prior.start.gross.amount+ == variant_channel_listing.prior_price_amount+ )++ assert availability.discount_prior is Nonediff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.pyindex 630e9499dd..5769cfe219 100644--- a/saleor/product/utils/availability.py+++ b/saleor/product/utils/availability.py@@ -1,5 +1,6 @@from dataclasses import dataclassfrom decimal import Decimal+from typing import Literalfrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange@@ -13,7 +14,9 @@ class ProductAvailability:on_sale: boolprice_range: TaxedMoneyRange | Noneprice_range_undiscounted: TaxedMoneyRange | None+ price_range_prior: TaxedMoneyRange | Nonediscount: TaxedMoney | None+ discount_prior: TaxedMoney | None@dataclass@@ -21,7 +24,9 @@ class VariantAvailability:on_sale: boolprice: TaxedMoneyprice_undiscounted: TaxedMoney+ price_prior: TaxedMoney | Nonediscount: TaxedMoney | None+ discount_prior: TaxedMoney | Nonedef _get_total_discount_from_range(@@ -51,7 +56,7 @@ def _get_total_discount(def get_product_price_range(*,variants_channel_listing: list[ProductVariantChannelListing],- discounted: bool,+ field: Literal["price", "discounted_price", "prior_price"],) -> MoneyRange | None:"""Return the range of product prices based on product variants prices.@@ -59,12 +64,8 @@ def get_product_price_range("""prices = []for channel_listing in variants_channel_listing:- if channel_listing.price:- price = (- channel_listing.discounted_price- if discounted- else channel_listing.price- )+ price: Money | None = channel_listing.__getattribute__(field)+ if price is not None:prices.append(price)if prices:return MoneyRange(min(prices), max(prices))@@ -85,59 +86,80 @@ def _calculate_product_price_with_taxes(return TaxedMoney(price, price)-def get_product_availability(- *,- product_channel_listing: ProductChannelListing | None,+def _calculate_product_price_with_taxes_range(+ field: Literal["price", "discounted_price", "prior_price"],variants_channel_listing: list[ProductVariantChannelListing],- prices_entered_with_tax: bool,- tax_calculation_strategy: str,tax_rate: Decimal,-) -> ProductAvailability:- discounted: TaxedMoneyRange | None = None- discounted_net_range = get_product_price_range(- variants_channel_listing=variants_channel_listing, discounted=True+ tax_calculation_strategy: str,+ prices_entered_with_tax: bool,+) -> TaxedMoneyRange | None:+ price: TaxedMoneyRange | None = None+ price_net_range = get_product_price_range(+ variants_channel_listing=variants_channel_listing, field=field)- if discounted_net_range is not None:- discounted = TaxedMoneyRange(+ if price_net_range is not None:+ price = TaxedMoneyRange(start=_calculate_product_price_with_taxes(- discounted_net_range.start,+ price_net_range.start,tax_rate,tax_calculation_strategy,prices_entered_with_tax,),stop=_calculate_product_price_with_taxes(- discounted_net_range.stop,+ price_net_range.stop,tax_rate,tax_calculation_strategy,prices_entered_with_tax,),)- undiscounted: TaxedMoneyRange | None = None- undiscounted_net_range = get_product_price_range(- variants_channel_listing=variants_channel_listing,- discounted=False,+ return price+++def get_product_availability(+ *,+ product_channel_listing: ProductChannelListing | None,+ variants_channel_listing: list[ProductVariantChannelListing],+ prices_entered_with_tax: bool,+ tax_calculation_strategy: str,+ tax_rate: Decimal,+) -> ProductAvailability:+ undiscounted: TaxedMoneyRange | None = _calculate_product_price_with_taxes_range(+ "price",+ variants_channel_listing,+ tax_rate,+ tax_calculation_strategy,+ prices_entered_with_tax,)- if undiscounted_net_range is not None:- undiscounted = TaxedMoneyRange(- start=_calculate_product_price_with_taxes(- undiscounted_net_range.start,- tax_rate,- tax_calculation_strategy,- prices_entered_with_tax,- ),- stop=_calculate_product_price_with_taxes(- undiscounted_net_range.stop,- tax_rate,- tax_calculation_strategy,- prices_entered_with_tax,- ),++ discounted: TaxedMoneyRange | None = None+ prior: TaxedMoneyRange | None = None++ if undiscounted is not None:+ discounted = _calculate_product_price_with_taxes_range(+ "discounted_price",+ variants_channel_listing,+ tax_rate,+ tax_calculation_strategy,+ prices_entered_with_tax,+ )++ prior = _calculate_product_price_with_taxes_range(+ "prior_price",+ variants_channel_listing,+ tax_rate,+ tax_calculation_strategy,+ prices_entered_with_tax,)discount = Noneif undiscounted is not None and discounted is not None:discount = _get_total_discount_from_range(undiscounted, discounted)+ discount_prior = None+ if prior is not None and discounted is not None:+ discount_prior = _get_total_discount_from_range(prior, discounted)+is_visible = (product_channel_listing is not None and product_channel_listing.is_visible)@@ -147,7 +169,9 @@ def get_product_availability(on_sale=is_on_sale,price_range=discounted,price_range_undiscounted=undiscounted,+ price_range_prior=prior,discount=discount,+ discount_prior=discount_prior,)@@ -174,8 +198,21 @@ def get_variant_availability(tax_calculation_strategy,prices_entered_with_tax,)+ prior_price = variant_channel_listing.prior_price+ prior_price_taxed = None+ if prior_price is not None:+ prior_price_taxed = _calculate_product_price_with_taxes(+ prior_price,+ tax_rate,+ tax_calculation_strategy,+ prices_entered_with_tax,+ )discount = _get_total_discount(undiscounted_price_taxed, discounted_price_taxed)+ discount_prior = None+ if prior_price_taxed is not None:+ discount_prior = _get_total_discount(prior_price_taxed, discounted_price_taxed)+is_visible = (product_channel_listing is not None and product_channel_listing.is_visible)@@ -185,5 +222,7 @@ def get_variant_availability(on_sale=is_on_sale,price=discounted_price_taxed,price_undiscounted=undiscounted_price_taxed,+ price_prior=prior_price_taxed,discount=discount,+ discount_prior=discount_prior,)