Skip to content

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

ENG-233: Allowing to reference a refund reason (#18026)

Lukasz Ostrowskid754a9132c2e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b97e25faad..ea15b5df28 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -94,6 +94,7 @@ Like `reference`, the `single-reference` type can target entities defined in the
- Added support for filtering by associated reference objects (e.g., `products`, `pages`, `variants`)
- Added `fractionalAmount` and `fractionDigits` fields to the `Money` type. These fields allow monetary values to be represented as a pair of integers, which is often required when integrating with payment service providers.
- Add support for filtering `productVariants` by associated attributes
+- Refunds are now more powerful. You can configure new `RefundSettings` to accept a `reasonReferenceType`. Once assigned, creating refunds (both manual and with grant refunds) will require a reason type to be specified. `refundReasonReferenceTypeClear` clears the settings.
- You can now use the `AssignedAttribute` interface and the `assignedAttribute`, `assignedAttributes` fields on `Page`, `Product`, and `ProductVariant` to fetch assigned attributes and their values in a cleaner, more focused shape.
- `attribute` and `attributes` fields on Page, Product, and ProductVariant are deprecated.
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 0c30eb68c6..0af22a946c 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -45,6 +45,7 @@ from .doc_category import (
DOC_CATEGORY_PAYMENTS,
DOC_CATEGORY_PRODUCTS,
DOC_CATEGORY_SHIPPING,
+ DOC_CATEGORY_SHOP,
DOC_CATEGORY_USERS,
DOC_CATEGORY_WEBHOOKS,
)
@@ -224,6 +225,11 @@ GiftCardSettingsErrorCode = graphene.Enum.from_enum(
)
GiftCardSettingsErrorCode.doc_category = DOC_CATEGORY_GIFT_CARDS
+RefundSettingsErrorCode = graphene.Enum.from_enum(
+ site_error_codes.RefundSettingsErrorCode
+)
+RefundSettingsErrorCode.doc_category = DOC_CATEGORY_SHOP
+
MetadataErrorCode = graphene.Enum.from_enum(core_error_codes.MetadataErrorCode)
OrderErrorCode = graphene.Enum.from_enum(order_error_codes.OrderErrorCode)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index b739a14da9..83a9ba0664 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -68,6 +68,7 @@ from ..enums import (
ProductTranslateErrorCode,
ProductVariantBulkErrorCode,
ProductVariantTranslateErrorCode,
+ RefundSettingsErrorCode,
SendConfirmationEmailErrorCode,
ShippingErrorCode,
ShopErrorCode,
@@ -352,6 +353,24 @@ class GiftCardSettingsError(Error):
doc_category = DOC_CATEGORY_GIFT_CARDS
+class RefundSettingsUpdateError(Error):
+ code = RefundSettingsErrorCode(
+ description="Failed to update Refund Settings", required=True
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_SHOP
+
+
+class RefundReasonReferenceTypeClearError(Error):
+ code = RefundSettingsErrorCode(
+ description="Failed to clear refund reason reference type", required=True
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_SHOP
+
+
class MetadataError(Error):
code = MetadataErrorCode(description="The error code.", required=True)
diff --git a/saleor/graphql/order/mutations/order_grant_refund_create.py b/saleor/graphql/order/mutations/order_grant_refund_create.py
index 89044656ad..256c9e407c 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_create.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_create.py
@@ -7,16 +7,18 @@ from django.db import transaction
from ....order import models
from ....order.utils import update_order_charge_data
+from ....page.models import Page
from ....permission.enums import OrderPermissions
from ...core import ResolveInfo
from ...core.context import SyncWebhookControlContext
-from ...core.descriptions import ADDED_IN_320, PREVIEW_FEATURE
+from ...core.descriptions import ADDED_IN_320, ADDED_IN_322, PREVIEW_FEATURE
from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.mutations import BaseMutation
from ...core.scalars import Decimal
from ...core.types import BaseInputObjectType
from ...core.types.common import Error, NonNullList
from ...payment.mutations.transaction.utils import get_transaction_item
+from ...payment.utils import validate_and_resolve_refund_reason_context
from ..enums import OrderGrantRefundCreateErrorCode, OrderGrantRefundCreateLineErrorCode
from ..types import Order, OrderGrantedRefund
from .order_grant_refund_utils import (
@@ -68,6 +70,9 @@ class OrderGrantRefundCreateInput(BaseInputObjectType):
)
)
reason = graphene.String(description="Reason of the granted refund.")
+ reason_reference = graphene.ID(
+ description="ID of a `Page` (Model) to reference in reason." + ADDED_IN_322
+ )
lines = NonNullList(
OrderGrantRefundCreateLineInput,
description="Lines to assign to granted refund.",
@@ -182,6 +187,32 @@ class OrderGrantRefundCreate(BaseMutation):
}
)
+ @classmethod
+ def _resolve_refund_reason_instance(
+ cls, /, reason_reference_id: str, refund_reason_reference_type_id: int
+ ):
+ reason_reference_pk = cls.get_global_id_or_error(
+ reason_reference_id, only_type="Page", field="reason_reference"
+ )
+
+ try:
+ reason_reference_instance = Page.objects.get(
+ pk=reason_reference_pk,
+ page_type=refund_reason_reference_type_id,
+ )
+
+ return reason_reference_instance
+
+ except Page.DoesNotExist:
+ raise ValidationError(
+ {
+ "reason_reference": ValidationError(
+ "Invalid reason reference. Must be an ID of a Model (Page)",
+ code=OrderGrantRefundCreateErrorCode.INVALID.value,
+ )
+ }
+ ) from None
+
@classmethod
def clean_input(
cls,
@@ -194,6 +225,7 @@ class OrderGrantRefundCreate(BaseMutation):
transaction_id = input.get("transaction_id")
input_lines = input.get("lines", [])
grant_refund_for_shipping = input.get("grant_refund_for_shipping", False)
+ reason_reference_id = input.get("reason_reference")
cls.validate_input(input)
@@ -254,12 +286,35 @@ class OrderGrantRefundCreate(BaseMutation):
}
)
+ requestor_is_app = info.context.app is not None
+ requestor_is_user = info.context.user is not None and not requestor_is_app
+
+ refund_reason_context = validate_and_resolve_refund_reason_context(
+ reason_reference_id=reason_reference_id,
+ requestor_is_user=bool(requestor_is_user),
+ refund_reference_field_name="reason_reference",
+ error_code_enum=OrderGrantRefundCreateErrorCode,
+ )
+
+ should_apply = refund_reason_context["should_apply"]
+ refund_reason_reference_type = refund_reason_context[
+ "refund_reason_reference_type"
+ ]
+
+ reason_reference_instance: Page | None = None
+
+ if should_apply:
+ reason_reference_instance = cls._resolve_refund_reason_instance(
+ str(reason_reference_id), refund_reason_reference_type.pk
+ )
+
return {
"amount": amount,
"reason": reason,
"lines": cleaned_input_lines,
"grant_refund_for_shipping": grant_refund_for_shipping,
"transaction_item": transaction_item,
+ "reason_reference_instance": reason_reference_instance,
}
@classmethod
@@ -273,6 +328,7 @@ class OrderGrantRefundCreate(BaseMutation):
cleaned_input_lines = cleaned_input["lines"]
grant_refund_for_shipping = cleaned_input["grant_refund_for_shipping"]
transaction_item = cleaned_input["transaction_item"]
+ reason_reference_instance = cleaned_input["reason_reference_instance"]
with transaction.atomic():
granted_refund = order.granted_refunds.create(
@@ -283,6 +339,7 @@ class OrderGrantRefundCreate(BaseMutation):
app=info.context.app,
shipping_costs_included=grant_refund_for_shipping or False,
transaction_item=transaction_item,
+ reason_reference=reason_reference_instance,
)
if cleaned_input_lines:
for line in cleaned_input_lines:
diff --git a/saleor/graphql/order/mutations/order_grant_refund_update.py b/saleor/graphql/order/mutations/order_grant_refund_update.py
index b1330441bc..1d86e4da1e 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_update.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_update.py
@@ -7,10 +7,11 @@ from graphql import GraphQLError
from ....order import OrderGrantedRefundStatus, models
from ....order.utils import update_order_charge_data
+from ....page.models import Page
from ....permission.enums import OrderPermissions
from ...core import ResolveInfo
from ...core.context import SyncWebhookControlContext
-from ...core.descriptions import ADDED_IN_320, PREVIEW_FEATURE
+from ...core.descriptions import ADDED_IN_320, ADDED_IN_322, PREVIEW_FEATURE
from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.mutations import BaseMutation
from ...core.scalars import Decimal
@@ -18,6 +19,7 @@ from ...core.types import BaseInputObjectType
from ...core.types.common import Error, NonNullList
from ...core.utils import from_global_id_or_error
from ...payment.types import TransactionItem
+from ...payment.utils import validate_and_resolve_refund_reason_context
from ..enums import OrderGrantRefundUpdateErrorCode, OrderGrantRefundUpdateLineErrorCode
from ..types import Order, OrderGrantedRefund
from .order_grant_refund_utils import (
@@ -75,6 +77,9 @@ class OrderGrantRefundUpdateInput(BaseInputObjectType):
)
)
reason = graphene.String(description="Reason of the granted refund.")
+ reason_reference = graphene.ID(
+ description="ID of a `Page` (Model) to reference in reason." + ADDED_IN_322
+ )
add_lines = NonNullList(
OrderGrantRefundUpdateLineAddInput,
description="Lines to assign to granted refund.",
@@ -243,6 +248,30 @@ class OrderGrantRefundUpdate(BaseMutation):
return list(input_lines_data.values())
+ @classmethod
+ def _resolve_refund_reason_instance(
+ cls, /, reason_reference_id: str, refund_reason_reference_type: int
+ ):
+ reason_reference_pk = cls.get_global_id_or_error(
+ reason_reference_id, only_type="Page", field="reason_reference"
+ )
+
+ try:
+ return Page.objects.get(
+ pk=reason_reference_pk,
+ page_type=refund_reason_reference_type,
+ )
+
+ except (Page.DoesNotExist, ValueError):
+ raise ValidationError(
+ {
+ "reason_reference": ValidationError(
+ "Invalid reason reference. Must be an ID of a Model (Page)",
+ code=OrderGrantRefundUpdateErrorCode.INVALID.value,
+ )
+ }
+ ) from None
+
@classmethod
def clean_input(
cls,
@@ -261,6 +290,10 @@ class OrderGrantRefundUpdate(BaseMutation):
add_lines = input.get("add_lines", [])
remove_lines = input.get("remove_lines", [])
grant_refund_for_shipping = input.get("grant_refund_for_shipping", None)
+ reason_reference_id = input.get("reason_reference")
+
+ requestor_is_app = info.context.app is not None
+ requestor_is_user = info.context.user is not None and not requestor_is_app
line_ids_to_remove = []
if remove_lines:
@@ -343,13 +376,35 @@ class OrderGrantRefundUpdate(BaseMutation):
if errors:
raise ValidationError(errors)
+ refund_reason_context = validate_and_resolve_refund_reason_context(
+ reason_reference_id=reason_reference_id,
+ requestor_is_user=bool(requestor_is_user),
+ refund_reference_field_name="reason_reference",
+ error_code_enum=OrderGrantRefundUpdateErrorCode,
+ )
+
+ should_apply = refund_reason_context["should_apply"]
+ refund_reason_reference_type = refund_reason_context[
+ "refund_reason_reference_type"
+ ]
+
+ reason_reference_instance: Page | None = None
+
+ if should_apply:
+ reason_reference_instance = cls._resolve_refund_reason_instance(
+ str(reason_reference_id),
+ refund_reason_reference_type.pk,
+ )
+
cleaned_input = {
"amount": amount,
"reason": reason,
+ "reason_reference": reason_reference_id,
"add_lines": lines_to_add,
"remove_lines": line_ids_to_remove,
"grant_refund_for_shipping": grant_refund_for_shipping,
"transaction_item": transaction_item,
+ "reason_reference_instance": reason_reference_instance,
}
return cleaned_input
@@ -398,6 +453,11 @@ class OrderGrantRefundUpdate(BaseMutation):
if reason is not None:
granted_refund.reason = reason
+ reason_reference_instance = cleaned_input["reason_reference_instance"]
+
+ if reason_reference_instance:
+ granted_refund.reason_reference = reason_reference_instance
+
granted_refund.save(
update_fields=[
"amount_value",
@@ -405,6 +465,7 @@ class OrderGrantRefundUpdate(BaseMutation):
"shipping_costs_included",
"updated_at",
"transaction_item",
+ "reason_reference",
]
)
@@ -421,6 +482,7 @@ class OrderGrantRefundUpdate(BaseMutation):
order = granted_refund.order
cleaned_input = cls.clean_input(info, granted_refund, input)
+
cls.process_update_for_granted_refund(order, granted_refund, cleaned_input)
update_order_charge_data(order)
return cls(
diff --git a/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py
index 01158a538e..3de91f7895 100644
--- a/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py
@@ -5,8 +5,12 @@ import pytest
from .....core.prices import quantize_price
from .....order.utils import update_order_charge_data
+from .....page.models import Page, PageType
from ....core.utils import to_global_id_or_none
-from ....tests.utils import assert_no_permission, get_graphql_content
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+)
from ...enums import (
OrderChargeStatusEnum,
OrderGrantedRefundStatusEnum,
@@ -27,6 +31,7 @@ mutation OrderGrantRefundCreate(
amount
}
reason
+ reasonReference { id }
user{
id
}
@@ -61,6 +66,7 @@ mutation OrderGrantRefundCreate(
createdAt
updatedAt
reason
+ reasonReference { id }
app{
id
}
@@ -1145,3 +1151,488 @@ def test_grant_refund_with_transaction_item_and_amount(
assert granted_refund_line.order_line == first_line
assert granted_refund_line.quantity == 1
assert granted_refund_line.reason == expected_reason
+
+
+# Reason reference tests
+
+
+def test_grant_refund_with_reference_required_created_by_user(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ order_id = to_global_id_or_none(order)
+ page_id = to_global_id_or_none(page)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert not errors
+
+ assert order_id == data["order"]["id"]
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund_from_db = order.granted_refunds.first()
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+
+ assert (
+ granted_refund_assigned_to_order["reasonReference"]["id"]
+ == page_id
+ == to_global_id_or_none(granted_refund_from_db.reason_reference)
+ )
+ assert granted_refund_from_db.reason_reference == page
+
+
+def test_grant_refund_with_reference_required_but_not_provided_created_by_user(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ order_id = to_global_id_or_none(order)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundCreateErrorCode.REQUIRED.name
+
+ assert order.granted_refunds.count() == 0
+
+
+def test_grant_refund_with_reference_required_but_not_provided_created_by_app(
+ app_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ order_id = to_global_id_or_none(order)
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ amount = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert not errors
+
+ assert order_id == data["order"]["id"]
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund_from_db = order.granted_refunds.first()
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+
+ assert granted_refund_assigned_to_order["reasonReference"] is None
+ assert granted_refund_from_db.reason_reference is None
+
+
+def test_grant_refund_with_reference_not_enabled_created_by_user_rejected(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ assert site_settings.refund_reason_reference_type is None
+
+ order_id = to_global_id_or_none(order)
+ page_id = to_global_id_or_none(page)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+
+ assert len(errors) == 1
+
+ error = errors[0]
+
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundCreateErrorCode.INVALID.name
+
+
+def test_grant_refund_with_reference_not_enabled_created_by_app_rejects(
+ app_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ assert site_settings.refund_reason_reference_type is None
+
+ order_id = to_global_id_or_none(order)
+ page_id = to_global_id_or_none(page)
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ amount = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundCreateErrorCode.INVALID.name
+
+
+def test_grant_refund_with_reference_required_created_by_user_throws_for_invalid_id(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ order_id = to_global_id_or_none(order)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ invalid_page_id = graphene.Node.to_global_id("Page", 99999)
+ assert Page.objects.count() == 0
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": invalid_page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundCreateErrorCode.INVALID.name
+
+ assert order.granted_refunds.count() == 0
+
+
+def test_grant_refund_with_reason_reference_wrong_page_type_created_by_user(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type1 = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type1
+ site_settings.save()
+
+ page_type2 = PageType.objects.create(name="Different Type", slug="different-type")
+ page_wrong_type = Page.objects.create(
+ slug="wrong-type-page",
+ title="Wrong Type Page",
+ page_type=page_type2,
+ is_published=True,
+ )
+
+ order_id = to_global_id_or_none(order)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ wrong_page_id = to_global_id_or_none(page_wrong_type)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": wrong_page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundCreateErrorCode.INVALID.name
+
+ assert order.granted_refunds.count() == 0
+
+
+def test_grant_refund_with_reason_reference_not_valid_page_id(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ order_id = to_global_id_or_none(order)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ invalid_page_id = graphene.Node.to_global_id("Product", 12345)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": invalid_page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+
+ assert error["field"] == "reasonReference"
+ assert error["code"] == "GRAPHQL_ERROR"
+
+ assert order.granted_refunds.count() == 0
+
+
+def test_grant_refund_with_reason_reference_not_valid_id_created_by_user(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ order_id = to_global_id_or_none(order)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ # Use a completely invalid ID format
+ invalid_id = "invalid-id-format"
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": invalid_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == "GRAPHQL_ERROR"
+
+ assert order.granted_refunds.count() == 0
diff --git a/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py
index f0acff9459..4d6405a5bb 100644
--- a/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py
@@ -6,6 +6,7 @@ import pytest
from .....core.prices import quantize_price
from .....order import OrderGrantedRefundStatus
from .....order.utils import update_order_charge_data
+from .....page.models import Page, PageType
from ....core.utils import to_global_id_or_none
from ....tests.utils import (
assert_no_permission,
@@ -32,6 +33,7 @@ mutation OrderGrantRefundUpdate(
amount
}
reason
+ reasonReference { id }
user {
id
}
@@ -65,6 +67,7 @@ mutation OrderGrantRefundUpdate(
createdAt
updatedAt
reason
+ reasonReference { id }
app{
id
}
@@ -734,7 +737,7 @@ def test_grant_refund_update_with_same_line_in_add_and_remove(
)
last_order_line = order_with_lines.lines.last()
last_order_line.quantity = 2
- last_order_line.save()
+ last_order_line.save(update_fields=["quantity"])
granted_refund_line_to_remove = granted_refund.lines.create(
order_line=last_order_line, quantity=1
)
@@ -2309,3 +2312,578 @@ def test_granted_refund_updated_when_status_blocks_action_and_only_reason_provid
assert granted_refund.reason == expected_reason
assert granted_refund_data["reason"] == expected_reason
+
+
+def test_grant_refund_update_with_reference_required_by_user(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+ app,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ current_reason = "Original reason"
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ page_id = to_global_id_or_none(page)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("15.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ errors = data["errors"]
+ assert not errors
+
+ order_id = to_global_id_or_none(order)
+ assert order_id == data["order"]["id"]
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund.refresh_from_db()
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+
+ assert (
+ granted_refund_assigned_to_order["reasonReference"]["id"]
+ == page_id
+ == to_global_id_or_none(granted_refund.reason_reference)
+ )
+ assert granted_refund.reason_reference == page
+
+
+def test_grant_refund_update_with_reference_required_but_not_provided_by_user(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+ app,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ current_reason = "Original reason"
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("15.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundUpdateErrorCode.REQUIRED.name
+
+ granted_refund.refresh_from_db()
+ assert granted_refund.amount_value == current_amount
+ assert granted_refund.reason == current_reason
+
+
+def test_grant_refund_update_with_reference_required_but_not_provided_by_app(
+ app_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+ staff_user,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ current_reason = "Original reason"
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ amount = Decimal("15.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ # "reasonReference": page_id, # Not provided
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ errors = data["errors"]
+ assert not errors
+
+ order_id = to_global_id_or_none(order)
+ assert order_id == data["order"]["id"]
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund.refresh_from_db()
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+
+ assert granted_refund_assigned_to_order["reasonReference"] is None
+ assert granted_refund.reason_reference is None
+
+
+def test_grant_refund_update_with_reference_not_enabled_by_user_rejects(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+ app,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ assert site_settings.refund_reason_reference_type is None
+
+ current_reason = "Original reason"
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ page_id = to_global_id_or_none(page)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("15.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name
+
+
+def test_grant_refund_update_with_reference_not_enabled_by_app_rejects(
+ app_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+ staff_user,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ assert site_settings.refund_reason_reference_type is None
+
+ current_reason = "Original reason"
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ page_id = to_global_id_or_none(page)
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ amount = Decimal("15.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name
+
+
+def test_grant_refund_update_with_reference_required_by_user_throws_for_invalid_id(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+ app,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ current_reason = "Original reason"
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("15.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ invalid_page_id = graphene.Node.to_global_id("Page", 99999)
+
+ assert Page.objects.count() == 0
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": invalid_page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name
+
+ granted_refund.refresh_from_db()
+ assert granted_refund.amount_value == current_amount
+ assert granted_refund.reason == current_reason
+
+
+def test_grant_refund_update_with_reason_reference_wrong_page_type_created_by_user(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ page_type1 = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type1
+ site_settings.save()
+
+ page_type2 = PageType.objects.create(name="Different Type", slug="different-type")
+ page_wrong_type = Page.objects.create(
+ slug="wrong-type-page",
+ title="Wrong Type Page",
+ page_type=page_type2,
+ is_published=True,
+ )
+
+ charged_value = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ order_id=order.id, charged_value=charged_value
+ )
+
+ current_reason = "Original reason."
+ current_amount = Decimal("5.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ user=staff_api_client.user,
+ transaction_item=transaction_item,
+ )
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ wrong_page_id = to_global_id_or_none(page_wrong_type)
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "reason": "Updated reason with wrong page type",
+ "reasonReference": wrong_page_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name
+
+ granted_refund.refresh_from_db()
+ assert granted_refund.amount_value == current_amount
+ assert granted_refund.reason == current_reason
+
+
+def test_grant_refund_update_with_reason_reference_not_valid_page_id(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+ app,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ current_reason = "Original reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("15.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ invalid_page_id = graphene.Node.to_global_id("Product", 12345)
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": invalid_page_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == "GRAPHQL_ERROR"
+
+ granted_refund.refresh_from_db()
+ assert granted_refund.amount_value == current_amount
+ assert granted_refund.reason == current_reason
+
+
+def test_grant_refund_update_with_reason_reference_not_valid_id(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+ site_settings,
+ app,
+):
+ # Given
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ current_reason = "Original reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ amount = Decimal("15.00")
+ transaction_item = transaction_item_generator(
+ charged_value=amount, order_id=order.id
+ )
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ invalid_id = "invalid-id-format"
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": amount,
+ "reason": "Damaged product refund",
+ "reasonReference": invalid_id,
+ "transactionId": transaction_item_id,
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == "GRAPHQL_ERROR"
+
+ granted_refund.refresh_from_db()
+ assert granted_refund.amount_value == current_amount
+ assert granted_refund.reason == current_reason
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 09d1f911cb..530ca284ba 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -75,6 +75,7 @@ from ..core.descriptions import (
ADDED_IN_319,
ADDED_IN_320,
ADDED_IN_321,
+ ADDED_IN_322,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
)
@@ -111,6 +112,8 @@ from ..invoice.dataloaders import InvoicesByOrderIdLoader
from ..invoice.types import Invoice
from ..meta.resolvers import check_private_metadata_privilege, resolve_metadata
from ..meta.types import MetadataItem, ObjectWithMetadata
+from ..page.dataloaders import PageByIdLoader
+from ..page.types import Page
from ..payment.dataloaders import (
TransactionByPaymentIdLoader,
TransactionItemByIDLoader,
@@ -268,7 +271,12 @@ class OrderGrantedRefund(
created_at = DateTime(required=True, description="Time of creation.")
updated_at = DateTime(required=True, description="Time of last update.")
amount = graphene.Field(Money, required=True, description="Refund amount.")
- reason = graphene.String(description="Reason of the refund.")
+ reason = graphene.String(description="Reason of the refund." + ADDED_IN_322)
+ reason_reference = graphene.Field(
+ Page,
+ required=False,
+ description="Reason Model (Page) reference for refund." + ADDED_IN_322,
+ )
user = graphene.Field(
User,
description=(
@@ -388,6 +396,31 @@ class OrderGrantedRefund(
granted_refund.transaction_item_id
)
+ @staticmethod
+ def resolve_reason_reference(
+ root: SyncWebhookControlContext[models.OrderGrantedRefund], info
+ ):
+ if not root.node.reason_reference:
+ return None
+
+ def wrap_page_with_context(page):
+ if not page:
+ return None
+
+ return (
+ ChannelByOrderIdLoader(info.context)
+ .load(root.node.order_id)
+ .then(
+ lambda channel: ChannelContext(node=page, channel_slug=channel.slug)
+ )
+ )
+
+ return (
+ PageByIdLoader(info.context)
+ .load(root.node.reason_reference_id)
+ .then(wrap_page_with_context)
+ )
+
class OrderDiscount(BaseObjectType):
value_type = graphene.Field(
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
index 0255841064..3b2651bace 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
@@ -1,6 +1,6 @@
import uuid
from decimal import Decimal
-from typing import TYPE_CHECKING, Optional, cast
+from typing import TYPE_CHECKING, Any, Optional, cast
import graphene
from django.core.exceptions import ValidationError
@@ -8,6 +8,7 @@ from django.core.exceptions import ValidationError
from .....app.models import App
from .....core.prices import quantize_price
from .....order.models import Order
+from .....page.models import Page
from .....payment import PaymentError, TransactionAction, TransactionEventType
from .....payment.error_codes import TransactionRequestActionErrorCode
from .....payment.gateway import (
@@ -19,6 +20,7 @@ from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
from ....checkout.types import Checkout
from ....core import ResolveInfo
+from ....core.descriptions import ADDED_IN_322
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.mutations import BaseMutation
from ....core.scalars import UUID, PositiveDecimal
@@ -27,6 +29,7 @@ from ....core.validators import validate_one_of_args_is_in_mutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import TransactionActionEnum
from ...types import TransactionItem
+from ...utils import validate_and_resolve_refund_reason_context
from .utils import get_transaction_item
if TYPE_CHECKING:
@@ -61,6 +64,14 @@ class TransactionRequestAction(BaseMutation):
),
required=False,
)
+ refund_reason = graphene.String(
+ description="Reason of the refund" + ADDED_IN_322,
+ required=False,
+ )
+ refund_reason_reference = graphene.ID(
+ description="ID of a `Page` (Model) to reference in reason." + ADDED_IN_322,
+ required=False,
+ )
class Meta:
description = "Request an action for payment transaction."
@@ -76,6 +87,8 @@ class TransactionRequestAction(BaseMutation):
action_value: Decimal | None,
user: Optional["User"],
app: App | None,
+ reason: str | None = None,
+ reason_reference: Page | None = None,
):
if action == TransactionAction.CANCEL:
transaction = action_kwargs["transaction"]
@@ -105,7 +118,13 @@ class TransactionRequestAction(BaseMutation):
action_value = action_value or transaction.charged_value
action_value = min(action_value, transaction.charged_value)
request_event = cls.create_transaction_event_requested(
- transaction, action_value, TransactionAction.REFUND, user=user, app=app
+ transaction,
+ action_value,
+ TransactionAction.REFUND,
+ user=user,
+ app=app,
+ reason=reason,
+ reason_reference=reason_reference,
)
request_refund_action(
**action_kwargs, refund_value=action_value, request_event=request_event
@@ -113,14 +132,26 @@ class TransactionRequestAction(BaseMutation):
@classmethod
def create_transaction_event_requested(
- cls, transaction, action_value, action, user=None, app=None
+ cls,
+ transaction,
+ action_value,
+ action,
+ user=None,
+ app=None,
+ reason=None,
+ reason_reference: Page | None = None,
):
+ message: str | None = None
+ reason_reference_to_set = None
+
if action == TransactionAction.CANCEL:
type = TransactionEventType.CANCEL_REQUEST
elif action == TransactionAction.CHARGE:
type = TransactionEventType.CHARGE_REQUEST
elif action == TransactionAction.REFUND:
type = TransactionEventType.REFUND_REQUEST
+ message = reason or None
+ reason_reference_to_set = reason_reference or None
else:
raise ValidationError(
{
@@ -138,14 +169,89 @@ class TransactionRequestAction(BaseMutation):
app=app,
app_identifier=app.identifier if app else None,
idempotency_key=str(uuid.uuid4()),
+ message=message,
+ reason_reference=reason_reference_to_set,
+ )
+
+ @classmethod
+ def _validate_reason_and_event(cls, input: dict[str, Any]):
+ action_type = input["action_type"]
+ reason = input.get("refund_reason")
+ reason_reference_id = input.get("refund_reason_reference")
+
+ reason_exists = reason or reason_reference_id
+
+ if reason_exists and action_type != TransactionAction.REFUND:
+ errors = {}
+
+ if reason:
+ errors["refund_reason"] = ValidationError(
+ f"Reason can be set only for {TransactionActionEnum.REFUND.name} action.",
+ code=TransactionRequestActionErrorCode.INVALID.value,
+ )
+
+ if reason_reference_id:
+ errors["refund_reason_reference"] = ValidationError(
+ f"Reason reference can be set only for {TransactionActionEnum.REFUND.name} action.",
+ code=TransactionRequestActionErrorCode.INVALID.value,
+ )
+
+ raise ValidationError(errors)
+
+ @classmethod
+ def _prepare_refund_reason(cls, info: ResolveInfo, /, **data):
+ cls._validate_reason_and_event(data)
+
+ reason_reference_id = data.get("refund_reason_reference")
+
+ requestor_is_app = info.context.app is not None
+ requestor_is_user = info.context.user is not None and not requestor_is_app
+
+ refund_reason_context = validate_and_resolve_refund_reason_context(
+ reason_reference_id=reason_reference_id,
+ requestor_is_user=bool(requestor_is_user),
+ refund_reference_field_name="refund_reason_reference",
+ error_code_enum=TransactionRequestActionErrorCode,
)
+ refund_reason_reference_type = refund_reason_context[
+ "refund_reason_reference_type"
+ ]
+
+ reason_reference_instance: Page | None = None
+
+ if refund_reason_context["should_apply"]:
+ try:
+ reason_reference_pk = cls.get_global_id_or_error(
+ str(reason_reference_id), only_type="Page", field="reason_reference"
+ )
+
+ reason_reference_instance = Page.objects.get(
+ pk=reason_reference_pk, page_type=refund_reason_reference_type.pk
+ )
+
+ except (Page.DoesNotExist, ValueError):
+ raise ValidationError(
+ {
+ "refund_reason_reference": ValidationError(
+ "Invalid reason reference.",
+ code=TransactionRequestActionErrorCode.INVALID.value,
+ )
+ }
+ ) from None
+
+ return reason_reference_instance
+
@classmethod
def perform_mutation(cls, root, info: ResolveInfo, /, **data):
id = data.get("id")
token = data.get("token")
action_type = data["action_type"]
action_value = data.get("amount")
+ reason = data.get("refund_reason")
+
+ reason_reference_instance = cls._prepare_refund_reason(info, **data)
+
validate_one_of_args_is_in_mutation("id", id, "token", token)
transaction = get_transaction_item(id, token)
if transaction.order_id:
@@ -175,7 +281,13 @@ class TransactionRequestAction(BaseMutation):
try:
cls.handle_transaction_action(
- action_type, action_kwargs, action_value, user, app
+ action_type,
+ action_kwargs,
+ action_value,
+ user,
+ app,
+ reason,
+ reason_reference_instance,
)
except PaymentError as e:
error_enum = TransactionRequestActionErrorCode
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
index 97af70daf0..ce3bc4ce05 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -6,12 +6,17 @@ import pytest
from .....app.models import App
from .....order import OrderEvents
+from .....page.models import Page, PageType
from .....payment import TransactionAction, TransactionEventType
from .....payment.interface import TransactionActionData
from .....payment.models import TransactionEvent, TransactionItem
from .....webhook.event_types import WebhookEventSyncType
from ....core.enums import TransactionRequestActionErrorCode
-from ....tests.utils import assert_no_permission, get_graphql_content
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+)
from ...enums import TransactionActionEnum
MUTATION_TRANSACTION_REQUEST_ACTION = """
@@ -19,11 +24,15 @@ mutation TransactionRequestAction(
$id: ID
$action_type: TransactionActionEnum!
$amount: PositiveDecimal
+ $refund_reason: String
+ $refund_reason_reference: ID
){
transactionRequestAction(
id: $id,
actionType: $action_type,
- amount: $amount
+ amount: $amount,
+ refundReason: $refund_reason,
+ refundReasonReference: $refund_reason_reference
){
transaction{
id
@@ -58,11 +67,15 @@ mutation TransactionRequestAction(
$token: UUID
$action_type: TransactionActionEnum!
$amount: PositiveDecimal
+ $reason: String
+ $reason_reference: ID
){
transactionRequestAction(
token: $token,
actionType: $action_type,
- amount: $amount
+ amount: $amount,
+ refundReason: $reason,
+ refundReasonReference: $reason_reference
){
transaction{
id
@@ -1308,3 +1321,643 @@ def test_transaction_request_cancel_sets_user_to_request_event(
assert request_event.app is None
assert request_event.app_identifier is None
assert request_event.user == staff_api_client.user
+
+
+# Reason reference tests for refund actions
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_with_reason_reference_required_created_by_user(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ staff_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ permission_group_handle_payments,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ # Create page type and page for refund reasons
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ page_id = to_global_id_or_none(page)
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "refund_reason": "Product was damaged during shipping",
+ "refund_reason_reference": page_id,
+ }
+ staff_api_client.user.groups.add(permission_group_handle_payments)
+
+ # When
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert not errors
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+
+ assert request_event
+ assert request_event.user == staff_api_client.user
+ assert request_event.message == "Product was damaged during shipping"
+ assert request_event.reason_reference == page
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_with_reason_reference_required_but_not_provided_created_by_user(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ staff_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ permission_group_handle_payments,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "refund_reason": "Product was damaged during shipping",
+ }
+ staff_api_client.user.groups.add(permission_group_handle_payments)
+
+ # When
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "refundReasonReference"
+ assert error["code"] == TransactionRequestActionErrorCode.REQUIRED.name
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+ assert request_event is None
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_with_reason_reference_required_but_not_provided_created_by_app(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "refund_reason": "Product was damaged during shipping",
+ }
+ app_api_client.app.permissions.add(permission_manage_payments)
+
+ # When
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert not errors
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+
+ assert request_event
+ assert request_event.app == app_api_client.app
+ assert request_event.message == "Product was damaged during shipping"
+ assert request_event.reason_reference is None
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_with_reason_reference_not_configured_created_by_app(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ assert site_settings.refund_reason_reference_type is None
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ page_id = to_global_id_or_none(page)
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "refund_reason": "Product was damaged during shipping",
+ "refund_reason_reference": page_id, # Provided but should be ignored
+ }
+ app_api_client.app.permissions.add(permission_manage_payments)
+
+ # When
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "refundReasonReference"
+ assert error["code"] == TransactionRequestActionErrorCode.INVALID.name
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_with_reason_reference_required_created_by_user_throws_for_invalid_id(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ staff_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ permission_group_handle_payments,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ invalid_page_id = graphene.Node.to_global_id("Page", 99999)
+
+ assert Page.objects.count() == 0
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "refund_reason": "Product was damaged during shipping",
+ "refund_reason_reference": invalid_page_id,
+ }
+ staff_api_client.user.groups.add(permission_group_handle_payments)
+
+ # When
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "refundReasonReference"
+ assert error["code"] == TransactionRequestActionErrorCode.INVALID.name
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+ assert request_event is None
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_with_reason_only_no_reference(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ staff_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ permission_group_handle_payments,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ assert site_settings.refund_reason_reference_type is None
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "refund_reason": "Product was damaged during shipping",
+ }
+ staff_api_client.user.groups.add(permission_group_handle_payments)
+
+ # When
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert not errors
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+
+ assert request_event
+ assert request_event.user == staff_api_client.user
+ assert request_event.message == "Product was damaged during shipping"
+ assert request_event.reason_reference is None
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_transaction_request_charge_rejects_reason_and_reference(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ staff_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ permission_group_handle_payments,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ authorized_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ page_id = to_global_id_or_none(page)
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.CHARGE.name,
+ "refund_reason": "Some reason that should be rejected",
+ "refund_reason_reference": page_id,
+ }
+ staff_api_client.user.groups.add(permission_group_handle_payments)
+
+ # When
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert len(errors) == 2
+
+ # Check that both refund_reason and refund_reason_reference errors are present
+ error_fields = [error["field"] for error in errors]
+ assert "refundReason" in error_fields
+ assert "refundReasonReference" in error_fields
+
+ # Check error codes
+ for error in errors:
+ assert error["code"] == TransactionRequestActionErrorCode.INVALID.name
+
+ # Check error messages
+ reason_error = next(error for error in errors if error["field"] == "refundReason")
+ reference_error = next(
+ error for error in errors if error["field"] == "refundReasonReference"
+ )
+
+ assert "Reason can be set only for REFUND action" in reason_error["message"]
+ assert (
+ "Reason reference can be set only for REFUND action"
+ in reference_error["message"]
+ )
+
+ # No transaction event should be created since validation failed
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST,
+ ).first()
+ assert request_event is None
+
+ # Payment action should not be called
+ assert not mocked_payment_action_request.called
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_with_reason_reference_wrong_page_type_created_by_user(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ staff_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ permission_group_handle_payments,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ page_type1 = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type1
+ site_settings.save()
+
+ page_type2 = PageType.objects.create(name="Different Type", slug="different-type")
+ page_wrong_type = Page.objects.create(
+ slug="wrong-type-page",
+ title="Wrong Type Page",
+ page_type=page_type2,
+ is_published=True,
+ )
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ wrong_page_id = to_global_id_or_none(page_wrong_type)
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "refund_reason": "Product was damaged during shipping",
+ "refund_reason_reference": wrong_page_id,
+ }
+ staff_api_client.user.groups.add(permission_group_handle_payments)
+
+ # When
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "refundReasonReference"
+ assert error["code"] == TransactionRequestActionErrorCode.INVALID.name
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+ assert request_event is None
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_with_reason_reference_not_valid_page_id(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ staff_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ permission_group_handle_payments,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ invalid_page_id = graphene.Node.to_global_id("Product", 12345)
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "refund_reason": "Product was damaged during shipping",
+ "refund_reason_reference": invalid_page_id,
+ }
+ staff_api_client.user.groups.add(permission_group_handle_payments)
+
+ # When
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == "GRAPHQL_ERROR"
+ assert "Invalid ID:" in error["message"]
+ assert "Expected: Page, received: Product" in error["message"]
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+ assert request_event is None
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_with_reason_reference_not_valid_id_format(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ staff_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ transaction_item_generator,
+ permission_group_handle_payments,
+ site_settings,
+):
+ # Given
+ mocked_is_active.return_value = False
+
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=Decimal(10),
+ app=transaction_request_webhook.app,
+ )
+
+ invalid_id = "invalid-id-format"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "refund_reason": "Product was damaged during shipping",
+ "refund_reason_reference": invalid_id,
+ }
+ staff_api_client.user.groups.add(permission_group_handle_payments)
+
+ # When
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "reasonReference"
+ assert error["code"] == "GRAPHQL_ERROR"
+ assert "Invalid ID: invalid-id-format. Expected: Page." in error["message"]
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+ assert request_event is None
diff --git a/saleor/graphql/payment/tests/queries/test_transaction.py b/saleor/graphql/payment/tests/queries/test_transaction.py
index 4d5dc49d3f..f69420df2f 100644
--- a/saleor/graphql/payment/tests/queries/test_transaction.py
+++ b/saleor/graphql/payment/tests/queries/test_transaction.py
@@ -5,6 +5,7 @@ import pytest
from django.utils import timezone
from freezegun import freeze_time
+from .....page.models import Page
from .....payment import PaymentMethodType, TransactionEventType
from .....payment.models import TransactionEvent
from ....core.utils import to_global_id_or_none
@@ -74,6 +75,9 @@ TRANSACTION_QUERY = """
id
}
}
+ reasonReference{
+ id
+ }
}
name
message
@@ -951,3 +955,90 @@ def test_transaction_query_by_staff_with_payment_method_other(
data = content["data"]["transaction"]
assert data["paymentMethodDetails"]["__typename"] == "OtherPaymentMethodDetails"
assert data["paymentMethodDetails"]["name"] == expected_payment_method_name
+
+
+def test_transaction_event_with_reason_reference(
+ staff_api_client,
+ transaction_item_created_by_user,
+ permission_manage_payments,
+ permission_manage_staff,
+ page_type,
+ channel_USD,
+):
+ # given
+ page = Page.objects.create(
+ slug="refund-policy",
+ title="Refund Policy",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ TransactionEvent.objects.create(
+ transaction=transaction_item_created_by_user,
+ psp_reference="psp-ref-123",
+ message="Refund with reason",
+ currency="USD",
+ type=TransactionEventType.REFUND_SUCCESS,
+ amount_value=Decimal("10.00"),
+ external_url=f"http://{TEST_SERVER_DOMAIN}/test",
+ user=staff_api_client.user,
+ reason_reference=page,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_user.token
+ )
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ events = content["data"]["transaction"]["events"]
+ event_data = next(e for e in events if e["pspReference"] == "psp-ref-123")
+ assert event_data["reasonReference"]["id"] == to_global_id_or_none(page)
+
+
+def test_transaction_event_without_reason_reference(
+ staff_api_client,
+ transaction_item_created_by_user,
+ permission_manage_payments,
+ permission_manage_staff,
+):
+ # given
+ TransactionEvent.objects.create(
+ transaction=transaction_item_created_by_user,
+ psp_reference="psp-ref-no-reason",
+ message="Regular event",
+ currency="USD",
+ type=TransactionEventType.CHARGE_SUCCESS,
+ amount_value=Decimal("10.00"),
+ external_url=f"http://{TEST_SERVER_DOMAIN}/test",
+ user=staff_api_client.user,
+ reason_reference=None,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_user.token
+ )
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ events = content["data"]["transaction"]["events"]
+ event_data = next(e for e in events if e["pspReference"] == "psp-ref-no-reason")
+ assert event_data["reasonReference"] is None
diff --git a/saleor/graphql/payment/tests/test_utils.py b/saleor/graphql/payment/tests/test_utils.py
new file mode 100644
index 0000000000..cea4ed8592
--- /dev/null
+++ b/saleor/graphql/payment/tests/test_utils.py
@@ -0,0 +1,269 @@
+import pytest
+from django.core.exceptions import ValidationError
+
+from ....page.models import PageType
+from ....payment.error_codes import (
+ TransactionRequestActionErrorCode,
+ TransactionRequestRefundForGrantedRefundErrorCode,
+)
+from ..utils import validate_and_resolve_refund_reason_context
+
+
+def test_no_reference_type_configured_no_reference_id_provided(site_settings):
+ # Given
+ site_settings.refund_reason_reference_type = None
+ site_settings.save()
+
+ # When
+ result = validate_and_resolve_refund_reason_context(
+ reason_reference_id=None,
+ requestor_is_user=True,
+ refund_reference_field_name="refundReasonReference",
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ # Then
+ assert result == {
+ "is_passing_reason_reference_required": False,
+ "refund_reason_reference_type": None,
+ "should_apply": False,
+ }
+
+
+def test_no_reference_type_configured_reference_id_provided_raises_invalid(
+ site_settings,
+):
+ # Given
+ site_settings.refund_reason_reference_type = None
+ site_settings.save()
+
+ # When / Then
+ with pytest.raises(ValidationError) as exc_info:
+ validate_and_resolve_refund_reason_context(
+ reason_reference_id="some-id",
+ requestor_is_user=True,
+ refund_reference_field_name="refundReasonReference",
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ error_dict = exc_info.value.error_dict
+ assert "refundReasonReference" in error_dict
+ assert (
+ error_dict["refundReasonReference"][0].code
+ == TransactionRequestActionErrorCode.INVALID.value
+ )
+ assert "Reason reference type is not configured" in str(
+ error_dict["refundReasonReference"][0]
+ )
+
+
+def test_reference_type_configured_no_reference_id_user_requestor_raises_required(
+ site_settings,
+):
+ # Given
+ page_type = PageType(name="Refund Reasons", slug="refund-reasons")
+ page_type.save()
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save()
+
+ # When / Then
+ with pytest.raises(ValidationError) as exc_info:
+ validate_and_resolve_refund_reason_context(
+ reason_reference_id=None,
+ requestor_is_user=True,
+ refund_reference_field_name="refundReasonReference",
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ error_dict = exc_info.value.error_dict
+ assert "refundReasonReference" in error_dict
+ assert (
+ error_dict["refundReasonReference"][0].code
+ == TransactionRequestActionErrorCode.REQUIRED.value
+ )
+ assert "Reason reference is required" in str(error_dict["refundReasonReference"][0])
+
+
+def test_reference_type_configured_no_reference_id_app_requestor_success(
+ site_settings,
+):
+ """Test when reference type is configured, no reference ID provided, but requestor is app - should succeed."""
+ # Given
+ page_type = PageType(name="Refund Reasons", slug="refund-reasons")
+ page_type.save()
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save()
+
+ # When
+ result = validate_and_resolve_refund_reason_context(
+ reason_reference_id=None,
+ requestor_is_user=False, # App requestor
+ refund_reference_field_name="refundReasonReference",
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ # Then
+ assert result == {
+ "is_passing_reason_reference_required": True,
+ "refund_reason_reference_type": page_type,
+ "should_apply": False,
+ }
+
+
+def test_reference_type_configured_reference_id_provided_success(site_settings):
+ """Test when reference type is configured and reference ID is provided - should succeed."""
+ # Given
+ page_type = PageType(name="Refund Reasons", slug="refund-reasons")
+ page_type.save()
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save()
+
+ # When
+ result = validate_and_resolve_refund_reason_context(
+ reason_reference_id="some-reference-id",
+ requestor_is_user=True,
+ refund_reference_field_name="refundReasonReference",
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ # Then
+ assert result == {
+ "is_passing_reason_reference_required": True,
+ "refund_reason_reference_type": page_type,
+ "should_apply": True,
+ }
+
+
+def test_reference_type_configured_reference_id_provided_app_requestor_success(
+ site_settings,
+):
+ """Test when reference type is configured, reference ID is provided, and requestor is app - should succeed."""
+ # Given
+ page_type = PageType(name="Refund Reasons", slug="refund-reasons")
+ page_type.save()
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save()
+
+ # When
+ result = validate_and_resolve_refund_reason_context(
+ reason_reference_id="some-reference-id",
+ requestor_is_user=False, # App requestor
+ refund_reference_field_name="refundReasonReference",
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ # Then
+ assert result == {
+ "is_passing_reason_reference_required": True,
+ "refund_reason_reference_type": page_type,
+ "should_apply": True,
+ }
+
+
+def test_custom_field_name_in_error_message(site_settings):
+ # Given
+ site_settings.refund_reason_reference_type = None
+ site_settings.save()
+ custom_field_name = "customReasonReference"
+
+ # When / Then
+ with pytest.raises(ValidationError) as exc_info:
+ validate_and_resolve_refund_reason_context(
+ reason_reference_id="some-id",
+ requestor_is_user=True,
+ refund_reference_field_name=custom_field_name,
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ error_dict = exc_info.value.error_dict
+ assert custom_field_name in error_dict
+ assert (
+ error_dict[custom_field_name][0].code
+ == TransactionRequestActionErrorCode.INVALID.value
+ )
+
+
+def test_custom_field_name_in_required_error_message(site_settings):
+ # Given
+ page_type = PageType(name="Refund Reasons", slug="refund-reasons")
+ page_type.save()
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save()
+ custom_field_name = "customReasonReference"
+
+ # When / Then
+ with pytest.raises(ValidationError) as exc_info:
+ validate_and_resolve_refund_reason_context(
+ reason_reference_id=None,
+ requestor_is_user=True,
+ refund_reference_field_name=custom_field_name,
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ error_dict = exc_info.value.error_dict
+ assert custom_field_name in error_dict
+ assert (
+ error_dict[custom_field_name][0].code
+ == TransactionRequestActionErrorCode.REQUIRED.value
+ )
+
+
+def test_different_error_code_enum(site_settings):
+ """Test that the function works with different error code enums."""
+ # Given
+ site_settings.refund_reason_reference_type = None
+ site_settings.save()
+
+ # When / Then
+ with pytest.raises(ValidationError) as exc_info:
+ validate_and_resolve_refund_reason_context(
+ reason_reference_id="some-id",
+ requestor_is_user=True,
+ refund_reference_field_name="refundReasonReference",
+ error_code_enum=TransactionRequestRefundForGrantedRefundErrorCode,
+ )
+
+ error_dict = exc_info.value.error_dict
+ assert "refundReasonReference" in error_dict
+ assert (
+ error_dict["refundReasonReference"][0].code
+ == TransactionRequestRefundForGrantedRefundErrorCode.INVALID.value
+ )
+
+
+def test_is_passing_reason_reference_required_when_no_reference_type(site_settings):
+ # Given: No reference type configured
+ site_settings.refund_reason_reference_type = None
+ site_settings.save()
+
+ # When
+ result = validate_and_resolve_refund_reason_context(
+ reason_reference_id=None,
+ requestor_is_user=False,
+ refund_reference_field_name="refundReasonReference",
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ # Then
+ assert result["is_passing_reason_reference_required"] is False
+
+
+def test_is_passing_reason_reference_required_when_reference_type_configured(
+ site_settings,
+):
+ # Given: Reference type configured
+ page_type = PageType(name="Refund Reasons", slug="refund-reasons")
+ page_type.save()
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save()
+
+ # When
+ result = validate_and_resolve_refund_reason_context(
+ reason_reference_id=None,
+ requestor_is_user=False,
+ refund_reference_field_name="refundReasonReference",
+ error_code_enum=TransactionRequestActionErrorCode,
+ )
+
+ # Then
+ assert result["is_passing_reason_reference_required"] is True
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index cb30c81fbb..b6bb60d520 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -4,6 +4,7 @@ from uuid import UUID
import graphene
from django.db.models import Q
from graphene import relay
+from promise import Promise
from ...core.exceptions import PermissionDenied
from ...graphql.core.descriptions import ADDED_IN_322
@@ -12,10 +13,11 @@ from ...payment.interface import PaymentMethodData
from ...permission.enums import OrderPermissions
from ..account.dataloaders import UserByUserIdLoader
from ..app.dataloaders import ActiveAppsByAppIdentifierLoader, AppByIdLoader
+from ..channel.dataloaders.by_transaction import ChannelByTransactionIdLoader
from ..checkout.dataloaders import CheckoutByTokenLoader
from ..core import ResolveInfo
from ..core.connection import CountableConnection
-from ..core.context import SyncWebhookControlContext
+from ..core.context import ChannelContext, SyncWebhookControlContext
from ..core.doc_category import DOC_CATEGORY_PAYMENTS
from ..core.fields import JSONString, PermissionsField
from ..core.scalars import JSON, DateTime
@@ -26,6 +28,8 @@ from ..meta.permissions import public_payment_permissions
from ..meta.resolvers import resolve_metadata
from ..meta.types import MetadataItem, ObjectWithMetadata
from ..order.dataloaders import OrderByIdLoader
+from ..page.dataloaders import PageByIdLoader
+from ..page.types import Page
from ..utils import get_user_or_app_from_context
from .dataloaders import (
TransactionByPaymentIdLoader,
@@ -343,6 +347,11 @@ class TransactionEvent(ModelObjectType[models.TransactionEvent]):
description="Message related to the transaction's event.",
required=True,
)
+ reason_reference = graphene.Field(
+ Page,
+ required=False,
+ description="Reason model of the transaction refund." + ADDED_IN_322,
+ )
external_url = graphene.String(
description=(
"The url that will allow to redirect user to "
@@ -429,6 +438,31 @@ class TransactionEvent(ModelObjectType[models.TransactionEvent]):
return UserByUserIdLoader(info.context).load(root.user_id)
return None
+ @staticmethod
+ def resolve_reason_reference(root: models.TransactionEvent, info):
+ if not root.reason_reference_id:
+ return None
+
+ def wrap_page_with_context(data):
+ page, channel = data
+
+ if not page:
+ return None
+
+ return ChannelContext(node=page, channel_slug=channel.slug)
+
+ page_promise = PageByIdLoader(info.context).load(root.reason_reference_id)
+ channel_promise = ChannelByTransactionIdLoader(info.context).load(
+ root.transaction_id
+ )
+
+ return Promise.all(
+ [
+ page_promise,
+ channel_promise,
+ ]
+ ).then(wrap_page_with_context)
+
class PaymentMethodDetails(graphene.Interface):
name = graphene.String(required=True, description="Name of the payment method.")
@@ -596,6 +630,13 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
description="The payment method used for this transaction." + ADDED_IN_322,
)
+ reason = graphene.String(description="Reason of the refund." + ADDED_IN_322)
+ reason_reference = graphene.Field(
+ Page,
+ required=False,
+ description="Reason `Page` (Model) for refund." + ADDED_IN_322,
+ )
+
class Meta:
description = "Represents a payment transaction."
interfaces = [relay.Node, ObjectWithMetadata]
diff --git a/saleor/graphql/payment/utils.py b/saleor/graphql/payment/utils.py
index 76ed94b69d..87fe7b579d 100644
--- a/saleor/graphql/payment/utils.py
+++ b/saleor/graphql/payment/utils.py
@@ -1,5 +1,8 @@
from typing import TYPE_CHECKING, Optional
+from django.contrib.sites.models import Site
+from django.core.exceptions import ValidationError
+
from ...payment import models as payment_models
if TYPE_CHECKING:
@@ -41,3 +44,52 @@ def check_if_requestor_has_access(
if transaction.app_identifier and transaction.app_identifier == app.identifier:
return True
return False
+
+
+def validate_and_resolve_refund_reason_context(
+ *,
+ reason_reference_id: str | None,
+ requestor_is_user: bool,
+ refund_reference_field_name: str,
+ error_code_enum,
+):
+ settings = Site.objects.get_current().settings
+ refund_reason_reference_type = settings.refund_reason_reference_type
+
+ is_passing_reason_reference_required: bool = (
+ refund_reason_reference_type is not None
+ )
+
+ if not refund_reason_reference_type and reason_reference_id:
+ raise ValidationError(
+ {
+ refund_reference_field_name: ValidationError(
+ "Reason reference type is not configured.",
+ code=error_code_enum.INVALID.value,
+ )
+ }
+ ) from None
+
+ if (
+ is_passing_reason_reference_required
+ and reason_reference_id is None
+ and requestor_is_user
+ ):
+ raise ValidationError(
+ {
+ refund_reference_field_name: ValidationError(
+ "Reason reference is required when refund reason reference type is configured.",
+ code=error_code_enum.REQUIRED.value,
+ )
+ }
+ ) from None
+
+ should_apply = bool(
+ reason_reference_id is not None and refund_reason_reference_type
+ )
+
+ return {
+ "is_passing_reason_reference_required": is_passing_reason_reference_required,
+ "refund_reason_reference_type": refund_reason_reference_type,
+ "should_apply": should_apply,
+ }
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c32b5f4fd4..242b355d09 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -261,6 +261,11 @@ type Query {
"""
giftCardSettings: GiftCardSettings! @doc(category: "Gift cards")
+ """
+ Refunds related settings. Returns `RefundSettings` configuration, global for the entire shop.
+ """
+ refundSettings: RefundSettings! @doc(category: "Shop")
+
"""
Look up a shipping zone by ID.
@@ -11072,6 +11077,20 @@ type TransactionItem implements Node & ObjectWithMetadata @doc(category: "Paymen
Added in Saleor 3.22.
"""
paymentMethodDetails: PaymentMethodDetails
+
+ """
+ Reason of the refund.
+
+ Added in Saleor 3.22.
+ """
+ reason: String
+
+ """
+ Reason `Page` (Model) for refund.
+
+ Added in Saleor 3.22.
+ """
+ reasonReference: Page
}
"""
@@ -12388,9 +12407,20 @@ type OrderGrantedRefund @doc(category: "Orders") {
"""Refund amount."""
amount: Money!
- """Reason of the refund."""
+ """
+ Reason of the refund.
+
+ Added in Saleor 3.22.
+ """
reason: String
+ """
+ Reason Model (Page) reference for refund.
+
+ Added in Saleor 3.22.
+ """
+ reasonReference: Page
+
"""
User who performed the action. Requires of of the following permissions: MANAGE_USERS, MANAGE_STAFF, OWNER.
"""
@@ -12472,6 +12502,13 @@ type TransactionEvent implements Node @doc(category: "Payments") {
"""Message related to the transaction's event."""
message: String!
+ """
+ Reason model of the transaction refund.
+
+ Added in Saleor 3.22.
+ """
+ reasonReference: Page
+
"""
The url that will allow to redirect user to payment provider page with transaction details.
"""
@@ -12860,6 +12897,16 @@ enum TimePeriodTypeEnum {
YEAR
}
+"""
+Refund related settings from site settings.
+
+Added in Saleor 3.22.
+"""
+type RefundSettings @doc(category: "Orders") {
+ """Model type used for refund reasons."""
+ reasonReferenceType: PageType
+}
+
input ShippingZoneFilterInput @doc(category: "Shipping") {
search: String
channels: [ID!]
@@ -15332,6 +15379,27 @@ type Mutation {
input: GiftCardSettingsUpdateInput!
): GiftCardSettingsUpdate @doc(category: "Gift cards")
+ """
+ Update refund settings across all channels.
+
+ Added in Saleor 3.22.
+
+ Requires one of the following permissions: MANAGE_SETTINGS.
+ """
+ refundSettingsUpdate(
+ """Fields required to update refund settings."""
+ input: RefundSettingsUpdateInput!
+ ): RefundSettingsUpdate @doc(category: "Shop")
+
+ """
+ Updates RefundSettings. The `Page` (Model) Type will be cleared from `reasonReferenceType`. When it's cleared, passing reason reference to refund mutations is no longer accepted and will raise error.
+
+ Added in Saleor 3.22.
+
+ Requires one of the following permissions: MANAGE_SETTINGS.
+ """
+ refundReasonReferenceClear: RefundReasonReferenceTypeClear @doc(category: "Orders")
+
"""
Manage shipping method's availability in channels.
@@ -16342,6 +16410,20 @@ type Mutation {
"""The ID of the transaction. One of field id or token is required."""
id: ID
+ """
+ Reason of the refund
+
+ Added in Saleor 3.22.
+ """
+ refundReason: String
+
+ """
+ ID of a `Page` (Model) to reference in reason.
+
+ Added in Saleor 3.22.
+ """
+ refundReasonReference: ID
+
"""The token of the transaction. One of field id or token is required."""
token: UUID
): TransactionRequestAction @doc(category: "Payments")
@@ -20738,6 +20820,75 @@ input TimePeriodInputType {
type: TimePeriodTypeEnum!
}
+"""
+Update refund settings across all channels.
+
+Added in Saleor 3.22.
+
+Requires one of the following permissions: MANAGE_SETTINGS.
+"""
+type RefundSettingsUpdate @doc(category: "Shop") {
+ """Refund settings."""
+ refundSettings: RefundSettings!
+ refundSettingsErrors: [RefundSettingsUpdateError!]! @deprecated(reason: "Use `errors` field instead.")
+ errors: [RefundSettingsUpdateError!]!
+}
+
+type RefundSettingsUpdateError @doc(category: "Shop") {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """Failed to update Refund Settings"""
+ code: RefundSettingsErrorCode!
+}
+
+enum RefundSettingsErrorCode @doc(category: "Shop") {
+ INVALID
+ REQUIRED
+ GRAPHQL_ERROR
+}
+
+input RefundSettingsUpdateInput @doc(category: "Shop") {
+ """
+ The ID of a model type, that will be used to reference refund reasons. All models with of this type will be accepted as refund reasons.
+
+ Added in Saleor 3.22.
+ """
+ refundReasonReferenceType: ID!
+}
+
+"""
+Updates RefundSettings. The `Page` (Model) Type will be cleared from `reasonReferenceType`. When it's cleared, passing reason reference to refund mutations is no longer accepted and will raise error.
+
+Added in Saleor 3.22.
+
+Requires one of the following permissions: MANAGE_SETTINGS.
+"""
+type RefundReasonReferenceTypeClear @doc(category: "Orders") {
+ """Refund settings."""
+ refundSettings: RefundSettings!
+ refundSettingsErrors: [RefundReasonReferenceTypeClearError!]! @deprecated(reason: "Use `errors` field instead.")
+ errors: [RefundReasonReferenceTypeClearError!]!
+}
+
+type RefundReasonReferenceTypeClearError @doc(category: "Shop") {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """Failed to clear refund reason reference type"""
+ code: RefundSettingsErrorCode!
+}
+
"""
Manage shipping method's availability in channels.
@@ -23578,6 +23729,7 @@ type TransactionRequestActionError @doc(category: "Payments") {
enum TransactionRequestActionErrorCode @doc(category: "Payments") {
INVALID
+ REQUIRED
GRAPHQL_ERROR
NOT_FOUND
MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK
@@ -24902,6 +25054,13 @@ input OrderGrantRefundCreateInput @doc(category: "Orders") {
"""Reason of the granted refund."""
reason: String
+ """
+ ID of a `Page` (Model) to reference in reason.
+
+ Added in Saleor 3.22.
+ """
+ reasonReference: ID
+
"""Lines to assign to granted refund."""
lines: [OrderGrantRefundCreateLineInput!]
@@ -25002,6 +25161,13 @@ input OrderGrantRefundUpdateInput @doc(category: "Orders") {
"""Reason of the granted refund."""
reason: String
+ """
+ ID of a `Page` (Model) to reference in reason.
+
+ Added in Saleor 3.22.
+ """
+ reasonReference: ID
+
"""Lines to assign to granted refund."""
addLines: [OrderGrantRefundUpdateLineAddInput!]
@@ -34964,7 +35130,7 @@ type AssignedMultiCollectionReferenceAttribute implements AssignedAttribute @doc
scalar _Any
"""_Entity union as defined by Federation spec."""
-union _Entity = App | Address | User | Group | ProductVariant | Product | ProductType | ProductMedia | Category | Collection | Order | PageType
+union _Entity = App | PageType | Address | User | Group | ProductVariant | Product | ProductType | ProductMedia | Category | Collection | Order
"""_Service manifest as defined by Federation spec."""
type _Service {
diff --git a/saleor/graphql/shop/mutations/__init__.py b/saleor/graphql/shop/mutations/__init__.py
index 852ea71c2c..9d279c962c 100644
--- a/saleor/graphql/shop/mutations/__init__.py
+++ b/saleor/graphql/shop/mutations/__init__.py
@@ -1,5 +1,7 @@
from .gift_card_settings_update import GiftCardSettingsUpdate
from .order_settings_update import OrderSettingsUpdate
+from .refund_reason_reference_type_clear import RefundReasonReferenceTypeClear
+from .refund_settings_update import RefundSettingsUpdate
from .shop_address_update import ShopAddressUpdate
from .shop_domain_update import ShopDomainUpdate
from .shop_fetch_tax_rates import ShopFetchTaxRates
@@ -11,6 +13,8 @@ from .staff_notification_recipient_update import StaffNotificationRecipientUpdat
__all__ = [
"GiftCardSettingsUpdate",
"OrderSettingsUpdate",
+ "RefundSettingsUpdate",
+ "RefundReasonReferenceTypeClear",
"ShopAddressUpdate",
"ShopDomainUpdate",
"ShopFetchTaxRates",
diff --git a/saleor/graphql/shop/mutations/refund_reason_reference_type_clear.py b/saleor/graphql/shop/mutations/refund_reason_reference_type_clear.py
new file mode 100644
index 0000000000..0fc72a9441
--- /dev/null
+++ b/saleor/graphql/shop/mutations/refund_reason_reference_type_clear.py
@@ -0,0 +1,37 @@
+import graphene
+
+from ....permission.enums import SitePermissions
+from ...core import ResolveInfo
+from ...core.descriptions import ADDED_IN_322
+from ...core.doc_category import DOC_CATEGORY_ORDERS
+from ...core.mutations import BaseMutation
+from ...core.types.common import RefundReasonReferenceTypeClearError
+from ...site.dataloaders import get_site_promise
+from ..types import RefundSettings
+
+
+class RefundReasonReferenceTypeClear(BaseMutation):
+ refund_settings = graphene.Field(
+ RefundSettings, description="Refund settings.", required=True
+ )
+
+ class Meta:
+ description = (
+ "Updates RefundSettings. The `Page` (Model) Type will be cleared from `reasonReferenceType`. When it's cleared, passing reason reference to refund mutations is no longer accepted and will raise error."
+ + ADDED_IN_322
+ )
+ doc_category = DOC_CATEGORY_ORDERS
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = RefundReasonReferenceTypeClearError
+ error_type_field = "refund_settings_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ site = get_site_promise(info.context).get()
+ settings = site.settings
+
+ settings.refund_reason_reference_type = None
+
+ settings.save(update_fields=["refund_reason_reference_type"])
+
+ return RefundReasonReferenceTypeClear(refund_settings=settings)
diff --git a/saleor/graphql/shop/mutations/refund_settings_update.py b/saleor/graphql/shop/mutations/refund_settings_update.py
new file mode 100644
index 0000000000..e226a5f8ee
--- /dev/null
+++ b/saleor/graphql/shop/mutations/refund_settings_update.py
@@ -0,0 +1,66 @@
+import graphene
+
+from ....permission.enums import SitePermissions
+from ...core import ResolveInfo
+from ...core.descriptions import ADDED_IN_322
+from ...core.doc_category import DOC_CATEGORY_SHOP
+from ...core.mutations import BaseMutation
+from ...core.types import BaseInputObjectType
+from ...core.types.common import RefundSettingsUpdateError
+from ...site.dataloaders import get_site_promise
+from ..types import RefundSettings
+
+
+class RefundSettingsUpdateInput(BaseInputObjectType):
+ refund_reason_reference_type = graphene.ID(
+ description=(
+ "The ID of a model type, that will be used to reference refund reasons. "
+ "All models with of this type will be accepted as refund reasons. "
+ f"{ADDED_IN_322}"
+ ),
+ required=True,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_SHOP
+
+
+class RefundSettingsUpdate(BaseMutation):
+ refund_settings = graphene.Field(
+ RefundSettings, description="Refund settings.", required=True
+ )
+
+ class Arguments:
+ input = RefundSettingsUpdateInput(
+ required=True, description="Fields required to update refund settings."
+ )
+
+ class Meta:
+ description = "Update refund settings across all channels." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_SHOP
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = RefundSettingsUpdateError
+ error_type_field = "refund_settings_errors"
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, input
+ ):
+ refund_reason_reference_type = input.get("refund_reason_reference_type")
+
+ site = get_site_promise(info.context).get()
+ settings = site.settings
+
+ if refund_reason_reference_type:
+ model_type = cls.get_node_or_error(
+ info,
+ refund_reason_reference_type,
+ only_type="PageType",
+ field="refund_reason_reference_type",
+ )
+
+ settings.refund_reason_reference_type = model_type # type: ignore[assignment]
+
+ settings.save(update_fields=["refund_reason_reference_type"])
+
+ return RefundSettingsUpdate(refund_settings=settings)
diff --git a/saleor/graphql/shop/schema.py b/saleor/graphql/shop/schema.py
index 5523f4a1c4..f1a690c883 100644
--- a/saleor/graphql/shop/schema.py
+++ b/saleor/graphql/shop/schema.py
@@ -5,13 +5,19 @@ from ...permission.enums import GiftcardPermissions, OrderPermissions
from ..channel.types import OrderSettings
from ..core.context import get_database_connection_name
from ..core.descriptions import DEFAULT_DEPRECATION_REASON
-from ..core.doc_category import DOC_CATEGORY_GIFT_CARDS, DOC_CATEGORY_ORDERS
+from ..core.doc_category import (
+ DOC_CATEGORY_GIFT_CARDS,
+ DOC_CATEGORY_ORDERS,
+ DOC_CATEGORY_SHOP,
+)
from ..core.fields import PermissionsField
from ..site.dataloaders import load_site_callback
from ..translations.mutations import ShopSettingsTranslate
from .mutations import (
GiftCardSettingsUpdate,
OrderSettingsUpdate,
+ RefundReasonReferenceTypeClear,
+ RefundSettingsUpdate,
ShopAddressUpdate,
ShopDomainUpdate,
ShopFetchTaxRates,
@@ -20,7 +26,7 @@ from .mutations import (
StaffNotificationRecipientDelete,
StaffNotificationRecipientUpdate,
)
-from .types import GiftCardSettings, Shop
+from .types import GiftCardSettings, RefundSettings, Shop
class ShopQueries(graphene.ObjectType):
@@ -47,6 +53,13 @@ class ShopQueries(graphene.ObjectType):
permissions=[GiftcardPermissions.MANAGE_GIFT_CARD],
doc_category=DOC_CATEGORY_GIFT_CARDS,
)
+ refund_settings = PermissionsField(
+ RefundSettings,
+ description="Refunds related settings. Returns `RefundSettings` configuration, global for the entire shop.",
+ required=True,
+ permissions=[],
+ doc_category=DOC_CATEGORY_SHOP,
+ )
def resolve_shop(self, _info):
return Shop()
@@ -75,6 +88,10 @@ class ShopQueries(graphene.ObjectType):
def resolve_gift_card_settings(self, _info, site):
return site.settings
+ @load_site_callback
+ def resolve_refund_settings(self, _info, site):
+ return site.settings
+
class ShopMutations(graphene.ObjectType):
staff_notification_recipient_create = StaffNotificationRecipientCreate.Field()
@@ -95,3 +112,5 @@ class ShopMutations(graphene.ObjectType):
deprecation_reason="Use `channelUpdate` mutation instead."
)
gift_card_settings_update = GiftCardSettingsUpdate.Field()
+ refund_settings_update = RefundSettingsUpdate.Field()
+ refund_reason_reference_clear = RefundReasonReferenceTypeClear.Field()
diff --git a/saleor/graphql/shop/tests/mutations/test_reason_reference_type_clear.py b/saleor/graphql/shop/tests/mutations/test_reason_reference_type_clear.py
new file mode 100644
index 0000000000..413a26d659
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_reason_reference_type_clear.py
@@ -0,0 +1,198 @@
+from .....page.models import PageType
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+REFUND_REASON_REFERENCE_TYPE_CLEAR_MUTATION = """
+ mutation refundReasonReferenceClear {
+ refundReasonReferenceClear {
+ refundSettings {
+ reasonReferenceType {
+ id
+ name
+ slug
+ }
+ }
+ errors {
+ code
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_refund_reason_reference_type_clear_by_staff_success(
+ staff_api_client, site_settings, permission_manage_settings, page_type
+):
+ """Test successful clearing of refund reason reference type by staff user."""
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ # Set initial page type
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save()
+ assert site_settings.refund_reason_reference_type == page_type
+
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_REASON_REFERENCE_TYPE_CLEAR_MUTATION,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["refundReasonReferenceClear"]
+
+ assert not data["errors"]
+ assert data["refundSettings"]
+ assert data["refundSettings"]["reasonReferenceType"] is None
+
+ # Verify database update
+ site_settings.refresh_from_db()
+ assert site_settings.refund_reason_reference_type is None
+
+
+def test_refund_reason_reference_type_clear_by_app_success(
+ app_api_client, site_settings, permission_manage_settings, page_type
+):
+ """Test successful clearing of refund reason reference type by app."""
+ # given
+ app_api_client.app.permissions.add(permission_manage_settings)
+
+ # Set initial page type
+ site_settings.refund_reason_reference_type = page_type
+ site_settings.save()
+ assert site_settings.refund_reason_reference_type == page_type
+
+ # when
+ response = app_api_client.post_graphql(
+ REFUND_REASON_REFERENCE_TYPE_CLEAR_MUTATION,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["refundReasonReferenceClear"]
+
+ assert not data["errors"]
+ assert data["refundSettings"]
+ assert data["refundSettings"]["reasonReferenceType"] is None
+
+ # Verify database update
+ site_settings.refresh_from_db()
+ assert site_settings.refund_reason_reference_type is None
+
+
+def test_refund_reason_reference_type_clear_when_already_none(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ """Test clearing when refund reason reference type is already None."""
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ # Ensure it's already None
+ site_settings.refund_reason_reference_type = None
+ site_settings.save()
+ assert site_settings.refund_reason_reference_type is None
+
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_REASON_REFERENCE_TYPE_CLEAR_MUTATION,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["refundReasonReferenceClear"]
+
+ assert not data["errors"]
+ assert data["refundSettings"]
+ assert data["refundSettings"]["reasonReferenceType"] is None
+
+ # Verify database state remains unchanged
+ site_settings.refresh_from_db()
+ assert site_settings.refund_reason_reference_type is None
+
+
+def test_refund_reason_reference_type_clear_multiple_page_types(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ """Test clearing when multiple page types exist."""
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ # Create multiple page types
+ page_type1 = PageType.objects.create(name="Type 1", slug="type-1")
+ page_type2 = PageType.objects.create(name="Type 2", slug="type-2")
+
+ # Set one as the reference type
+ site_settings.refund_reason_reference_type = page_type1
+ site_settings.save()
+ assert site_settings.refund_reason_reference_type == page_type1
+
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_REASON_REFERENCE_TYPE_CLEAR_MUTATION,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["refundReasonReferenceClear"]
+
+ assert not data["errors"]
+ assert data["refundSettings"]
+ assert data["refundSettings"]["reasonReferenceType"] is None
+
+ # Verify database update
+ site_settings.refresh_from_db()
+ assert site_settings.refund_reason_reference_type is None
+
+ # Verify other page types still exist
+ assert PageType.objects.filter(id=page_type1.id).exists()
+ assert PageType.objects.filter(id=page_type2.id).exists()
+
+
+def test_refund_reason_reference_type_clear_no_permission_staff(
+ staff_api_client,
+):
+ """Test permission denied for staff without proper permissions."""
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_REASON_REFERENCE_TYPE_CLEAR_MUTATION
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_refund_reason_reference_type_clear_no_permission_customer(
+ user_api_client,
+):
+ """Test permission denied for customer users."""
+ # when
+ response = user_api_client.post_graphql(REFUND_REASON_REFERENCE_TYPE_CLEAR_MUTATION)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_refund_reason_reference_type_clear_no_permission_anonymous(
+ api_client,
+):
+ """Test permission denied for anonymous users."""
+ # when
+ response = api_client.post_graphql(REFUND_REASON_REFERENCE_TYPE_CLEAR_MUTATION)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_refund_reason_reference_type_clear_app_no_permission(
+ app_api_client,
+):
+ """Test permission denied for app without proper permissions."""
+ # when
+ response = app_api_client.post_graphql(REFUND_REASON_REFERENCE_TYPE_CLEAR_MUTATION)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/shop/tests/mutations/test_refund_settings_update.py b/saleor/graphql/shop/tests/mutations/test_refund_settings_update.py
new file mode 100644
index 0000000000..d9a06866d9
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_refund_settings_update.py
@@ -0,0 +1,252 @@
+import graphene
+
+from .....page.models import PageType
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+REFUND_SETTINGS_UPDATE_MUTATION = """
+ mutation refundSettingsUpdate($input: RefundSettingsUpdateInput!) {
+ refundSettingsUpdate(input: $input) {
+ refundSettings {
+ reasonReferenceType {
+ id
+ name
+ slug
+ }
+ }
+ errors {
+ code
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_refund_settings_update_by_staff_success(
+ staff_api_client, site_settings, permission_manage_settings, page_type
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ assert site_settings.refund_reason_reference_type is None
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"refundReasonReferenceType": page_type_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["refundSettingsUpdate"]
+
+ assert not data["errors"]
+ assert data["refundSettings"]
+ assert data["refundSettings"]["reasonReferenceType"]["id"] == page_type_id
+ assert data["refundSettings"]["reasonReferenceType"]["name"] == page_type.name
+ assert data["refundSettings"]["reasonReferenceType"]["slug"] == page_type.slug
+
+ # Verify database update
+ site_settings.refresh_from_db()
+ assert site_settings.refund_reason_reference_type == page_type
+
+
+def test_refund_settings_update_by_app_success(
+ app_api_client, site_settings, permission_manage_settings, page_type
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_settings)
+
+ assert site_settings.refund_reason_reference_type is None
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"refundReasonReferenceType": page_type_id}}
+
+ # when
+ response = app_api_client.post_graphql(
+ REFUND_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["refundSettingsUpdate"]
+
+ assert not data["errors"]
+ assert data["refundSettings"]
+ assert data["refundSettings"]["reasonReferenceType"]["id"] == page_type_id
+
+ # Verify database update
+ site_settings.refresh_from_db()
+ assert site_settings.refund_reason_reference_type == page_type
+
+
+def test_refund_settings_update_change_page_type(
+ staff_api_client, site_settings, permission_manage_settings, page_type
+):
+ # given - set initial page type
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ initial_page_type = PageType.objects.create(
+ name="Initial Type", slug="initial-type"
+ )
+ site_settings.refund_reason_reference_type = initial_page_type
+ site_settings.save()
+
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"refundReasonReferenceType": page_type_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["refundSettingsUpdate"]
+
+ assert not data["errors"]
+ assert data["refundSettings"]["reasonReferenceType"]["id"] == page_type_id
+
+ # Verify database update
+ site_settings.refresh_from_db()
+ assert site_settings.refund_reason_reference_type == page_type
+
+
+def test_refund_settings_update_empty_id_success(
+ staff_api_client, permission_manage_settings, site_settings
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ variables = {"input": {"refundReasonReferenceType": ""}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["refundSettingsUpdate"]
+
+ assert not data["errors"]
+ assert data["refundSettings"]
+ assert data["refundSettings"]["reasonReferenceType"] is None
+
+
+def test_refund_settings_update_invalid_id_format(
+ staff_api_client, permission_manage_settings
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ variables = {"input": {"refundReasonReferenceType": "invalid-id-format"}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert "errors" in content
+
+
+def test_refund_settings_update_nonexistent_page_type(
+ staff_api_client, permission_manage_settings
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ nonexistent_id = graphene.Node.to_global_id("PageType", 99999)
+ variables = {"input": {"refundReasonReferenceType": nonexistent_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert "errors" in content
+
+
+def test_refund_settings_update_wrong_page_type(
+ staff_api_client, permission_manage_settings, product
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ variables = {"input": {"refundReasonReferenceType": product_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ REFUND_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert "errors" in content
+
+
+def test_refund_settings_update_no_permission_staff(staff_api_client, page_type):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"refundReasonReferenceType": page_type_id}}
+
+ # when
+ response = staff_api_client.post_graphql(REFUND_SETTINGS_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_refund_settings_update_no_permission_customer(user_api_client, page_type):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"refundReasonReferenceType": page_type_id}}
+
+ # when
+ response = user_api_client.post_graphql(REFUND_SETTINGS_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_refund_settings_update_no_permission_anonymous(api_client, page_type):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"refundReasonReferenceType": page_type_id}}
+
+ # when
+ response = api_client.post_graphql(REFUND_SETTINGS_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_refund_settings_update_app_no_permission(app_api_client, page_type):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"refundReasonReferenceType": page_type_id}}
+
+ # when
+ response = app_api_client.post_graphql(REFUND_SETTINGS_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 644c62d23c..31554f7374 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -18,6 +18,7 @@ from ..core import ResolveInfo
from ..core.context import get_database_connection_name
from ..core.descriptions import (
ADDED_IN_319,
+ ADDED_IN_322,
DEFAULT_DEPRECATION_REASON,
DEPRECATED_IN_3X_INPUT,
)
@@ -40,6 +41,7 @@ from ..core.types import (
)
from ..core.utils import str_to_enum
from ..meta.types import ObjectWithMetadata
+from ..page.types import PageType
from ..payment.types import PaymentGateway
from ..plugins.dataloaders import plugin_manager_promise_callback
from ..shipping.types import ShippingMethod
@@ -79,6 +81,20 @@ class OrderSettings(ModelObjectType[site_models.SiteSettings]):
model = site_models.SiteSettings
+class RefundSettings(ModelObjectType[site_models.SiteSettings]):
+ reason_reference_type = graphene.Field(
+ PageType, description="Model type used for refund reasons."
+ )
+
+ class Meta:
+ description = "Refund related settings from site settings." + ADDED_IN_322
+ doc_category = DOC_CATEGORY_ORDERS
+ model = site_models.SiteSettings
+
+ def resolve_reason_reference_type(root, info):
+ return root.refund_reason_reference_type
+
+
class GiftCardSettings(ModelObjectType[site_models.SiteSettings]):
expiry_type = GiftCardSettingsExpiryTypeEnum(
description="The gift card expiry type settings.", required=True
diff --git a/saleor/order/migrations/0217_ordergrantedrefund_reason_reference.py b/saleor/order/migrations/0217_ordergrantedrefund_reason_reference.py
new file mode 100644
index 0000000000..63b3e7dd09
--- /dev/null
+++ b/saleor/order/migrations/0217_ordergrantedrefund_reason_reference.py
@@ -0,0 +1,25 @@
+# Generated by Django 5.2.1 on 2025-08-08 09:29
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0216_merge_20250704_1033"),
+ ("page", "0031_alter_page_metadata_alter_page_private_metadata_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="ordergrantedrefund",
+ name="reason_reference",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="page.page",
+ ),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 3b77bdca81..c579b3b72d 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -922,6 +922,9 @@ class OrderGrantedRefund(models.Model):
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
)
reason = models.TextField(blank=True, default="")
+ reason_reference = models.ForeignKey(
+ "page.Page", related_name="+", on_delete=models.SET_NULL, null=True, blank=True
+ )
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=True,
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index 7a15be1b8e..9874f50be6 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -43,6 +43,7 @@ class TransactionUpdateErrorCode(Enum):
class TransactionRequestActionErrorCode(Enum):
INVALID = "invalid"
+ REQUIRED = "required"
GRAPHQL_ERROR = "graphql_error"
NOT_FOUND = "not_found"
MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK = (
diff --git a/saleor/payment/migrations/0065_transactionevent_reason_reference.py b/saleor/payment/migrations/0065_transactionevent_reason_reference.py
new file mode 100644
index 0000000000..45722ce29c
--- /dev/null
+++ b/saleor/payment/migrations/0065_transactionevent_reason_reference.py
@@ -0,0 +1,25 @@
+# Generated by Django 5.2.1 on 2025-08-12 06:07
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("page", "0031_alter_page_metadata_alter_page_private_metadata_and_more"),
+ ("payment", "0064_merge_20250716_0709"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="transactionevent",
+ name="reason_reference",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="page.page",
+ ),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 1023d82c12..66de0ffc80 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -240,6 +240,10 @@ class TransactionEvent(models.Model):
on_delete=models.SET_NULL,
)
+ reason_reference = models.ForeignKey(
+ "page.Page", related_name="+", on_delete=models.SET_NULL, blank=True, null=True
+ )
+
class Meta:
ordering = ("pk",)
constraints = [
diff --git a/saleor/site/error_codes.py b/saleor/site/error_codes.py
index b60a63e7aa..c25755771c 100644
--- a/saleor/site/error_codes.py
+++ b/saleor/site/error_codes.py
@@ -14,3 +14,9 @@ class GiftCardSettingsErrorCode(Enum):
INVALID = "invalid"
REQUIRED = "required"
GRAPHQL_ERROR = "graphql_error"
+
+
+class RefundSettingsErrorCode(Enum):
+ INVALID = "invalid"
+ REQUIRED = "required"
+ GRAPHQL_ERROR = "graphql_error"
diff --git a/saleor/site/migrations/0042_sitesettings_refund_reason_reference_type.py b/saleor/site/migrations/0042_sitesettings_refund_reason_reference_type.py
new file mode 100644
index 0000000000..31a3572ac7
--- /dev/null
+++ b/saleor/site/migrations/0042_sitesettings_refund_reason_reference_type.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.1 on 2025-08-12 13:06
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("page", "0031_alter_page_metadata_alter_page_private_metadata_and_more"),
+ ("site", "0041_alter_sitesettings_metadata_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sitesettings",
+ name="refund_reason_reference_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="page.pagetype",
+ ),
+ ),
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index ceab38eb1a..c0d59508e9 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -95,6 +95,11 @@ class SiteSettings(ModelWithMetadata):
)
gift_card_expiry_period = models.PositiveIntegerField(null=True, blank=True)
+ # refund settings
+ refund_reason_reference_type = models.ForeignKey(
+ null=True, blank=True, on_delete=models.SET_NULL, to="page.PageType"
+ )
+
# deprecated
charge_taxes_on_shipping = models.BooleanField(default=True)
include_taxes_in_prices = models.BooleanField(default=True)
diff --git a/saleor/site/tests/fixtures/site_settings.py b/saleor/site/tests/fixtures/site_settings.py
index 45a5e8dd1c..c55b456f9d 100644
--- a/saleor/site/tests/fixtures/site_settings.py
+++ b/saleor/site/tests/fixtures/site_settings.py
@@ -15,6 +15,7 @@ def site_settings(db, settings) -> SiteSettings:
site = Site.objects.get_or_create(name="example.com", domain="example.com")[0]
obj = SiteSettings.objects.get_or_create(
site=site,
+ refund_reason_reference_type=None,
default_mail_sender_name="Example",
default_mail_sender_address="[email protected]",
)[0]