Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix negative unit price on gift line in case promotion gift reward changes (#18469)
Iga Karbowiak261bbc8d35c4
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex efcf28203b..f6bbf417e8 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -390,12 +390,11 @@ def _fetch_checkout_prices_if_expired(checkout_info, database_connection_name)- 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+ recalculate_discounts(+ checkout_info,+ lines,+ database_connection_name=database_connection_name,+ force_update=force_update,)checkout.tax_error = None@@ -431,7 +430,9 @@ def _fetch_checkout_prices_if_expired(# tax from the original gross prices._remove_tax(checkout, lines)- checkout.price_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL+ price_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL+ checkout.price_expiration = price_expiration+ checkout.discount_expiration = price_expirationwith allow_writer():with transaction.atomic():@@ -466,6 +467,7 @@ def _fetch_checkout_prices_if_expired("currency","last_change","price_expiration",+ "discount_expiration","tax_error",]@@ -488,6 +490,54 @@ def _fetch_checkout_prices_if_expired(return checkout_info, lines+@allow_writer()+def recalculate_discounts(+ checkout_info: "CheckoutInfo",+ lines_info: Iterable["CheckoutLineInfo"],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,+ force_update: bool = False,+) -> tuple["CheckoutInfo", Iterable["CheckoutLineInfo"]]:+ """Recalculate checkout discounts.++ Discounts are recalculated only if force_update is True, or if both discount+ and price expirations have passed.+ This updates catalogue promotions, vouchers, and order promotion discounts.+ """+ checkout = checkout_info.checkout++ # Do not recalculate discounts in case the checkout prices are still valid, either+ # discounts or tax prices.+ if not force_update and (+ checkout.discount_expiration > timezone.now()+ or checkout.price_expiration > timezone.now()+ ):+ return checkout_info, lines_info++ lines = cast(list, lines_info)+ update_undiscounted_unit_price_for_lines(lines)+ update_prior_unit_price_for_lines(lines)++ soonest_promotion_end_date = (+ create_or_update_discount_objects_from_promotion_for_checkout(+ checkout_info, lines, database_connection_name+ )+ )++ if soonest_promotion_end_date is not None:+ checkout.discount_expiration = min(+ soonest_promotion_end_date, timezone.now() + settings.CHECKOUT_PRICES_TTL+ )+ else:+ checkout.discount_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL++ checkout.save(+ update_fields=["discount_expiration"],+ using=settings.DATABASE_CONNECTION_DEFAULT_NAME,+ )++ return checkout_info, lines++def _calculate_and_add_tax(tax_calculation_strategy: str,tax_app_identifier: str | None,diff --git a/saleor/checkout/migrations/0076_checkout_discount_expiration.py b/saleor/checkout/migrations/0076_checkout_discount_expiration.pynew file mode 100644index 0000000000..4cf7974c0a--- /dev/null+++ b/saleor/checkout/migrations/0076_checkout_discount_expiration.py@@ -0,0 +1,28 @@+# Generated by Django 4.2.20 on 2025-10-24 07:31++import django.utils.timezone+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0075_alter_checkout_base_subtotal_amount_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkout",+ name="discount_expiration",+ field=models.DateTimeField(default=django.utils.timezone.now),+ ),+ migrations.RunSQL(+ sql=(+ "ALTER TABLE checkout_checkout "+ "ALTER COLUMN discount_expiration SET DEFAULT NOW();"+ ),+ reverse_sql=(+ "ALTER TABLE checkout_checkout "+ "ALTER COLUMN discount_expiration DROP DEFAULT;"+ ),+ ),+ ]diff --git a/saleor/checkout/migrations/0081_merge_20251107_1134.py b/saleor/checkout/migrations/0081_merge_20251107_1134.pynew file mode 100644index 0000000000..6dd9837b26--- /dev/null+++ b/saleor/checkout/migrations/0081_merge_20251107_1134.py@@ -0,0 +1,12 @@+# Generated by Django 4.2.26 on 2025-11-07 11:34++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0076_checkout_discount_expiration"),+ ("checkout", "0080_alter_checkout_external_shipping_method_id"),+ ]++ operations = []diff --git a/saleor/checkout/migrations/0082_merge_20251107_1235.py b/saleor/checkout/migrations/0082_merge_20251107_1235.pynew file mode 100644index 0000000000..fd1603b18f--- /dev/null+++ b/saleor/checkout/migrations/0082_merge_20251107_1235.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.8 on 2025-11-07 12:35++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0081_merge_20251103_0924"),+ ("checkout", "0081_merge_20251107_1134"),+ ]++ operations = []diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex d6dc6922cf..5fad24d284 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -194,6 +194,9 @@ class Checkout(models.Model):)price_expiration = models.DateTimeField(default=timezone.now)+ # Expiration time of the applied discounts.+ # Decides if the discounts are updated before tax recalculation.+ discount_expiration = models.DateTimeField(default=timezone.now)discount_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 2a2c6a74f7..9743bdecbd 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -122,8 +122,10 @@ def invalidate_checkout_prices("""Mark checkout as ready for prices recalculation."""checkout = checkout_info.checkout- checkout.price_expiration = timezone.now()- updated_fields = ["price_expiration", "last_change"]+ price_expiration = timezone.now()+ checkout.price_expiration = price_expiration+ checkout.discount_expiration = price_expiration+ updated_fields = ["price_expiration", "discount_expiration", "last_change"]if save:checkout.save(update_fields=updated_fields)@@ -285,7 +287,10 @@ def add_variant_to_checkout(line.save(update_fields=["quantity"])# invalidate calculated prices- checkout.price_expiration = timezone.now()+ price_expiration = timezone.now()+ checkout.price_expiration = price_expiration+ checkout.discount_expiration = price_expiration+return checkoutdiff --git a/saleor/discount/utils/checkout.py b/saleor/discount/utils/checkout.pyindex 29dcfa220d..ef1449b096 100644--- a/saleor/discount/utils/checkout.py+++ b/saleor/discount/utils/checkout.py@@ -1,3 +1,4 @@+import datetimefrom typing import TYPE_CHECKINGfrom django.conf import settings@@ -35,26 +36,32 @@ def create_or_update_discount_objects_from_promotion_for_checkout(lines_info: list["CheckoutLineInfo"],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):- create_checkout_line_discount_objects_for_catalogue_promotions(lines_info)- create_checkout_discount_objects_for_order_promotions(+ soonest_catalogue_promotion_end_date = (+ create_checkout_line_discount_objects_for_catalogue_promotions(lines_info)+ )+ order_promotion_end_date = create_checkout_discount_objects_for_order_promotions(checkout_info, lines_info, database_connection_name=database_connection_name)+ if soonest_catalogue_promotion_end_date and order_promotion_end_date:+ return min(soonest_catalogue_promotion_end_date, order_promotion_end_date)+ return soonest_catalogue_promotion_end_date or order_promotion_end_datedef create_checkout_line_discount_objects_for_catalogue_promotions(lines_info: list["CheckoutLineInfo"],-):+) -> datetime.datetime | None:discount_data = prepare_checkout_line_discount_objects_for_catalogue_promotions(lines_info)if not discount_data or not lines_info:- return+ return None(discounts_to_create_inputs,discounts_to_update,discount_to_remove,updated_fields,+ soonest_end_date,) = discount_datanew_line_discounts = []@@ -91,18 +98,27 @@ def create_checkout_line_discount_objects_for_catalogue_promotions(update_line_info_cached_discounts(lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove)+ return soonest_end_datedef prepare_checkout_line_discount_objects_for_catalogue_promotions(lines_info: list["CheckoutLineInfo"],) -> (- tuple[list[dict], list[CheckoutLineDiscount], list[CheckoutLineDiscount], list[str]]+ tuple[+ list[dict],+ list[CheckoutLineDiscount],+ list[CheckoutLineDiscount],+ list[str],+ datetime.datetime | None,+ ]| None):line_discounts_to_create_inputs: list[dict] = []line_discounts_to_update: list[CheckoutLineDiscount] = []line_discounts_to_remove: list[CheckoutLineDiscount] = []updated_fields: list[str] = []+ soonest_end_date = None+ applied_promotions_end_dates = []if not lines_info:return None@@ -146,6 +162,9 @@ def prepare_checkout_line_discount_objects_for_catalogue_promotions(if line_info.rules_info:rule_info = line_info.rules_info[0]rule = rule_info.rule+ promotion = rule_info.promotion+ if promotion.end_date:+ applied_promotions_end_dates.append(promotion.end_date)rule_discount_amount = _get_rule_discount_amount(line, rule_info, line_info.channel)@@ -180,11 +199,15 @@ def prepare_checkout_line_discount_objects_for_catalogue_promotions(# Fallback for unlike mismatch between discount_amount and rules_infoline_discounts_to_remove.extend(discounts_to_update)+ if applied_promotions_end_dates:+ soonest_end_date = min(applied_promotions_end_dates)+return (line_discounts_to_create_inputs,line_discounts_to_update,line_discounts_to_remove,updated_fields,+ soonest_end_date,)@@ -203,11 +226,12 @@ def create_checkout_discount_objects_for_order_promotions(# Discount from order rules is applied only when the voucher is not setif checkout.voucher_code:_clear_checkout_discount(checkout_info, lines_info, save)- return+ return None(gift_promotion_applied,discount_object,+ promotion_end_date,) = create_discount_objects_for_order_promotions(checkout,lines_info,@@ -218,7 +242,7 @@ def create_checkout_discount_objects_for_order_promotions()if not gift_promotion_applied and not discount_object:_clear_checkout_discount(checkout_info, lines_info, save)- return+ return Noneif discount_object:checkout_info.discounts = [discount_object]@@ -234,6 +258,7 @@ def create_checkout_discount_objects_for_order_promotions("translated_discount_name",])+ return promotion_end_datedef _set_checkout_base_prices(checkout_info, lines_info):diff --git a/saleor/discount/utils/order.py b/saleor/discount/utils/order.pyindex 2fa10e936b..1372091ec9 100644--- a/saleor/discount/utils/order.py+++ b/saleor/discount/utils/order.py@@ -201,6 +201,7 @@ def create_order_discount_objects_for_order_promotions((gift_promotion_applied,discount_object,+ _end_date,) = create_discount_objects_for_order_promotions(order,lines_info,diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.pyindex 0d9e67ddb5..2d5c9f222c 100644--- a/saleor/discount/utils/promotion.py+++ b/saleor/discount/utils/promotion.py@@ -449,7 +449,7 @@ def create_gift_line(if fields_to_update:line.save(update_fields=fields_to_update)- return line, created+ return linedef _get_defaults_for_gift_line(@@ -705,6 +705,7 @@ def create_discount_objects_for_order_promotions("""gift_promotion_applied = Falsediscount_object = None+ promotion_end_date = Nonerules = fetch_promotion_rules_for_checkout_or_order(order_or_checkout, database_connection_name)@@ -716,7 +717,7 @@ def create_discount_objects_for_order_promotions(database_connection_name=database_connection_name,)if not rule_data:- return gift_promotion_applied, discount_object+ return gift_promotion_applied, discount_object, promotion_end_datebest_rule, best_discount_amount, gift_listing = rule_datapromotion = best_rule.promotion@@ -747,7 +748,7 @@ def create_discount_objects_for_order_promotions(translated_name=get_discount_translated_name(rule_info),reason=prepare_promotion_discount_reason(rule_info.promotion),)-+ promotion_end_date = promotion.end_dateif gift_listing:_handle_gift_reward(order_or_checkout,@@ -765,7 +766,7 @@ def create_discount_objects_for_order_promotions(line_discount,rule_info,)- return gift_promotion_applied, discount_object+ return gift_promotion_applied, discount_object, promotion_end_date@allow_writer()@@ -812,9 +813,7 @@ def _handle_gift_reward(else OrderLineDiscount)with transaction.atomic():- line, line_created = create_gift_line(- order_or_checkout, gift_listing, line_discount_data- )+ line = create_gift_line(order_or_checkout, gift_listing, line_discount_data)(line_discount,discount_created,@@ -840,34 +839,34 @@ def _handle_gift_reward(if fields_to_update:line_discount.save(update_fields=fields_to_update)- if line_created:- variant = gift_listing.variant- init_values = {- "line": line,- "variant": variant,- "product": variant.product,- "product_type": variant.product.product_type,- "collections": [],- "discounts": [line_discount],- "channel": channel,- "voucher": None,- "voucher_code": None,- }- gift_line_info: CheckoutLineInfo | EditableOrderLineInfo- if isinstance(order_or_checkout, Checkout):- init_values["channel_listing"] = gift_listing- init_values["rules_info"] = [rule_info]- gift_line_info = CheckoutLineInfo(**init_values)- else:- init_values["voucher_denormalized_info"] = None- gift_line_info = EditableOrderLineInfo(**init_values)- lines_info.append(gift_line_info) # type: ignore[arg-type]+ # replace the current line info with the new one to prevent the mismatch+ line_info = next(+ (line_info for line_info in lines_info if line_info.line.pk == line.id), None+ )+ if line_info:+ lines_info.remove(line_info) # type: ignore[arg-type]++ variant = gift_listing.variant+ init_values = {+ "line": line,+ "variant": variant,+ "product": variant.product,+ "product_type": variant.product.product_type,+ "collections": [],+ "discounts": [line_discount],+ "channel": channel,+ "voucher": None,+ "voucher_code": None,+ }+ gift_line_info: CheckoutLineInfo | EditableOrderLineInfo+ if isinstance(order_or_checkout, Checkout):+ init_values["channel_listing"] = gift_listing+ init_values["rules_info"] = [rule_info]+ gift_line_info = CheckoutLineInfo(**init_values)else:- line_info = next(- line_info for line_info in lines_info if line_info.line.pk == line.id- )- line_info.line = line- line_info.discounts = [line_discount] # type: ignore[assignment]+ init_values["voucher_denormalized_info"] = None+ gift_line_info = EditableOrderLineInfo(**init_values)+ lines_info.append(gift_line_info) # type: ignore[arg-type]def get_active_catalogue_promotion_rules(diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex d7dcf5ea5b..7245e0d511 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -584,9 +584,7 @@ def apply_gift_reward_if_applicable_on_checkout_creation(currency=checkout.currency,)with transaction.atomic():- line, _line_created = create_gift_line(- checkout, gift_listing, line_discount_data- )+ line = create_gift_line(checkout, gift_listing, line_discount_data)CheckoutLineDiscount.objects.create(line=line, **asdict(line_discount_data))diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 703148b490..d1ee3587a7 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -422,7 +422,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(86):+ with django_assert_num_queries(87):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -440,7 +440,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(86):+ with django_assert_num_queries(87):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10@@ -572,7 +572,7 @@ def test_create_checkout_with_order_promotion(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(92):+ with django_assert_num_queries(93):response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)# then@@ -828,7 +828,7 @@ def test_update_checkout_lines_with_reservations()user_api_client.ensure_access_token()- with django_assert_num_queries(108):+ with django_assert_num_queries(109):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"id": to_global_id_or_none(checkout),@@ -842,7 +842,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(108):+ with django_assert_num_queries(109):variables = {"id": to_global_id_or_none(checkout),"lines": [],@@ -1103,7 +1103,7 @@ def test_add_checkout_lines_with_reservations(user_api_client.ensure_access_token()# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(105):+ with django_assert_num_queries(106):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -1116,7 +1116,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(105):+ with django_assert_num_queries(106):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,@@ -1167,7 +1167,7 @@ def test_add_checkout_lines_catalogue_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(96):+ with django_assert_num_queries(97):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1253,7 +1253,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(96):+ with django_assert_num_queries(97):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1289,7 +1289,7 @@ def test_add_checkout_lines_order_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(102):+ with django_assert_num_queries(103):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1324,7 +1324,7 @@ def test_add_checkout_lines_gift_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(129):+ with django_assert_num_queries(135):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# thendiff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 49af6b5ef8..bba41d4f98 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -3770,7 +3770,8 @@ def test_checkout_prices_expired_variant_listing_price_changed(force_update=True,)checkout_with_item.price_expiration = timezone.now() - datetime.timedelta(days=1)- checkout_with_item.save(update_fields=["price_expiration"])+ checkout_with_item.discount_expiration = timezone.now() - datetime.timedelta(days=1)+ checkout_with_item.save(update_fields=["price_expiration", "discount_expiration"])line = lines[0]listing = line.variant.channel_listings.get(diff --git a/saleor/graphql/checkout/tests/test_checkout_discount_expiration.py b/saleor/graphql/checkout/tests/test_checkout_discount_expiration.pynew file mode 100644index 0000000000..40d800a767--- /dev/null+++ b/saleor/graphql/checkout/tests/test_checkout_discount_expiration.py@@ -0,0 +1,659 @@+from datetime import timedelta+from unittest import mock++import graphene+import pytest+from django.utils import timezone++from ....discount.utils.checkout import (+ create_or_update_discount_objects_from_promotion_for_checkout,+)+from ...tests.utils import get_graphql_content++QUERY_CHECKOUT_BASIC_FIELDS = """+query getCheckout($id: ID) {+ checkout(id: $id) {+ id+ token+ }+}+"""+++QUERY_CHECKOUT_LINES_ONLY_ID = """+query getCheckout($id: ID) {+ checkout(id: $id) {+ token+ lines {+ id+ isGift+ }+ }+}+"""+++QUERY_CHECKOUT_LINES_WITH_PRICES = """+query getCheckout($id: ID) {+ checkout(id: $id) {+ token+ lines {+ id+ isGift+ quantity+ variant {+ id+ }+ unitPrice {+ gross {+ amount+ }+ }+ totalPrice {+ currency+ gross {+ amount+ }+ }+ undiscountedUnitPrice {+ amount+ currency+ }+ undiscountedTotalPrice {+ amount+ currency+ }+ }+ }+}+"""+++def test_checkout_basic_fields_no_recalculation(+ user_api_client, checkout_with_item_and_gift_promotion, gift_promotion_rule, product+):+ """Test that querying only basic checkout fields performs NO recalculation.++ This test ensures that when querying only basic fields (id, token, email)+ that don't involve lines or pricing, the system will:+ 1. NOT recalculate discounts (keep discount_expiration unchanged)+ 2. NOT recalculate taxes (keep price_expiration unchanged)+ 3. Return data without triggering any expensive calculations+ """+ # given+ checkout = checkout_with_item_and_gift_promotion+ query = QUERY_CHECKOUT_BASIC_FIELDS++ initial_price_expiration = timezone.now() - timedelta(minutes=5)+ initial_discount_expiration = timezone.now() - timedelta(minutes=5)+ checkout.price_expiration = initial_price_expiration+ checkout.discount_expiration = initial_discount_expiration+ checkout.save(update_fields=["price_expiration", "discount_expiration"])++ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}++ # Change gift promotion to simulate that data is stale+ new_gift_variant = product.variants.last()+ gift_promotion_rule.gifts.set([new_gift_variant])+ gift_promotion_rule.order_predicate = {"discountedObjectPredicate": {}}+ gift_promotion_rule.save(update_fields=["order_predicate"])++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ # then+ assert data["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ assert data["token"] == str(checkout.token)+ assert data["email"] == checkout.email++ checkout.refresh_from_db()+ # Verify that NO recalculation happened - both expirations should remain unchanged+ assert checkout.discount_expiration == initial_discount_expiration+ assert checkout.price_expiration == initial_price_expiration+++def test_checkout_gift_promotion_changed_only_line_id(+ user_api_client, checkout_with_item_and_gift_promotion, gift_promotion_rule, product+):+ """Test that querying only line.id triggers discount recalculation but NOT tax recalculation.++ This test ensures that when a gift promotion changes and we only query line IDs,+ the system will:+ 1. Recalculate discounts (update discount_expiration)+ 2. Update gift lines to reflect the new promotion+ 3. NOT recalculate taxes (keep price_expiration unchanged)++ This prevents unnecessary expensive tax calculations when only IDs are needed.+ """+ # given+ checkout = checkout_with_item_and_gift_promotion+ query = QUERY_CHECKOUT_LINES_ONLY_ID++ initial_price_expiration = timezone.now() - timedelta(minutes=5)+ checkout.price_expiration = initial_price_expiration+ checkout.discount_expiration = initial_price_expiration+ checkout.save(update_fields=["price_expiration", "discount_expiration"])++ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}++ lines_count = checkout.lines.count()++ # Get initial gift line+ initial_gift_line = checkout.lines.filter(is_gift=True).first()+ initial_gift_line_variant = initial_gift_line.variant+ assert initial_gift_line is not None++ # Change gift promotion to a different variant+ new_gift_variant = product.variants.last()+ gift_promotion_rule.gifts.set([new_gift_variant])+ gift_promotion_rule.order_predicate = {"discountedObjectPredicate": {}}+ gift_promotion_rule.save(update_fields=["order_predicate"])++ # Set promotion end date+ end_date = timezone.now() + timedelta(minutes=10)+ gift_promotion_rule.promotion.end_date = end_date+ gift_promotion_rule.promotion.save(update_fields=["end_date"])++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ # then+ assert data["token"] == str(checkout.token)+ assert len(data["lines"]) == lines_count++ # Verify the gift line was updated to the new variant+ gift_line = checkout.lines.filter(is_gift=True).first()+ assert gift_line.variant != initial_gift_line_variant+ assert gift_line.variant == new_gift_variant++ # Verify the response contains the updated gift line+ gift_lines = [line for line in data["lines"] if line["isGift"] is True]+ assert len(gift_lines) == 1++ gift_line_data = gift_lines[0]+ assert gift_line_data["id"] == graphene.Node.to_global_id(+ "CheckoutLine", gift_line.pk+ )++ # Verify discount_expiration was updated (discount recalculation happened)+ # Should be set to promotion end_date as it's sooner than now + checkout ttl+ checkout.refresh_from_db()+ assert checkout.discount_expiration == end_date++ # Verify price_expiration was NOT updated (tax recalculation did NOT happen)+ assert checkout.price_expiration == initial_price_expiration+++ "saleor.checkout.calculations.create_or_update_discount_objects_from_promotion_for_checkout",+ wraps=create_or_update_discount_objects_from_promotion_for_checkout,+)+def test_checkout_gift_promotion_changed_with_line_prices(+ mocked_discount_creation,+ user_api_client,+ checkout_with_item_and_gift_promotion,+ gift_promotion_rule,+ product,+):+ """Test that querying line prices triggers both discount and tax recalculation.++ This test ensures that when a gift promotion changes and we query line prices,+ the system will:+ 1. Recalculate discounts (update discount_expiration)+ 2. Update gift lines to reflect the new promotion+ 3. Recalculate taxes (update price_expiration)+ 4. Return correct pricing for gift lines (unit price = 0, undiscounted price > 0)++ This ensures accurate pricing information when price fields are requested.+ """+ # given+ checkout = checkout_with_item_and_gift_promotion+ query = QUERY_CHECKOUT_LINES_WITH_PRICES++ initial_price_expiration = timezone.now() - timedelta(minutes=5)+ checkout.price_expiration = initial_price_expiration+ checkout.discount_expiration = initial_price_expiration+ checkout.save(update_fields=["price_expiration", "discount_expiration"])++ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}++ lines_count = checkout.lines.count()++ # Get initial gift line+ initial_gift_line = checkout.lines.filter(is_gift=True).first()+ initial_gift_line_variant = initial_gift_line.variant+ assert initial_gift_line is not None++ # Change gift promotion to a different variant+ new_gift_variant = product.variants.last()+ gift_promotion_rule.gifts.set([new_gift_variant])+ gift_promotion_rule.order_predicate = {"discountedObjectPredicate": {}}+ gift_promotion_rule.save(update_fields=["order_predicate"])++ # Set promotion end date+ end_date = timezone.now() + timedelta(minutes=10)+ gift_promotion_rule.promotion.end_date = end_date+ gift_promotion_rule.promotion.save(update_fields=["end_date"])++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ # then+ assert data["token"] == str(checkout.token)+ assert len(data["lines"]) == lines_count++ # Verify the gift line was updated to the new variant+ gift_line = checkout.lines.filter(is_gift=True).first()+ assert gift_line.variant != initial_gift_line_variant+ assert gift_line.variant == new_gift_variant++ # Verify the response contains the updated gift line+ gift_lines = [line for line in data["lines"] if line["isGift"] is True]+ assert len(gift_lines) == 1++ gift_line_data = gift_lines[0]+ assert gift_line_data["id"] == graphene.Node.to_global_id(+ "CheckoutLine", gift_line.pk+ )++ # Verify gift line has correct pricing+ assert gift_line_data["unitPrice"]["gross"]["amount"] == 0+ assert gift_line_data["totalPrice"]["gross"]["amount"] == 0+ # undiscountedUnitPrice should have the original price of the variant+ assert gift_line_data["undiscountedUnitPrice"]["amount"] > 0++ # Verify both expirations were updated (full recalculation happened)+ # Both price expiration should be the same+ checkout.refresh_from_db()+ assert checkout.price_expiration > timezone.now()+ assert checkout.discount_expiration == checkout.price_expiration++ # Ensure that discount recalculation called only once+ mocked_discount_creation.assert_called_once()+++def test_checkout_gift_promotion_removed_only_line_id(+ user_api_client, checkout_with_item_and_gift_promotion, gift_promotion_rule+):+ """Test that querying only line.id triggers discount recalculation when gift promotion is removed.++ This test ensures that when a gift promotion is removed and we only query line IDs,+ the system will:+ 1. Recalculate discounts (update discount_expiration)+ 2. Remove gift lines that are no longer valid+ 3. NOT recalculate taxes (keep price_expiration unchanged)++ This prevents unnecessary expensive tax calculations when only IDs are needed.+ """+ # given+ checkout = checkout_with_item_and_gift_promotion+ query = QUERY_CHECKOUT_LINES_ONLY_ID++ initial_price_expiration = timezone.now() - timedelta(minutes=5)+ checkout.price_expiration = initial_price_expiration+ checkout.discount_expiration = initial_price_expiration+ checkout.save(update_fields=["price_expiration", "discount_expiration"])++ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}++ initial_lines_count = checkout.lines.count()+ initial_gift_line = checkout.lines.filter(is_gift=True).first()+ assert initial_gift_line is not None++ # Remove the gift promotion+ gift_promotion_rule.delete()++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ # then+ assert data["token"] == str(checkout.token)++ # Gift line should be removed+ assert len(data["lines"]) == initial_lines_count - 1++ # Verify no gift lines remain+ gift_lines = [line for line in data["lines"] if line["isGift"] is True]+ assert len(gift_lines) == 0++ # Verify gift line was removed from database+ gift_line_exists = checkout.lines.filter(is_gift=True).exists()+ assert not gift_line_exists++ # Verify discount_expiration was updated (discount recalculation happened)+ checkout.refresh_from_db()+ assert checkout.discount_expiration > timezone.now()++ # Verify price_expiration was NOT updated (tax recalculation did NOT happen)+ assert checkout.price_expiration == initial_price_expiration+++ "saleor.checkout.calculations.create_or_update_discount_objects_from_promotion_for_checkout",+ wraps=create_or_update_discount_objects_from_promotion_for_checkout,+)+def test_checkout_gift_promotion_removed_with_line_prices(+ mocked_discount_creation,+ user_api_client,+ checkout_with_item_and_gift_promotion,+ gift_promotion_rule,+):+ """Test that querying line prices triggers both discount and tax recalculation when gift promotion is removed.++ This test ensures that when a gift promotion is removed and we query line prices,+ the system will:+ 1. Recalculate discounts (update discount_expiration)+ 2. Remove gift lines that are no longer valid+ 3. Recalculate taxes (update price_expiration)++ This ensures accurate pricing information when price fields are requested.+ """+ # given+ checkout = checkout_with_item_and_gift_promotion+ query = QUERY_CHECKOUT_LINES_WITH_PRICES++ initial_price_expiration = timezone.now() - timedelta(minutes=5)+ checkout.price_expiration = initial_price_expiration+ checkout.discount_expiration = initial_price_expiration+ checkout.save(update_fields=["price_expiration", "discount_expiration"])++ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}++ initial_lines_count = checkout.lines.count()+ initial_gift_line = checkout.lines.filter(is_gift=True).first()+ assert initial_gift_line is not None++ # Remove the gift promotion+ gift_promotion_rule.delete()++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ # then+ assert data["token"] == str(checkout.token)++ # Gift line should be removed+ assert len(data["lines"]) == initial_lines_count - 1++ # Verify no gift lines remain+ gift_lines = [line for line in data["lines"] if line["isGift"] is True]+ assert len(gift_lines) == 0++ # Verify gift line was removed from database+ gift_line_exists = checkout.lines.filter(is_gift=True).exists()+ assert not gift_line_exists++ # Verify both expirations were updated (full recalculation happened)+ checkout.refresh_from_db()+ assert checkout.discount_expiration > timezone.now()+ assert checkout.price_expiration > timezone.now()++ # Ensure that discount recalculation called only once+ mocked_discount_creation.assert_called_once()+++def test_checkout_gift_promotion_added_only_line_id(+ user_api_client, checkout_with_item, gift_promotion_rule, product+):+ """Test that querying only line.id triggers discount recalculation when gift promotion is added.++ This test ensures that when a gift promotion is added to a checkout without gift lines+ and we only query line IDs, the system will:+ 1. Recalculate discounts (update discount_expiration)+ 2. Add new gift lines based on the promotion+ 3. NOT recalculate taxes (keep price_expiration unchanged)++ This prevents unnecessary expensive tax calculations when only IDs are needed.+ """+ # given+ checkout = checkout_with_item+ query = QUERY_CHECKOUT_LINES_ONLY_ID++ initial_price_expiration = timezone.now() - timedelta(minutes=5)+ checkout.price_expiration = initial_price_expiration+ checkout.discount_expiration = initial_price_expiration+ checkout.save(update_fields=["price_expiration", "discount_expiration"])++ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}++ initial_lines_count = checkout.lines.count()++ # Verify no gift lines initially exist+ initial_gift_line = checkout.lines.filter(is_gift=True).first()+ assert initial_gift_line is None++ # Add gift to the promotion rule+ gift_variant = product.variants.first()+ gift_promotion_rule.gifts.set([gift_variant])+ gift_promotion_rule.order_predicate = {"discountedObjectPredicate": {}}+ gift_promotion_rule.save(update_fields=["order_predicate"])++ # Set promotion end date+ end_date = timezone.now() + timedelta(days=20)+ gift_promotion_rule.promotion.end_date = end_date+ gift_promotion_rule.promotion.save(update_fields=["end_date"])++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ # then+ assert data["token"] == str(checkout.token)++ # Gift line should be added+ assert len(data["lines"]) == initial_lines_count + 1++ # Verify gift line was added+ gift_lines = [line for line in data["lines"] if line["isGift"] is True]+ assert len(gift_lines) == 1++ # Verify gift line exists in database+ gift_line = checkout.lines.filter(is_gift=True).first()+ assert gift_line is not None+ assert gift_line.variant == gift_variant++ # Verify the response contains the added gift line+ gift_line_data = gift_lines[0]+ assert gift_line_data["id"] == graphene.Node.to_global_id(+ "CheckoutLine", gift_line.pk+ )++ # Verify discount_expiration was updated (discount recalculation happened)+ # Ensure it's not set to promotion end date as it's later than now + checkout ttl+ checkout.refresh_from_db()+ assert checkout.discount_expiration > timezone.now() < end_date++ # Verify price_expiration was NOT updated (tax recalculation did NOT happen)+ assert checkout.price_expiration == initial_price_expiration+++ "saleor.checkout.calculations.create_or_update_discount_objects_from_promotion_for_checkout",+ wraps=create_or_update_discount_objects_from_promotion_for_checkout,+)+def test_checkout_gift_promotion_added_with_line_prices(+ mocked_discount_creation,+ user_api_client,+ checkout_with_item,+ gift_promotion_rule,+ product,+):+ """Test that querying line prices triggers both discount and tax recalculation when gift promotion is added.++ This test ensures that when a gift promotion is added to a checkout without gift lines+ and we query line prices, the system will:+ 1. Recalculate discounts (update discount_expiration)+ 2. Add new gift lines based on the promotion+ 3. Recalculate taxes (update price_expiration)+ 4. Return correct pricing for gift lines (unit price = 0, undiscounted price > 0)++ This ensures accurate pricing information when price fields are requested.+ """+ # given+ checkout = checkout_with_item+ query = QUERY_CHECKOUT_LINES_WITH_PRICES++ initial_price_expiration = timezone.now() - timedelta(minutes=5)+ checkout.price_expiration = initial_price_expiration+ checkout.discount_expiration = initial_price_expiration+ checkout.save(update_fields=["price_expiration", "discount_expiration"])++ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}++ initial_lines_count = checkout.lines.count()++ # Verify no gift lines initially exist+ initial_gift_line = checkout.lines.filter(is_gift=True).first()+ assert initial_gift_line is None++ # Add gift to the promotion rule+ gift_variant = product.variants.first()+ gift_promotion_rule.gifts.set([gift_variant])+ gift_promotion_rule.order_predicate = {"discountedObjectPredicate": {}}+ gift_promotion_rule.save(update_fields=["order_predicate"])++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ # then+ assert data["token"] == str(checkout.token)++ # Gift line should be added+ assert len(data["lines"]) == initial_lines_count + 1++ # Verify gift line was added+ gift_lines = [line for line in data["lines"] if line["isGift"] is True]+ assert len(gift_lines) == 1++ # Verify gift line exists in database+ gift_line = checkout.lines.filter(is_gift=True).first()+ assert gift_line is not None+ assert gift_line.variant == gift_variant++ # Verify the response contains the added gift line+ gift_line_data = gift_lines[0]+ assert gift_line_data["id"] == graphene.Node.to_global_id(+ "CheckoutLine", gift_line.pk+ )++ # Verify gift line has correct pricing+ assert gift_line_data["unitPrice"]["gross"]["amount"] == 0+ assert gift_line_data["totalPrice"]["gross"]["amount"] == 0+ # undiscountedUnitPrice should have the original price of the variant+ assert gift_line_data["undiscountedUnitPrice"]["amount"] > 0++ # Verify both expirations were updated (full recalculation happened)+ checkout.refresh_from_db()+ assert checkout.discount_expiration > timezone.now()+ assert checkout.price_expiration > timezone.now()++ # Ensure that discount recalculation called only once+ mocked_discount_creation.assert_called_once()+++ ("price_expiration", "discount_expiration"),+ [+ (+ timezone.now() + timedelta(minutes=10),+ timezone.now(),+ ),+ (+ timezone.now() + timedelta(minutes=20),+ timezone.now() - timedelta(minutes=20),+ ),+ (+ timezone.now() + timedelta(minutes=30),+ timezone.now() + timedelta(minutes=30),+ ),+ ],+)+def test_checkout_lines_with_prices_price_expiration_in_future_no_recalculation(+ product,+ price_expiration,+ discount_expiration,+ user_api_client,+ checkout_with_item_and_gift_promotion,+ gift_promotion_rule,+):+ """Test that querying line prices does NOT trigger recalculation if price_expiration is in the future.++ This test ensures that when price_expiration and discount_expiration are set to a future time,+ querying line prices will:+ 1. NOT recalculate discounts (keep discount_expiration unchanged)+ 2. NOT recalculate taxes (keep price_expiration unchanged)+ 3. Return correct pricing for gift lines+ """+ # given+ checkout = checkout_with_item_and_gift_promotion+ query = QUERY_CHECKOUT_LINES_WITH_PRICES++ checkout.price_expiration = price_expiration+ checkout.discount_expiration = discount_expiration+ checkout.save(update_fields=["price_expiration", "discount_expiration"])++ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}++ lines_count = checkout.lines.count()++ # Get initial gift line+ initial_gift_line = checkout.lines.filter(is_gift=True).first()+ initial_gift_line_variant = initial_gift_line.variant+ assert initial_gift_line is not None++ # Change gift promotion to a different variant, but since expiration is in future, no recalculation should happen+ new_gift_variant = product.variants.last()+ gift_promotion_rule.gifts.set([new_gift_variant])+ gift_promotion_rule.order_predicate = {"discountedObjectPredicate": {}}+ gift_promotion_rule.save(update_fields=["order_predicate"])++ # Set promotion end date+ end_date = timezone.now() + timedelta(minutes=20)+ gift_promotion_rule.promotion.end_date = end_date+ gift_promotion_rule.promotion.save(update_fields=["end_date"])++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ # then+ assert data["token"] == str(checkout.token)+ assert len(data["lines"]) == lines_count++ # Gift line should NOT be updated to the new variant+ gift_line = checkout.lines.filter(is_gift=True).first()+ assert gift_line.variant == initial_gift_line_variant++ # Verify the response contains the original gift line+ gift_lines = [line for line in data["lines"] if line["isGift"] is True]+ assert len(gift_lines) == 1++ gift_line_data = gift_lines[0]+ assert gift_line_data["id"] == graphene.Node.to_global_id(+ "CheckoutLine", gift_line.pk+ )++ # Verify gift line has correct pricing+ assert gift_line_data["unitPrice"]["gross"]["amount"] == 0+ assert gift_line_data["totalPrice"]["gross"]["amount"] == 0+ assert gift_line_data["undiscountedUnitPrice"]["amount"] > 0++ # Verify NO recalculation happened - both expirations should remain unchanged+ checkout.refresh_from_db()+ assert checkout.discount_expiration == discount_expiration+ assert checkout.price_expiration == price_expirationdiff --git a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py b/saleor/graphql/checkout/tests/test_checkout_price_expiration.pyindex f7ab4bc927..1781ec844e 100644--- a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py+++ b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py@@ -369,7 +369,8 @@ def test_checkout_delivery_method_update_invalidate_prices(def test_invalidate_checkout_with_save(checkout, plugins_manager):# givencheckout.price_expiration = timezone.now() + datetime.timedelta(minutes=5)- checkout.save(update_fields=["price_expiration"])+ checkout.discount_expiration = timezone.now() + datetime.timedelta(minutes=5)+ checkout.save(update_fields=["price_expiration", "discount_expiration"])lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)@@ -381,7 +382,11 @@ def test_invalidate_checkout_with_save(checkout, plugins_manager):# thencheckout.refresh_from_db()assert checkout.price_expiration == timezone.now()- assert updated_fields == ["price_expiration", "last_change"]+ assert updated_fields == [+ "price_expiration",+ "discount_expiration",+ "last_change",+ ]@freeze_time("2020-12-12 12:00:00")@@ -390,7 +395,8 @@ def test_invalidate_checkout_without_save(checkout, plugins_manager):original_expiration = checkout.price_expiration = (timezone.now() + datetime.timedelta(minutes=5))- checkout.save(update_fields=["price_expiration"])+ checkout.discount_expiration = timezone.now() + datetime.timedelta(minutes=5)+ checkout.save(update_fields=["price_expiration", "discount_expiration"])lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)@@ -402,4 +408,8 @@ def test_invalidate_checkout_without_save(checkout, plugins_manager):# thencheckout.refresh_from_db()assert checkout.price_expiration == original_expiration- assert updated_fields == ["price_expiration", "last_change"]+ assert updated_fields == [+ "price_expiration",+ "discount_expiration",+ "last_change",+ ]diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 9ec058e533..642fcf932e 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -91,7 +91,6 @@ from ..webhook.dataloaders.pregenerated_payloads_for_checkout_filter_shipping_mefrom .dataloaders import (CheckoutByTokenLoader,CheckoutInfoByCheckoutTokenLoader,- CheckoutLinesByCheckoutTokenLoader,CheckoutLinesInfoByCheckoutTokenLoader,CheckoutMetadataByCheckoutIdLoader,TransactionItemsByCheckoutIDLoader,@@ -142,6 +141,18 @@ def get_dataloaders_for_fetching_checkout_data()+def get_dataloaders_for_recalculate_discounts(+ root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo+) -> tuple[+ Promise[list["CheckoutLineInfo"]],+ Promise["CheckoutInfo"],+]:+ checkout = root.node+ lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(checkout.token)+ checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(checkout.token)+ return lines, checkout_info++class CheckoutLineProblemInsufficientStock(SyncWebhookControlContextObjectType[problems.CheckoutLineProblemInsufficientStock],):@@ -1170,19 +1181,23 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):def resolve_lines(root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo):- def _wrap_with_sync_webhook_control_context(lines):- return [+ @allow_writer_in_context(info.context)+ def get_lines(data):+ lines_info, checkout_info = data+ database_connection_name = get_database_connection_name(info.context)+ # we need to recalculate discount as the gift line might be added / changed+ calculations.recalculate_discounts(+ checkout_info, lines_info, database_connection_name+ )+ return (SyncWebhookControlContext(- node=line, allow_sync_webhooks=root.allow_sync_webhooks+ line_info.line, allow_sync_webhooks=root.allow_sync_webhooks)- for line in lines- ]+ for line_info in lines_info+ )- return (- CheckoutLinesByCheckoutTokenLoader(info.context)- .load(root.node.token)- .then(_wrap_with_sync_webhook_control_context)- )+ dataloaders = list(get_dataloaders_for_recalculate_discounts(root, info))+ return Promise.all(dataloaders).then(get_lines)@staticmethod@traced_resolverdiff --git a/saleor/graphql/order/tests/queries/test_order_with_where.py b/saleor/graphql/order/tests/queries/test_order_with_where.pyindex 28bf8056be..6c19f74014 100644--- a/saleor/graphql/order/tests/queries/test_order_with_where.py+++ b/saleor/graphql/order/tests/queries/test_order_with_where.py@@ -577,7 +577,7 @@ def test_order_filter_by_number_nothing_returned(permission_group_manage_orders.user_set.add(staff_api_client.user)variables = {- "where": {"number": {"eq": "123"}},+ "where": {"number": {"eq": "11111111"}},}# whendiff --git a/saleor/graphql/tax/mutations/tax_exemption_manage.py b/saleor/graphql/tax/mutations/tax_exemption_manage.pyindex 4b129ab297..25bcabe478 100644--- a/saleor/graphql/tax/mutations/tax_exemption_manage.py+++ b/saleor/graphql/tax/mutations/tax_exemption_manage.py@@ -95,7 +95,14 @@ class TaxExemptionManage(BaseMutation):if isinstance(obj, Checkout):cls._invalidate_checkout(info, obj)- obj.save(update_fields=["tax_exemption", "price_expiration", "last_change"])+ obj.save(+ update_fields=[+ "tax_exemption",+ "price_expiration",+ "discount_expiration",+ "last_change",+ ]+ )if isinstance(obj, Order):cls.validate_order_status(obj)diff --git a/saleor/shipping/tasks.py b/saleor/shipping/tasks.pyindex 2a150bcc9c..6eff8d52e2 100644--- a/saleor/shipping/tasks.py+++ b/saleor/shipping/tasks.py@@ -17,12 +17,14 @@ def drop_invalid_shipping_methods_relations_for_given_channels():# unlink shipping methods from order and checkout instances# when method is no longer available in given channels+ current_time = timezone.now()Checkout.objects.filter(shipping_method_id__in=shipping_method_ids, channel_id__in=channel_ids).update(shipping_method=None,- price_expiration=timezone.now(),- last_change=timezone.now(),+ price_expiration=current_time,+ discount_expiration=current_time,+ last_change=current_time,)Order.objects.filter(status__in=ORDER_EDITABLE_STATUS,diff --git a/saleor/tests/e2e/checkout/test_checkout_with_gift_promotion_updates.py b/saleor/tests/e2e/checkout/test_checkout_with_gift_promotion_updates.pynew file mode 100644index 0000000000..6c70b45cb4--- /dev/null+++ b/saleor/tests/e2e/checkout/test_checkout_with_gift_promotion_updates.py@@ -0,0 +1,335 @@+"""E2E test for gift promotion with discount price expiration.++This test verifies the complete flow of gift promotions with dynamic updates:+1. Create checkout with a product line+2. Create a gift promotion (order promotion with gift reward)+3. Update shipping - gift line should be added+4. Update gift promotion - change the gift variant+5. Update shipping again - gift line should update with new variant and prices+6. Complete checkout successfully+"""++import pytest++from ..product.utils.preparing_product import prepare_product+from ..promotions.utils.promotion_create import create_promotion+from ..promotions.utils.promotion_rule_create import create_promotion_rule+from ..promotions.utils.promotion_rule_update import update_promotion_rule+from ..shop.utils.preparing_shop import prepare_default_shop+from ..utils import assign_permissions+from .utils import (+ checkout_complete,+ checkout_create,+ checkout_delivery_method_update,+ checkout_dummy_payment_create,+ checkout_lines_add,+)+++def get_checkout_with_lines(api_client, checkout_id):+ """Query checkout with detailed line information including gift lines."""+ query = """+ query Checkout($checkoutId: ID!){+ checkout(id: $checkoutId){+ id+ totalPrice{+ gross{+ amount+ }+ }+ lines {+ id+ isGift+ quantity+ variant {+ id+ name+ }+ unitPrice {+ gross {+ amount+ }+ }+ totalPrice {+ gross {+ amount+ }+ }+ undiscountedUnitPrice {+ amount+ }+ }+ }+ }+ """+ variables = {"checkoutId": checkout_id}+ response = api_client.post_graphql(query, variables)+ content = response.json()+ assert "errors" not in content, f"GraphQL errors: {content.get('errors')}"+ return content["data"]["checkout"]+++def test_checkout_gift_promotion_update_flow(+ e2e_staff_api_client,+ e2e_not_logged_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_orders,+ permission_manage_checkouts,+ permission_manage_discounts,+ shop_permissions,+):+ """Test gift promotion update flow in checkout.++ Checks:+ - Gift line is added when promotion is active+ - Gift line updates when the promotion's gift variant changes+ - Discount recalculation reflects updated gift variant and prices+ - Checkout completes successfully with correct gift line in order+ """+ # Setup permissions+ permissions = [+ *shop_permissions,+ permission_manage_product_types_and_attributes,+ permission_manage_orders,+ permission_manage_checkouts,+ permission_manage_discounts,+ ]+ assign_permissions(e2e_staff_api_client, permissions)++ # Prepare shop data+ shop_data = prepare_default_shop(e2e_staff_api_client)+ channel_id = shop_data["channel"]["id"]+ channel_slug = shop_data["channel"]["slug"]+ warehouse_id = shop_data["warehouse"]["id"]+ shipping_method_id = shop_data["shipping_method"]["id"]++ # Prepare regular product (to be purchased)+ variant_price = 50+ (+ _product_id,+ product_variant_id,+ _product_variant_price,+ ) = prepare_product(+ e2e_staff_api_client,+ warehouse_id,+ channel_id,+ variant_price,+ product_type_slug="regular-product",+ )++ # Prepare another product (to be purchased)+ variant_price = 25+ (+ _product_id_2,+ product_variant_id_2,+ _product_variant_price_2,+ ) = prepare_product(+ e2e_staff_api_client,+ warehouse_id,+ channel_id,+ variant_price,+ product_type_slug="new-product",+ )++ # Prepare two gift products (different variants for testing updates)+ gift1_price = 20+ (+ gift1_product_id,+ gift1_variant_id,+ _gift1_price,+ ) = prepare_product(+ e2e_staff_api_client,+ warehouse_id,+ channel_id,+ gift1_price,+ product_type_slug="gift-product-1",+ )++ gift2_price = 30+ (+ gift2_product_id,+ gift2_variant_id,+ _gift2_price,+ ) = prepare_product(+ e2e_staff_api_client,+ warehouse_id,+ channel_id,+ gift2_price,+ product_type_slug="gift-product-2",+ )++ # Step 1 - Create checkout with regular product+ lines = [+ {"variantId": product_variant_id, "quantity": 1},+ ]+ checkout_data = checkout_create(+ e2e_not_logged_api_client,+ lines,+ channel_slug,+ email="[email protected]",+ )+ checkout_id = checkout_data["id"]+ assert checkout_data["isShippingRequired"] is True++ # Verify only one line (no gift yet)+ checkout_lines = get_checkout_with_lines(e2e_not_logged_api_client, checkout_id)+ assert len(checkout_lines["lines"]) == 1+ assert checkout_lines["lines"][0]["isGift"] is False++ # Step 2 - Create gift promotion (order promotion with gift reward)+ promotion_name = "Gift Promotion Test"+ promotion = create_promotion(+ e2e_staff_api_client,+ promotion_name,+ promotion_type="ORDER",+ )+ promotion_id = promotion["id"]++ # Create promotion rule with gift reward+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}+ }++ promotion_rule_input = {+ "promotion": promotion_id,+ "channels": [channel_id],+ "name": "Gift Rule 1",+ "rewardType": "GIFT",+ "gifts": [gift1_variant_id],+ "orderPredicate": order_predicate,+ }+ promotion_rule = create_promotion_rule(+ e2e_staff_api_client,+ promotion_rule_input,+ )+ promotion_rule_id = promotion_rule["id"]++ # Step 3 - Update shipping method - this should trigger discount recalculation+ # and add the gift line+ checkout_data = checkout_delivery_method_update(+ e2e_not_logged_api_client,+ checkout_id,+ shipping_method_id,+ )+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id++ # Verify gift line was added+ checkout_lines = get_checkout_with_lines(e2e_not_logged_api_client, checkout_id)+ assert len(checkout_lines["lines"]) == 2++ # Find gift line+ gift_lines = [line for line in checkout_lines["lines"] if line["isGift"]]+ regular_lines = [line for line in checkout_lines["lines"] if not line["isGift"]]++ assert len(gift_lines) == 1+ assert len(regular_lines) == 1++ # Verify gift line details+ gift_line = gift_lines[0]+ assert gift_line["variant"]["id"] == gift1_variant_id+ assert gift_line["unitPrice"]["gross"]["amount"] == 0 # Gift should be free+ assert gift_line["totalPrice"]["gross"]["amount"] == 0+ assert gift_line["undiscountedUnitPrice"]["amount"] == gift1_price++ # Step 4 - Update gift promotion - change to different gift variant+ promotion_rule_update_input = {+ "addGifts": [gift2_variant_id],+ "removeGifts": [gift1_variant_id],+ }+ update_promotion_rule(+ e2e_staff_api_client,+ promotion_rule_id,+ promotion_rule_update_input,+ )++ # Step 6 - Fetch checkout after promotion update.+ # The gift line should still be the old variant (gift1), as checkout prices+ # do not expired.+ checkout_lines = get_checkout_with_lines(e2e_not_logged_api_client, checkout_id)+ assert len(checkout_lines["lines"]) == 2++ gift_lines = [line for line in checkout_lines["lines"] if line["isGift"]]+ assert len(gift_lines) == 1++ # Gift line should still be the original variant+ gift_line = gift_lines[0]+ assert gift_line["variant"]["id"] == gift1_variant_id+ assert gift_line["unitPrice"]["gross"]["amount"] == 0+ assert gift_line["totalPrice"]["gross"]["amount"] == 0+ assert gift_line["undiscountedUnitPrice"]["amount"] == gift1_price++ # Step 6 - Add new checkout line - this should trigger discount recalculation+ # and update the gift line to new variant+ checkout_data = checkout_lines_add(+ e2e_not_logged_api_client,+ checkout_id,+ [{"variantId": product_variant_id_2, "quantity": 1}],+ )++ # Verify gift line was updated (new variant, new line ID)+ checkout_lines = get_checkout_with_lines(e2e_not_logged_api_client, checkout_id)+ assert len(checkout_lines["lines"]) == 3++ gift_lines = [line for line in checkout_lines["lines"] if line["isGift"]]+ assert len(gift_lines) == 1++ # Verify the gift line changed+ updated_gift_line = gift_lines[0]+ # Verify the gift line changed to the new variant+ assert updated_gift_line["variant"]["id"] == gift2_variant_id++ # Verify new variant details+ assert updated_gift_line["variant"]["id"] == gift2_variant_id+ assert updated_gift_line["unitPrice"]["gross"]["amount"] == 0 # Still free+ assert updated_gift_line["totalPrice"]["gross"]["amount"] == 0+ assert updated_gift_line["undiscountedUnitPrice"]["amount"] == gift2_price++ # Find and validate regular line for product_variant_id+ regular_line_1 = next(+ line+ for line in checkout_lines["lines"]+ if not line["isGift"] and line["variant"]["id"] == product_variant_id+ )+ assert regular_line_1["unitPrice"]["gross"]["amount"] == 50++ # Find and validate regular line for product_variant_id_2+ regular_line_2 = next(+ line+ for line in checkout_lines["lines"]+ if not line["isGift"] and line["variant"]["id"] == product_variant_id_2+ )+ assert regular_line_2["unitPrice"]["gross"]["amount"] == 25++ # Step 7 - Complete checkout+ total_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]++ # Create payment (only for regular product, gift is free)+ checkout_dummy_payment_create(+ e2e_not_logged_api_client,+ checkout_id,+ total_gross_amount,+ )++ # Complete checkout+ order_data = checkout_complete(+ e2e_not_logged_api_client,+ checkout_id,+ )++ # Verify order was created successfully+ assert order_data["status"] == "UNFULFILLED"+ assert order_data["total"]["gross"]["amount"] == total_gross_amount++ # Verify order has both lines (regular + gift)+ order_lines = order_data["lines"]+ assert len(order_lines) == 3++ # Verify gift line in order+ order_gift_lines = [line for line in order_lines if line["isGift"]]+ assert len(order_gift_lines) == 1++ order_gift_line = order_gift_lines[0]+ assert order_gift_line["variant"]["id"] == gift2_variant_id+ assert order_gift_line["unitPrice"]["gross"]["amount"] == 0+ assert order_gift_line["totalPrice"]["gross"]["amount"] == 0diff --git a/saleor/tests/e2e/checkout/utils/checkout_complete.py b/saleor/tests/e2e/checkout/utils/checkout_complete.pyindex de7d777feb..b80ba5732f 100644--- a/saleor/tests/e2e/checkout/utils/checkout_complete.py+++ b/saleor/tests/e2e/checkout/utils/checkout_complete.py@@ -64,11 +64,7 @@ mutation CheckoutComplete($checkoutId: ID!) {lines {idquantity- totalPrice {- gross {- amount- }- }+ isGiftunitPrice {gross {amount@@ -101,6 +97,14 @@ mutation CheckoutComplete($checkoutId: ID!) {amount}}+ totalPrice {+ gross {+ amount+ }+ }+ variant {+ id+ }}discounts {iddiff --git a/saleor/tests/e2e/checkout/utils/checkout_lines_add.py b/saleor/tests/e2e/checkout/utils/checkout_lines_add.pyindex 4fd7d11508..57aba1a9dd 100644--- a/saleor/tests/e2e/checkout/utils/checkout_lines_add.py+++ b/saleor/tests/e2e/checkout/utils/checkout_lines_add.py@@ -6,6 +6,7 @@ mutation checkoutLinesAdd($checkoutId: ID!, $lines: [CheckoutLineInput!]!) {checkout {lines {id+ isGiftquantityvariant {id