Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add reason for price override (#19466) (#19506)
Lukasz Ostrowski6902b62fa490
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 2a7904eddd..bfb2ad2854 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -406,6 +406,7 @@ def _create_line_for_order(base_unit_price=base_unit_price, # money field not supported by mypy_django_plugin # noqa: E501undiscounted_base_unit_price=undiscounted_base_unit_price, # money field not supported by mypy_django_plugin # noqa: E501is_price_overridden=is_price_overridden,+ price_override_reason=checkout_line.price_override_reason,metadata=checkout_line.metadata,private_metadata=checkout_line.private_metadata,**get_tax_class_kwargs_for_order_line(tax_class),diff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.pyindex dc6fa8dd16..d757456617 100644--- a/saleor/checkout/error_codes.py+++ b/saleor/checkout/error_codes.py@@ -12,6 +12,7 @@ class CheckoutErrorCode(Enum):INVALID_SHIPPING_METHOD = "invalid_shipping_method"NOT_FOUND = "not_found"PAYMENT_ERROR = "payment_error"+ PRICE_OVERRIDE_REASON_WITHOUT_OVERRIDE = "price_override_reason_without_override"QUANTITY_GREATER_THAN_LIMIT = "quantity_greater_than_limit"REQUIRED = "required"SHIPPING_ADDRESS_NOT_SET = "shipping_address_not_set"diff --git a/saleor/checkout/migrations/0094_checkoutline_price_override_reason.py b/saleor/checkout/migrations/0094_checkoutline_price_override_reason.pynew file mode 100644index 0000000000..a0780f0b64--- /dev/null+++ b/saleor/checkout/migrations/0094_checkoutline_price_override_reason.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.15 on 2026-07-13 10:28++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0093_propagate_checkout_delivery"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkoutline",+ name="price_override_reason",+ field=models.CharField(blank=True, max_length=255, null=True),+ ),+ ]diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex f6dcd21414..d33eb5b370 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -455,6 +455,7 @@ class CheckoutLine(ModelWithMetadata):blank=True,null=True,)+ price_override_reason = models.CharField(max_length=255, null=True, blank=True)currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,)diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 75042dd3aa..cda8a8a150 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -256,7 +256,8 @@ def add_variants_to_checkout(if to_update:checkout_lines_bulk_update(- to_update, ["quantity", "price_override", "metadata"]+ to_update,+ ["quantity", "price_override", "price_override_reason", "metadata"],)if to_create:@@ -313,6 +314,11 @@ def _append_line_to_update(to_update, to_delete, line_data, replace, line):if line not in to_delete:line.price_override = line_data.custom_priceto_update.append(line)+ if line_data.custom_price_reason_to_update:+ if line not in to_delete:+ line.price_override_reason = line_data.custom_price_reason+ if line not in to_update:+ to_update.append(line)def _append_line_to_delete(to_delete, line_data, line):@@ -341,6 +347,7 @@ def _append_line_to_create(quantity=line_data.quantity,currency=checkout.currency,price_override=line_data.custom_price,+ price_override_reason=line_data.custom_price_reason,undiscounted_unit_price_amount=variant_price_amount,prior_unit_price_amount=variant_prior_price_amount,)diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex cfbed76724..5a2f73718b 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -34,11 +34,13 @@ from ...product.types import ProductVariantfrom ...site.dataloaders import get_site_promisefrom ..types import Checkoutfrom .utils import (+ PRICE_OVERRIDE_REASON_INPUT_DESCRIPTION,apply_gift_reward_if_applicable_on_checkout_creation,check_lines_quantity,check_permissions_for_custom_prices,get_variants_and_total_quantities,group_lines_input_on_add,+ validate_price_override_reason,validate_variants_are_published,validate_variants_available_for_purchase,)@@ -109,6 +111,10 @@ class CheckoutLineInput(BaseInputObjectType):"will be provided multiple times, the last price will be used."),)+ price_override_reason = graphene.String(+ required=False,+ description=PRICE_OVERRIDE_REASON_INPUT_DESCRIPTION,+ )force_new_line = graphene.Boolean(required=False,default_value=False,@@ -262,6 +268,7 @@ class CheckoutCreate(DeprecatedModelMutation, I18nMixin):)checkout_lines_data = group_lines_input_on_add(lines)+ validate_price_override_reason(checkout_lines_data)variant_db_ids = {variant.id for variant in variants}validate_variants_available_for_purchase(variant_db_ids, channel.id)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex 33a229e93f..5042a3dfba 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -35,6 +35,7 @@ from .utils import (get_variants_and_total_quantities,group_lines_input_on_add,mark_checkout_deliveries_as_stale_if_needed,+ validate_price_override_reason,validate_variants_are_published,validate_variants_available_for_purchase,)@@ -173,6 +174,8 @@ class CheckoutLinesAdd(BaseMutation):lines=lines,)+ validate_price_override_reason(checkout_lines_data, lines)+variants_ids_to_validate = {variant.idfor variant, line_data in zip(variants, checkout_lines_data, strict=False)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.pyindex a7991521a3..6ee54bbf5b 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py@@ -22,6 +22,7 @@ from ...utils import ERROR_COULD_NO_RESOLVE_GLOBAL_IDfrom ..types import Checkoutfrom .checkout_lines_add import CheckoutLinesAddfrom .utils import (+ PRICE_OVERRIDE_REASON_INPUT_DESCRIPTION,CheckoutLineData,check_lines_quantity,get_variants_and_total_quantities,@@ -51,6 +52,10 @@ class CheckoutLineUpdateInput(BaseInputObjectType):"will be provided multiple times, the last price will be used."),)+ price_override_reason = graphene.String(+ required=False,+ description=PRICE_OVERRIDE_REASON_INPUT_DESCRIPTION,+ )line_id = graphene.ID(description="ID of the line.",required=False,diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex 35fdd9fd03..1f98f668c6 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -32,6 +32,7 @@ from ....product import models as product_modelsfrom ....product.models import ProductChannelListing, ProductVariantfrom ....warehouse.availability import check_stock_and_preorder_quantity_bulkfrom ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_323from ...core.validators import validate_one_of_args_is_in_mutationfrom ..types import Checkout@@ -54,6 +55,8 @@ class CheckoutLineData:quantity_to_update: bool = Falsecustom_price: Decimal | None = Nonecustom_price_to_update: bool = False+ custom_price_reason: str | None = None+ custom_price_reason_to_update: bool = Falsemetadata_list: list = field(default_factory=list)@@ -358,6 +361,19 @@ def group_lines_input_on_add(if "price" in line:line_data.custom_price = line["price"]line_data.custom_price_to_update = True+ # Reason is per-operation: it is tied to the price-setting operation.+ # Setting a price without a reason clears any previous reason.+ line_data.custom_price_reason = _clean_price_override_reason(+ line.get("price_override_reason")+ )+ line_data.custom_price_reason_to_update = True+ elif "price_override_reason" in line:+ # Reason-only update; allowed when the line already has a price override+ # (enforced later by `validate_price_override_reason`).+ line_data.custom_price_reason = _clean_price_override_reason(+ line.get("price_override_reason")+ )+ line_data.custom_price_reason_to_update = Truegrouped_checkout_lines_data += list(checkout_lines_data_map.values())return grouped_checkout_lines_data@@ -407,6 +423,19 @@ def group_lines_input_data_on_update(if "price" in line:line_data.custom_price = line["price"]line_data.custom_price_to_update = True+ # Reason is per-operation: it is tied to the price-setting operation.+ # Setting a price without a reason clears any previous reason.+ line_data.custom_price_reason = _clean_price_override_reason(+ line.get("price_override_reason")+ )+ line_data.custom_price_reason_to_update = True+ elif "price_override_reason" in line:+ # Reason-only update; allowed when the line already has a price override+ # (enforced later by `validate_price_override_reason`).+ line_data.custom_price_reason = _clean_price_override_reason(+ line.get("price_override_reason")+ )+ line_data.custom_price_reason_to_update = Trueline_data.metadata_list += metadata_list_from_input@@ -420,7 +449,7 @@ def check_permissions_for_custom_prices(app, lines):Checkout line custom price can be changed only by app withhandle checkout permission."""- if any("price" in line for line in lines) and (+ if any("price" in line or "price_override_reason" in line for line in lines) and (not app or not app.has_perm(CheckoutPermissions.HANDLE_CHECKOUTS)):raise PermissionDenied(@@ -429,6 +458,66 @@ def check_permissions_for_custom_prices(app, lines):)+PRICE_OVERRIDE_REASON_MAX_LENGTH = models.CheckoutLine._meta.get_field(+ "price_override_reason"+).max_length++PRICE_OVERRIDE_REASON_INPUT_DESCRIPTION = (+ "Reason explaining why a custom `price` was set on the line, for debugging "+ "and auditing. Can be set only by apps with `HANDLE_CHECKOUTS` permission and "+ "only when the line has a `price` override. Setting a new `price` without a "+ "reason clears the previous reason. Blank values are stored as no reason. "+ "Limited to 255 characters; longer values are truncated." + ADDED_IN_323+)+++def _clean_price_override_reason(reason: str | None) -> str | None:+ """Normalize a price override reason.++ Blank strings are treated as no reason and the value is truncated to the+ stored column's max length so an over-long reason cannot crash on save.+ """+ if reason is None:+ return None+ reason = reason.strip()[:PRICE_OVERRIDE_REASON_MAX_LENGTH]+ return reason or None+++def validate_price_override_reason(+ checkout_lines_data: list[CheckoutLineData],+ existing_lines_info: list[CheckoutLineInfo] | None = None,+):+ """Reject a price override reason that is not backed by a price override.++ A reason may only be stored when the line has a price override - either set in+ the same operation or already present on the line.+ """+ existing_override_by_line_id = {+ str(line_info.line.pk): line_info.line.price_override+ for line_info in (existing_lines_info or [])+ }+ for line_data in checkout_lines_data:+ reason_is_set = (+ line_data.custom_price_reason_to_update+ and line_data.custom_price_reason is not None+ )+ if not reason_is_set:+ continue+ # When the same operation sets the price, only the incoming value counts -+ # a null price clears the override, so the existing one must not be credited.+ if line_data.custom_price_to_update:+ effective_override = line_data.custom_price+ elif line_data.line_id:+ effective_override = existing_override_by_line_id.get(line_data.line_id)+ else:+ effective_override = None+ if effective_override is None:+ raise ValidationError(+ "Cannot set priceOverrideReason without a price override on the line.",+ code=CheckoutErrorCode.PRICE_OVERRIDE_REASON_WITHOUT_OVERRIDE.value,+ )++def find_line_id_when_variant_parameter_used(variant_db_id: str, lines_info: list[CheckoutLineInfo]) -> None | str:diff --git a/saleor/graphql/checkout/tests/mutations/test_price_override_reason.py b/saleor/graphql/checkout/tests/mutations/test_price_override_reason.pynew file mode 100644index 0000000000..492a15caf3--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_price_override_reason.py@@ -0,0 +1,697 @@+"""Tests for the `priceOverrideReason` field on checkout / order lines.++Feature spec: .context/price-override-reason-scenarios.md++An app with HANDLE_CHECKOUTS may record *why* it set a custom price on a checkout+line. The reason is stored natively, carried onto the order line at completion, and+readable by staff/app (dashboard + subscription webhooks). Strict contract,+per-operation semantics.+"""++from decimal import Decimal++import graphene++from .....checkout.error_codes import CheckoutErrorCode+from .....checkout.models import Checkout, CheckoutLine+from .....order import OrderOrigin, OrderStatus+from .....order.models import Order+from ....core.utils import to_global_id_or_none+from ....tests.utils import (+ assert_no_permission,+ get_graphql_content,+)++CHECKOUT_LINES_ADD = """+ mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {+ checkoutLinesAdd(id: $id, lines: $lines) {+ checkout { id }+ errors { field code message }+ }+ }+"""++CHECKOUT_CREATE = """+ mutation checkoutCreate($input: CheckoutCreateInput!) {+ checkoutCreate(input: $input) {+ checkout { id token }+ errors { field code message }+ }+ }+"""++CHECKOUT_LINES_UPDATE = """+ mutation checkoutLinesUpdate($id: ID, $lines: [CheckoutLineUpdateInput!]!) {+ checkoutLinesUpdate(id: $id, lines: $lines) {+ checkout { id }+ errors { field code message }+ }+ }+"""++CHECKOUT_LINE_REASON_QUERY = """+ query getCheckout($id: ID) {+ checkout(id: $id) {+ lines {+ priceOverrideReason+ }+ }+ }+"""++ORDER_LINE_REASON_QUERY = """+ query OrdersQuery {+ orders(first: 1) {+ edges {+ node {+ lines {+ priceOverrideReason+ }+ }+ }+ }+ }+"""++MUTATION_CHECKOUT_COMPLETE = """+ mutation checkoutComplete($id: ID, $redirectUrl: String) {+ checkoutComplete(id: $id, redirectUrl: $redirectUrl) {+ order { id }+ errors { field message code }+ }+ }+"""++REASON_WITHOUT_OVERRIDE_MESSAGE = (+ "Cannot set priceOverrideReason without a price override on the line."+)+++# --- 1. Writing the reason (checkout, app-only) ---------------------------------+++def test_lines_add_sets_price_override_reason(+ app_api_client, checkout, stock, permission_handle_checkouts+):+ # given+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")+ reason = "Loyalty pricing rule #42"++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ "price": price,+ "priceOverrideReason": reason,+ }+ ],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_ADD, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert data["errors"] == []+ checkout.refresh_from_db()+ line = checkout.lines.last()+ assert line.price_override == price+ assert line.price_override_reason == reason+++def test_lines_add_price_without_reason_stores_null(+ app_api_client, checkout, stock, permission_handle_checkouts+):+ # given+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_ADD, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutLinesAdd"]["errors"] == []+ checkout.refresh_from_db()+ line = checkout.lines.last()+ assert line.price_override == price+ assert line.price_override_reason is None+++def test_lines_add_reason_without_override_raises_error(+ app_api_client, checkout, stock, permission_handle_checkouts+):+ # given+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ reason = "Reason without a price"++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [+ {"variantId": variant_id, "quantity": 1, "priceOverrideReason": reason}+ ],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_ADD, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesAdd"]["errors"]+ assert len(errors) == 1+ assert (+ errors[0]["code"]+ == CheckoutErrorCode.PRICE_OVERRIDE_REASON_WITHOUT_OVERRIDE.name+ )+ assert errors[0]["message"] == REASON_WITHOUT_OVERRIDE_MESSAGE+++def test_lines_add_reason_by_app_no_perm(app_api_client, checkout, stock):+ # given+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ "price": Decimal("13.11"),+ "priceOverrideReason": "not allowed without perm",+ }+ ],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = app_api_client.post_graphql(CHECKOUT_LINES_ADD, variables)++ # then+ assert_no_permission(response)+++def test_create_sets_price_override_reason(+ app_api_client,+ stock,+ graphql_address_data,+ channel_USD,+ permission_handle_checkouts,+):+ # given+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ price = Decimal("12.25")+ reason = "Contract price"++ variables = {+ "input": {+ "channel": channel_USD.slug,+ "lines": [+ {+ "quantity": 1,+ "variantId": variant_id,+ "price": price,+ "priceOverrideReason": reason,+ }+ ],+ "email": "[email protected]",+ "shippingAddress": graphql_address_data,+ }+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_CREATE, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutCreate"]["errors"] == []+ checkout_line = Checkout.objects.first().lines.first()+ assert checkout_line.price_override == price+ assert checkout_line.price_override_reason == reason+++# --- 2. Normalization -----------------------------------------------------------+++def test_lines_add_empty_reason_stored_as_null(+ app_api_client, checkout, stock, permission_handle_checkouts+):+ # given+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ "price": price,+ "priceOverrideReason": " ",+ }+ ],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_ADD, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutLinesAdd"]["errors"] == []+ checkout.refresh_from_db()+ line = checkout.lines.last()+ assert line.price_override == price+ assert line.price_override_reason is None+++def test_lines_add_reason_truncated_to_max_length(+ app_api_client, checkout, stock, permission_handle_checkouts+):+ # given+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")+ max_length = CheckoutLine._meta.get_field("price_override_reason").max_length+ reason = "x" * (max_length + 50)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ "price": price,+ "priceOverrideReason": reason,+ }+ ],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_ADD, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutLinesAdd"]["errors"] == []+ checkout.refresh_from_db()+ line = checkout.lines.last()+ assert line.price_override_reason == reason[:max_length]+ assert len(line.price_override_reason) == max_length+++# --- 3. Update semantics on checkoutLinesUpdate (per-operation) ------------------+++def test_lines_update_new_price_and_reason(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ # given+ checkout = checkout_with_item+ line = checkout.lines.first()+ line.price_override = Decimal("10.00")+ line.price_override_reason = "old"+ line.save(update_fields=["price_override", "price_override_reason"])+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ new_price = Decimal("12.00")+ new_reason = "new"++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ "price": new_price,+ "priceOverrideReason": new_reason,+ }+ ],+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_UPDATE, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutLinesUpdate"]["errors"] == []+ line.refresh_from_db()+ assert line.price_override == new_price+ assert line.price_override_reason == new_reason+++def test_lines_update_new_price_without_reason_nulls_reason(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ # given+ checkout = checkout_with_item+ line = checkout.lines.first()+ line.price_override = Decimal("10.00")+ line.price_override_reason = "old"+ line.save(update_fields=["price_override", "price_override_reason"])+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ new_price = Decimal("12.00")++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": new_price}],+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_UPDATE, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutLinesUpdate"]["errors"] == []+ line.refresh_from_db()+ assert line.price_override == new_price+ assert line.price_override_reason is None+++def test_lines_update_clear_price_clears_reason(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ # given+ checkout = checkout_with_item+ line = checkout.lines.first()+ line.price_override = Decimal("10.00")+ line.price_override_reason = "old"+ line.save(update_fields=["price_override", "price_override_reason"])+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": None}],+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_UPDATE, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutLinesUpdate"]["errors"] == []+ line.refresh_from_db()+ assert line.price_override is None+ assert line.price_override_reason is None+++def test_lines_update_reason_only_when_override_exists(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ # given+ checkout = checkout_with_item+ line = checkout.lines.first()+ price = Decimal("10.00")+ line.price_override = price+ line.price_override_reason = "old"+ line.save(update_fields=["price_override", "price_override_reason"])+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ corrected = "corrected"++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "priceOverrideReason": corrected}],+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_UPDATE, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutLinesUpdate"]["errors"] == []+ line.refresh_from_db()+ assert line.price_override == price+ assert line.price_override_reason == corrected+++def test_lines_update_reason_only_without_override_raises(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ # given+ checkout = checkout_with_item+ line = checkout.lines.first()+ assert line.price_override is None+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "priceOverrideReason": "orphan"}],+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_UPDATE, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesUpdate"]["errors"]+ assert len(errors) == 1+ assert (+ errors[0]["code"]+ == CheckoutErrorCode.PRICE_OVERRIDE_REASON_WITHOUT_OVERRIDE.name+ )+ assert errors[0]["message"] == REASON_WITHOUT_OVERRIDE_MESSAGE+++def test_lines_update_clear_price_with_reason_raises(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ # given+ checkout = checkout_with_item+ line = checkout.lines.first()+ price = Decimal("10.00")+ reason = "old"+ line.price_override = price+ line.price_override_reason = reason+ line.save(update_fields=["price_override", "price_override_reason"])+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)++ # clearing the override and setting a reason in the same operation must be+ # rejected - the reason would otherwise be orphaned (no price override left).+ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ "price": None,+ "priceOverrideReason": "still here",+ }+ ],+ }++ # when+ response = app_api_client.post_graphql(+ CHECKOUT_LINES_UPDATE, variables, permissions=[permission_handle_checkouts]+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesUpdate"]["errors"]+ assert len(errors) == 1+ assert (+ errors[0]["code"]+ == CheckoutErrorCode.PRICE_OVERRIDE_REASON_WITHOUT_OVERRIDE.name+ )+ assert errors[0]["message"] == REASON_WITHOUT_OVERRIDE_MESSAGE+ line.refresh_from_db()+ assert line.price_override == price+ assert line.price_override_reason == reason+++# --- 4. Checkout -> Order conversion --------------------------------------------+++def test_complete_copies_price_override_reason_to_order_line(+ user_api_client,+ checkout_with_item,+ address,+ checkout_delivery,+ shipping_method,+):+ # given+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)+ checkout.billing_address = address+ checkout.tax_exemption = True+ checkout.save()++ line = checkout.lines.first()+ reason = "rule #42"+ line.price_override = Decimal(2)+ line.price_override_reason = reason+ line.save(update_fields=["price_override", "price_override_reason"])++ channel = checkout.channel+ channel.allow_unpaid_orders = True+ channel.save(update_fields=["allow_unpaid_orders"])++ variables = {+ "id": to_global_id_or_none(checkout),+ "redirectUrl": "https://www.example.com",+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutComplete"]["errors"] == []+ order = Order.objects.get()+ assert order.status == OrderStatus.UNCONFIRMED+ assert order.origin == OrderOrigin.CHECKOUT+ order_line = order.lines.get()+ assert order_line.is_price_overridden+ assert order_line.price_override_reason == reason+++def test_complete_without_override_leaves_reason_null(+ user_api_client,+ checkout_with_item,+ address,+ checkout_delivery,+ shipping_method,+):+ # given+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)+ checkout.billing_address = address+ checkout.tax_exemption = True+ checkout.save()++ channel = checkout.channel+ channel.allow_unpaid_orders = True+ channel.save(update_fields=["allow_unpaid_orders"])++ variables = {+ "id": to_global_id_or_none(checkout),+ "redirectUrl": "https://www.example.com",+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["checkoutComplete"]["errors"] == []+ order_line = Order.objects.get().lines.get()+ assert not order_line.is_price_overridden+ assert order_line.price_override_reason is None+++# --- 5. Reading the reason ------------------------------------------------------+++def test_query_checkout_line_reason_by_staff(+ staff_api_client, checkout_with_item, permission_manage_checkouts+):+ # given+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)+ line = checkout_with_item.lines.first()+ reason = "rule #42"+ line.price_override = Decimal("10.00")+ line.price_override_reason = reason+ line.save(update_fields=["price_override", "price_override_reason"])+ variables = {"id": to_global_id_or_none(checkout_with_item)}++ # when+ response = staff_api_client.post_graphql(CHECKOUT_LINE_REASON_QUERY, variables)++ # then+ content = get_graphql_content(response)+ lines = content["data"]["checkout"]["lines"]+ assert lines[0]["priceOverrideReason"] == reason+++def test_query_checkout_line_reason_by_app(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ # given+ app_api_client.app.permissions.add(permission_handle_checkouts)+ line = checkout_with_item.lines.first()+ reason = "rule #42"+ line.price_override = Decimal("10.00")+ line.price_override_reason = reason+ line.save(update_fields=["price_override", "price_override_reason"])+ variables = {"id": to_global_id_or_none(checkout_with_item)}++ # when+ response = app_api_client.post_graphql(CHECKOUT_LINE_REASON_QUERY, variables)++ # then+ content = get_graphql_content(response)+ lines = content["data"]["checkout"]["lines"]+ assert lines[0]["priceOverrideReason"] == reason+++def test_query_checkout_line_reason_no_permission(user_api_client, checkout_with_item):+ # given+ line = checkout_with_item.lines.first()+ line.price_override = Decimal("10.00")+ line.price_override_reason = "rule #42"+ line.save(update_fields=["price_override", "price_override_reason"])+ variables = {"id": to_global_id_or_none(checkout_with_item)}++ # when+ response = user_api_client.post_graphql(CHECKOUT_LINE_REASON_QUERY, variables)++ # then+ assert_no_permission(response)+++def test_query_order_line_reason_by_app(+ app_api_client, order_line, permission_manage_orders+):+ # given+ app_api_client.app.permissions.add(permission_manage_orders)+ reason = "rule #42"+ order_line.is_price_overridden = True+ order_line.price_override_reason = reason+ order_line.save(update_fields=["is_price_overridden", "price_override_reason"])++ # when+ response = app_api_client.post_graphql(ORDER_LINE_REASON_QUERY)++ # then+ content = get_graphql_content(response)+ node = content["data"]["orders"]["edges"][0]["node"]+ assert node["lines"][0]["priceOverrideReason"] == reasondiff --git a/saleor/graphql/checkout/tests/mutations/test_utils.py b/saleor/graphql/checkout/tests/mutations/test_utils.pyindex 24ee36efad..1cf2a8f73a 100644--- a/saleor/graphql/checkout/tests/mutations/test_utils.py+++ b/saleor/graphql/checkout/tests/mutations/test_utils.py@@ -66,6 +66,7 @@ def test_group_on_add_when_same_variants_in_multiple_lines_and_price_provided():quantity_to_update=True,custom_price=1.22,custom_price_to_update=True,+ custom_price_reason_to_update=True,),CheckoutLineData(variant_id="2",@@ -74,6 +75,7 @@ def test_group_on_add_when_same_variants_in_multiple_lines_and_price_provided():quantity_to_update=True,custom_price=10,custom_price_to_update=True,+ custom_price_reason_to_update=True,),]@@ -107,6 +109,7 @@ def test_group_on_add_when_same_variants_in_multiple_lines_and_force_new_line():quantity_to_update=True,custom_price=1.22,custom_price_to_update=True,+ custom_price_reason_to_update=True,),CheckoutLineData(variant_id="2",@@ -115,6 +118,7 @@ def test_group_on_add_when_same_variants_in_multiple_lines_and_force_new_line():quantity_to_update=True,custom_price=10,custom_price_to_update=True,+ custom_price_reason_to_update=True,),]@@ -138,6 +142,7 @@ def test_group_on_update_when_line_id_as_parameter_provided():quantity_to_update=True,custom_price=1.22,custom_price_to_update=True,+ custom_price_reason_to_update=True,),CheckoutLineData(variant_id=None,@@ -146,6 +151,7 @@ def test_group_on_update_when_line_id_as_parameter_provided():quantity_to_update=True,custom_price=10,custom_price_to_update=True,+ custom_price_reason_to_update=True,),]@@ -174,6 +180,7 @@ def test_group_on_update_when_one_line_and_mixed_parameters_provided(quantity_to_update=True,custom_price=10,custom_price_to_update=True,+ custom_price_reason_to_update=True,)]assert expected == group_lines_input_data_on_update(diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex d10da652c9..f3b096305b 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -332,6 +332,17 @@ class CheckoutLine(SyncWebhookControlContextModelObjectType[models.CheckoutLine]is_gift = graphene.Boolean(description="Determine if the line is a gift." + PREVIEW_FEATURE,)+ price_override_reason = PermissionsField(+ graphene.String,+ description=(+ "Reason explaining why a custom price was set on the line, provided by "+ "the app that set the price override." + ADDED_IN_323+ ),+ permissions=[+ CheckoutPermissions.MANAGE_CHECKOUTS,+ CheckoutPermissions.HANDLE_CHECKOUTS,+ ],+ )class Meta:default_resolver = (diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 3be1ff980f..45496e04a8 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -1178,6 +1178,15 @@ class OrderLine(is_price_overridden = graphene.Boolean(description="Returns True, if the line unit price was overridden.")+ price_override_reason = PermissionsField(+ graphene.String,+ description=(+ "Reason explaining why a custom price was set on the line, copied from "+ "the checkout line when the order was created from a checkout."+ + ADDED_IN_323+ ),+ permissions=[OrderPermissions.MANAGE_ORDERS],+ )variant = graphene.Field(ProductVariant,required=False,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 9c4d038de2..6f2582c71f 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -11535,6 +11535,15 @@ type CheckoutLine implements Node & ObjectWithMetadata @doc(category: "Checkout"Note: this API is currently in Feature Preview and can be subject to changes at later point."""isGift: Boolean++ """+ Reason explaining why a custom price was set on the line, provided by the app that set the price override.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_CHECKOUTS, HANDLE_CHECKOUTS.+ """+ priceOverrideReason: String}"""Represents an problem in the checkout line."""@@ -12261,6 +12270,15 @@ type OrderLine implements Node & ObjectWithMetadata @doc(category: "Orders") {"""Returns True, if the line unit price was overridden."""isPriceOverridden: Boolean+ """+ Reason explaining why a custom price was set on the line, copied from the checkout line when the order was created from a checkout.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_ORDERS.+ """+ priceOverrideReason: String+"""A purchased product variant. Note: this field may be null if the variant has been removed from stock at all. Requires one of the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS."""@@ -30628,6 +30646,7 @@ enum CheckoutErrorCode @doc(category: "Checkout") {INVALID_SHIPPING_METHODNOT_FOUNDPAYMENT_ERROR+ PRICE_OVERRIDE_REASON_WITHOUT_OVERRIDEQUANTITY_GREATER_THAN_LIMITREQUIREDSHIPPING_ADDRESS_NOT_SET@@ -30797,6 +30816,13 @@ input CheckoutLineInput @doc(category: "Checkout") {"""price: PositiveDecimal+ """+ Reason explaining why a custom `price` was set on the line, for debugging and auditing. Can be set only by apps with `HANDLE_CHECKOUTS` permission and only when the line has a `price` override. Setting a new `price` without a reason clears the previous reason. Blank values are stored as no reason. Limited to 255 characters; longer values are truncated.++ Added in Saleor 3.23.+ """+ priceOverrideReason: String+"""Flag that allow force splitting the same variant into multiple lines by skipping the matching logic."""@@ -31021,6 +31047,13 @@ input CheckoutLineUpdateInput @doc(category: "Checkout") {"""price: PositiveDecimal+ """+ Reason explaining why a custom `price` was set on the line, for debugging and auditing. Can be set only by apps with `HANDLE_CHECKOUTS` permission and only when the line has a `price` override. Setting a new `price` without a reason clears the previous reason. Blank values are stored as no reason. Limited to 255 characters; longer values are truncated.++ Added in Saleor 3.23.+ """+ priceOverrideReason: String+"""ID of the line."""lineId: IDdiff --git a/saleor/order/migrations/0227_orderline_price_override_reason.py b/saleor/order/migrations/0227_orderline_price_override_reason.pynew file mode 100644index 0000000000..d7d605829a--- /dev/null+++ b/saleor/order/migrations/0227_orderline_price_override_reason.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.15 on 2026-07-13 10:28++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0226_grantedrefundline_reason_ref_idx"),+ ]++ operations = [+ migrations.AddField(+ model_name="orderline",+ name="price_override_reason",+ field=models.CharField(blank=True, max_length=255, null=True),+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 0a68987b50..a6296532db 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -716,6 +716,7 @@ class OrderLine(ModelWithMetadata):)is_price_overridden = models.BooleanField(null=True, blank=True)+ price_override_reason = models.CharField(max_length=255, null=True, blank=True)# Fulfilled when voucher code was used for product in the linevoucher_code = models.CharField(max_length=255, null=True, blank=True)