Skip to content

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

Refund Reasons phase 2 (#19272)

Lukasz Ostrowski901a5299cfca
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 6bea4a5635..2edf9e5371 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -266,6 +266,11 @@ RefundSettingsErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(
)
RefundSettingsErrorCode.doc_category = DOC_CATEGORY_SHOP
+ReturnSettingsErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(
+ site_error_codes.ReturnSettingsErrorCode
+)
+ReturnSettingsErrorCode.doc_category = DOC_CATEGORY_SHOP
+
MetadataErrorCode: Final[graphene.Enum] = graphene.Enum.from_enum(
core_error_codes.MetadataErrorCode
)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 20be8eff00..8de81eaa91 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -70,6 +70,7 @@ from ..enums import (
ProductVariantBulkErrorCode,
ProductVariantTranslateErrorCode,
RefundSettingsErrorCode,
+ ReturnSettingsErrorCode,
SendConfirmationEmailErrorCode,
ShippingErrorCode,
ShopErrorCode,
@@ -372,6 +373,24 @@ class RefundReasonReferenceTypeClearError(Error):
doc_category = DOC_CATEGORY_SHOP
+class ReturnSettingsUpdateError(Error):
+ code = ReturnSettingsErrorCode(
+ description="Failed to update Return Settings", required=True
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_SHOP
+
+
+class ReturnReasonReferenceTypeClearError(Error):
+ code = ReturnSettingsErrorCode(
+ description="Failed to clear return 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/dataloaders.py b/saleor/graphql/order/dataloaders.py
index ba596c2d0a..91ef497284 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -151,6 +151,16 @@ class OrderEventsByIdLoader(DataLoader[int, OrderEvent]):
return [events.get(event_id) for event_id in keys]
+class OrderGrantedRefundByIdLoader(DataLoader[int, OrderGrantedRefund]):
+ context_key = "order_granted_refund_by_id"
+
+ def batch_load(self, keys):
+ refunds = OrderGrantedRefund.objects.using(
+ self.database_connection_name
+ ).in_bulk(keys)
+ return [refunds.get(refund_id) for refund_id in keys]
+
+
class OrderGrantedRefundsByOrderIdLoader(DataLoader[UUID, list[OrderGrantedRefund]]):
context_key = "order_granted_refunds_by_order_id"
@@ -198,6 +208,16 @@ class AllocationsByOrderLineIdLoader(DataLoader[UUID, list[Allocation]]):
return [order_lines_to_allocations[order_line_id] for order_line_id in keys]
+class FulfillmentByIdLoader(DataLoader[int, Fulfillment]):
+ context_key = "fulfillment_by_id"
+
+ def batch_load(self, keys):
+ fulfillments = Fulfillment.objects.using(self.database_connection_name).in_bulk(
+ keys
+ )
+ return [fulfillments.get(fulfillment_id) for fulfillment_id in keys]
+
+
class FulfillmentsByOrderIdLoader(DataLoader[UUID, list[Fulfillment]]):
context_key = "fulfillments_by_order"
diff --git a/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py b/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py
index c3c4c1ebf7..e5afb4b981 100644
--- a/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py
+++ b/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py
@@ -1,3 +1,5 @@
+from uuid import UUID
+
import graphene
from django.core.exceptions import ValidationError
@@ -6,14 +8,46 @@ from ....order import FulfillmentLineData
from ....order import models as order_models
from ....order.error_codes import OrderErrorCode
from ....order.fetch import OrderLineInfo
+from ....page.models import Page, PageType
+from ....site.models import SiteSettings
from ...core.mutations import BaseMutation
+from ...payment.utils import validate_reason_reference_context
from ..types import FulfillmentLine, OrderLine
+from .order_grant_refund_utils import resolve_reason_reference_page
class FulfillmentRefundAndReturnProductBase(BaseMutation):
class Meta:
abstract = True
+ @classmethod
+ def _resolve_line_reason_reference(
+ cls,
+ reason_reference_id: str | None,
+ site_settings: SiteSettings | None,
+ reason_reference_type: PageType | None,
+ ) -> Page | None:
+ """Validate and resolve a per-line reason reference to a Page.
+
+ Per-line references are always optional (for both staff and apps); when
+ provided the referenced Page must match the configured reference type.
+ Reason processing is skipped entirely when ``site_settings`` is not given.
+ """
+ if not site_settings or reason_reference_id is None:
+ return None
+ should_apply = validate_reason_reference_context(
+ reason_reference_id=reason_reference_id,
+ requestor_is_user=False,
+ reason_reference_field_name="reason_reference",
+ error_code_enum=OrderErrorCode,
+ reason_reference_type=reason_reference_type,
+ )
+ if should_apply and reason_reference_type:
+ return resolve_reason_reference_page(
+ str(reason_reference_id), reason_reference_type.pk, OrderErrorCode
+ )
+ return None
+
@classmethod
def clean_order_payment(cls, payment, cleaned_input):
if not payment or not payment.can_refund():
@@ -85,7 +119,12 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
@classmethod
def clean_fulfillment_lines(
- cls, fulfillment_lines_data, cleaned_input, whitelisted_statuses
+ cls,
+ fulfillment_lines_data,
+ cleaned_input,
+ whitelisted_statuses,
+ site_settings: SiteSettings | None = None,
+ reason_reference_type: PageType | None = None,
):
fulfillment_lines = cls.get_nodes_or_error(
[line["fulfillment_line_id"] for line in fulfillment_lines_data],
@@ -134,17 +173,30 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
line.pk,
"order_line_id",
)
+ reason_reference_instance = cls._resolve_line_reason_reference(
+ line_data.get("reason_reference"),
+ site_settings,
+ reason_reference_type,
+ )
cleaned_fulfillment_lines.append(
FulfillmentLineData(
line=line,
quantity=quantity,
replace=replace,
+ reason=line_data.get("reason"),
+ reason_reference=reason_reference_instance,
)
)
cleaned_input["fulfillment_lines"] = cleaned_fulfillment_lines
@classmethod
- def clean_lines(cls, lines_data, cleaned_input):
+ def clean_lines(
+ cls,
+ lines_data,
+ cleaned_input,
+ site_settings: SiteSettings | None = None,
+ reason_reference_type: PageType | None = None,
+ ):
order_lines = cls.get_nodes_or_error(
[line["order_line_id"] for line in lines_data],
field="order_lines",
@@ -155,6 +207,7 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
)
order_lines = list(order_lines)
cleaned_order_lines = []
+ order_lines_reason_data: dict[UUID, tuple[str | None, Page | None]] = {}
for line, line_data in zip(order_lines, lines_data, strict=False):
quantity = line_data["quantity"]
if line.is_gift_card:
@@ -190,9 +243,19 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
"order_line_id",
)
+ reason_reference_instance = cls._resolve_line_reason_reference(
+ line_data.get("reason_reference"),
+ site_settings,
+ reason_reference_type,
+ )
cleaned_order_lines.append(
OrderLineInfo(
line=line, quantity=quantity, variant=variant, replace=replace
)
)
+ order_lines_reason_data[line.pk] = (
+ line_data.get("reason"),
+ reason_reference_instance,
+ )
cleaned_input["order_lines"] = cleaned_order_lines
+ cleaned_input["order_lines_reason_data"] = order_lines_reason_data
diff --git a/saleor/graphql/order/mutations/fulfillment_return_products.py b/saleor/graphql/order/mutations/fulfillment_return_products.py
index b3b18ce45b..d63b54dd0d 100644
--- a/saleor/graphql/order/mutations/fulfillment_return_products.py
+++ b/saleor/graphql/order/mutations/fulfillment_return_products.py
@@ -5,20 +5,24 @@ import graphene
from ....order import FulfillmentStatus
from ....order import models as order_models
from ....order.actions import create_fulfillments_for_returned_products
+from ....order.error_codes import OrderErrorCode
from ....payment import PaymentError
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
from ...core.context import SyncWebhookControlContext
+from ...core.descriptions import ADDED_IN_323
from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.scalars import PositiveDecimal
from ...core.types import BaseInputObjectType, NonNullList, OrderError
+from ...payment.utils import validate_reason_reference_context
from ...plugins.dataloaders import get_plugin_manager_promise
from ...site.dataloaders import get_site_promise
from ..types import Fulfillment, Order
from .fulfillment_refund_and_return_product_base import (
FulfillmentRefundAndReturnProductBase,
)
+from .order_grant_refund_utils import resolve_reason_reference_page
class OrderReturnLineInput(BaseInputObjectType):
@@ -35,6 +39,13 @@ class OrderReturnLineInput(BaseInputObjectType):
description="Determines, if the line should be added to replace order.",
default_value=False,
)
+ reason = graphene.String(
+ description="Reason for returning this line." + ADDED_IN_323,
+ )
+ reason_reference = graphene.ID(
+ description="ID of a `Page` (Model) to reference in reason for this line."
+ + ADDED_IN_323,
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -54,6 +65,13 @@ class OrderReturnFulfillmentLineInput(BaseInputObjectType):
description="Determines, if the line should be added to replace order.",
default_value=False,
)
+ reason = graphene.String(
+ description="Reason for returning this fulfillment line." + ADDED_IN_323,
+ )
+ reason_reference = graphene.ID(
+ description="ID of a `Page` (Model) to reference in reason for this "
+ "fulfillment line." + ADDED_IN_323,
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -83,6 +101,13 @@ class OrderReturnProductsInput(BaseInputObjectType):
description="If true, Saleor will call refund action for all lines.",
default_value=False,
)
+ reason = graphene.String(
+ description="Reason for returning this order." + ADDED_IN_323,
+ )
+ reason_reference = graphene.ID(
+ description="ID of a `Page` (Model) to reference in reason for this return."
+ + ADDED_IN_323,
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -123,6 +148,8 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
amount_to_refund = input.get("amount_to_refund")
include_shipping_costs = input["include_shipping_costs"]
refund = input["refund"]
+ reason = input.get("reason") or ""
+ reason_reference_id = input.get("reason_reference")
qs = order_models.Order.objects.prefetch_related("payments")
order = cls.get_node_or_error(
@@ -136,11 +163,32 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
order, amount_to_refund, charged_value, cleaned_input
)
+ site = get_site_promise(info.context).get()
+ return_reason_reference_type = site.settings.return_reason_reference_type
+ requestor_is_user = info.context.user is not None and info.context.app is None
+
+ should_apply = validate_reason_reference_context(
+ reason_reference_id=reason_reference_id,
+ requestor_is_user=requestor_is_user,
+ reason_reference_field_name="reason_reference",
+ error_code_enum=OrderErrorCode,
+ reason_reference_type=return_reason_reference_type,
+ )
+ reason_reference_instance = None
+ if should_apply and return_reason_reference_type:
+ reason_reference_instance = resolve_reason_reference_page(
+ str(reason_reference_id),
+ return_reason_reference_type.pk,
+ OrderErrorCode,
+ )
+
cleaned_input.update(
{
"include_shipping_costs": include_shipping_costs,
"order": order,
"refund": refund,
+ "reason": reason,
+ "reason_reference_instance": reason_reference_instance,
}
)
@@ -148,7 +196,12 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
fulfillment_lines_data = input.get("fulfillment_lines")
if order_lines_data:
- cls.clean_lines(order_lines_data, cleaned_input)
+ cls.clean_lines(
+ order_lines_data,
+ cleaned_input,
+ site_settings=site.settings,
+ reason_reference_type=return_reason_reference_type,
+ )
if fulfillment_lines_data:
cls.clean_fulfillment_lines(
fulfillment_lines_data,
@@ -158,6 +211,8 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
FulfillmentStatus.REFUNDED,
FulfillmentStatus.WAITING_FOR_APPROVAL,
],
+ site_settings=site.settings,
+ reason_reference_type=return_reason_reference_type,
)
return cleaned_input
@@ -182,6 +237,9 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
cleaned_input["refund"],
cleaned_input.get("amount_to_refund"),
cleaned_input["include_shipping_costs"],
+ reason=cleaned_input.get("reason", ""),
+ reason_reference=cleaned_input.get("reason_reference_instance"),
+ order_lines_reason_data=cleaned_input.get("order_lines_reason_data"),
)
except PaymentError:
cls.raise_error_for_payment_error()
diff --git a/saleor/graphql/order/mutations/order_grant_refund_create.py b/saleor/graphql/order/mutations/order_grant_refund_create.py
index be32c28176..e37680d796 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_create.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_create.py
@@ -11,21 +11,26 @@ 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, ADDED_IN_322, PREVIEW_FEATURE
+from ...core.descriptions import (
+ ADDED_IN_320,
+ ADDED_IN_322,
+ ADDED_IN_323,
+ 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 ...payment.utils import validate_reason_reference_context
from ...site.dataloaders import get_site_promise
from ..enums import OrderGrantRefundCreateErrorCode, OrderGrantRefundCreateLineErrorCode
from ..types import Order, OrderGrantedRefund
from .order_grant_refund_utils import (
- assign_order_lines,
- get_input_lines_data,
- handle_lines_with_quantity_already_refunded,
+ GrantRefundLineDict,
+ clean_grant_refund_lines,
+ resolve_reason_reference_page,
shipping_costs_already_granted,
)
@@ -57,6 +62,10 @@ class OrderGrantRefundCreateLineInput(BaseInputObjectType):
description="The quantity of line items to be marked to refund.", required=True
)
reason = graphene.String(description="Reason of the granted refund for the line.")
+ reason_reference = graphene.ID(
+ description="ID of a `Page` (Model) to reference in reason for the line."
+ + ADDED_IN_323,
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -125,29 +134,28 @@ class OrderGrantRefundCreate(BaseMutation):
def clean_input_lines(
cls,
order: models.Order,
- lines: list[dict[str, str | int]],
- ) -> tuple[list[models.OrderGrantedRefundLine], list[dict[str, str]] | None]:
- errors: list[dict[str, str]] = []
- input_lines_data = get_input_lines_data(
- lines, errors, OrderGrantRefundCreateLineErrorCode.GRAPHQL_ERROR.value
+ lines: list[GrantRefundLineDict],
+ refund_reason_reference_type_pk: int | None,
+ ) -> list[models.OrderGrantedRefundLine]:
+ lines_errors: list[dict[str, str]] = []
+ result = clean_grant_refund_lines(
+ order=order,
+ lines=lines,
+ refund_reason_reference_type_pk=refund_reason_reference_type_pk,
+ errors=lines_errors,
+ line_error_code_enum=OrderGrantRefundCreateLineErrorCode,
)
- assign_order_lines(
- order,
- input_lines_data,
- errors,
- OrderGrantRefundCreateLineErrorCode.NOT_FOUND.value,
- )
- handle_lines_with_quantity_already_refunded(
- order,
- input_lines_data,
- errors,
- OrderGrantRefundCreateLineErrorCode.QUANTITY_GREATER_THAN_AVAILABLE.value,
- )
-
- if errors:
- return [], errors
-
- return list(input_lines_data.values()), None
+ if lines_errors:
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ "Provided input for lines is invalid.",
+ code=OrderGrantRefundCreateErrorCode.INVALID.value,
+ params={"lines": lines_errors},
+ ),
+ }
+ )
+ return result
@classmethod
def calculate_amount(
@@ -188,32 +196,6 @@ 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,
@@ -230,21 +212,33 @@ class OrderGrantRefundCreate(BaseMutation):
cls.validate_input(input)
+ site = get_site_promise(info.context).get()
+
+ refund_reason_reference_type = site.settings.refund_reason_reference_type
+ should_apply = validate_reason_reference_context(
+ reason_reference_id=reason_reference_id,
+ requestor_is_user=bool(info.context.user),
+ reason_reference_field_name="reason_reference",
+ error_code_enum=OrderGrantRefundCreateErrorCode,
+ reason_reference_type=refund_reason_reference_type,
+ )
+ refund_reason_reference_type_pk = (
+ refund_reason_reference_type.pk if refund_reason_reference_type else None
+ )
+
+ reason_reference_instance: Page | None = None
+ if should_apply and refund_reason_reference_type_pk:
+ reason_reference_instance = resolve_reason_reference_page(
+ str(reason_reference_id),
+ refund_reason_reference_type_pk,
+ OrderGrantRefundCreateErrorCode,
+ )
+
cleaned_input_lines: list[models.OrderGrantedRefundLine] = []
if input_lines:
- cleaned_input_lines, lines_errors = cls.clean_input_lines(
- order, input_lines
+ cleaned_input_lines = cls.clean_input_lines(
+ order, input_lines, refund_reason_reference_type_pk
)
- if lines_errors:
- raise ValidationError(
- {
- "lines": ValidationError(
- "Provided input for lines is invalid.",
- code=OrderGrantRefundCreateErrorCode.INVALID.value,
- params={"lines": lines_errors},
- ),
- }
- )
if grant_refund_for_shipping and shipping_costs_already_granted(order):
error_code = OrderGrantRefundCreateErrorCode.SHIPPING_COSTS_ALREADY_GRANTED
raise ValidationError(
@@ -287,31 +281,6 @@ 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
-
- site = get_site_promise(info.context).get()
-
- 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,
- site_settings=site.settings,
- )
-
- 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,
diff --git a/saleor/graphql/order/mutations/order_grant_refund_update.py b/saleor/graphql/order/mutations/order_grant_refund_update.py
index d9a1026806..77002698f3 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_update.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_update.py
@@ -11,7 +11,12 @@ 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, ADDED_IN_322, PREVIEW_FEATURE
+from ...core.descriptions import (
+ ADDED_IN_320,
+ ADDED_IN_322,
+ ADDED_IN_323,
+ PREVIEW_FEATURE,
+)
from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.mutations import BaseMutation
from ...core.scalars import Decimal
@@ -19,14 +24,14 @@ 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 ...payment.utils import validate_reason_reference_context
from ...site.dataloaders import get_site_promise
from ..enums import OrderGrantRefundUpdateErrorCode, OrderGrantRefundUpdateLineErrorCode
from ..types import Order, OrderGrantedRefund
from .order_grant_refund_utils import (
- assign_order_lines,
- get_input_lines_data,
- handle_lines_with_quantity_already_refunded,
+ GrantRefundLineDict,
+ clean_grant_refund_lines,
+ resolve_reason_reference_page,
shipping_costs_already_granted,
)
@@ -64,6 +69,10 @@ class OrderGrantRefundUpdateLineAddInput(BaseInputObjectType):
description="The quantity of line items to be marked to refund.", required=True
)
reason = graphene.String(description="Reason of the granted refund for the line.")
+ reason_reference = graphene.ID(
+ description="ID of a `Page` (Model) to reference in reason for the line."
+ + ADDED_IN_323,
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -226,53 +235,20 @@ class OrderGrantRefundUpdate(BaseMutation):
def clean_add_lines(
cls,
order: models.Order,
- lines: list[dict[str, str | int]],
+ lines: list[GrantRefundLineDict],
errors: list[dict[str, Any]],
line_ids_exclude: list[int],
+ refund_reason_reference_type_pk: int | None,
) -> list[models.OrderGrantedRefundLine]:
- input_lines_data = get_input_lines_data(
- lines, errors, OrderGrantRefundUpdateLineErrorCode.GRAPHQL_ERROR.value
- )
- assign_order_lines(
- order,
- input_lines_data,
- errors,
- OrderGrantRefundUpdateLineErrorCode.NOT_FOUND.value,
- )
- handle_lines_with_quantity_already_refunded(
- order,
- input_lines_data,
- errors,
- OrderGrantRefundUpdateLineErrorCode.QUANTITY_GREATER_THAN_AVAILABLE.value,
+ return clean_grant_refund_lines(
+ order=order,
+ lines=lines,
+ refund_reason_reference_type_pk=refund_reason_reference_type_pk,
+ errors=errors,
+ line_error_code_enum=OrderGrantRefundUpdateLineErrorCode,
granted_refund_lines_to_exclude=line_ids_exclude,
)
- 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,
@@ -293,8 +269,27 @@ class OrderGrantRefundUpdate(BaseMutation):
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
+ site = get_site_promise(info.context).get()
+
+ refund_reason_reference_type = site.settings.refund_reason_reference_type
+ should_apply = validate_reason_reference_context(
+ reason_reference_id=reason_reference_id,
+ requestor_is_user=bool(info.context.user),
+ reason_reference_field_name="reason_reference",
+ error_code_enum=OrderGrantRefundUpdateErrorCode,
+ reason_reference_type=refund_reason_reference_type,
+ )
+ refund_reason_reference_type_pk = (
+ refund_reason_reference_type.pk if refund_reason_reference_type else None
+ )
+
+ reason_reference_instance: Page | None = None
+ if should_apply and refund_reason_reference_type_pk:
+ reason_reference_instance = resolve_reason_reference_page(
+ str(reason_reference_id),
+ refund_reason_reference_type_pk,
+ OrderGrantRefundUpdateErrorCode,
+ )
line_ids_to_remove = []
if remove_lines:
@@ -309,10 +304,14 @@ class OrderGrantRefundUpdate(BaseMutation):
params={"remove_lines": remove_errors},
)
- lines_to_add = []
+ lines_to_add: list[models.OrderGrantedRefundLine] = []
if add_lines:
lines_to_add = cls.clean_add_lines(
- order, add_lines, add_errors, line_ids_to_remove
+ order,
+ add_lines,
+ add_errors,
+ line_ids_to_remove,
+ refund_reason_reference_type_pk,
)
for line in lines_to_add:
line.granted_refund = granted_refund
@@ -377,29 +376,6 @@ class OrderGrantRefundUpdate(BaseMutation):
if errors:
raise ValidationError(errors)
- site = get_site_promise(info.context).get()
-
- 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,
- site_settings=site.settings,
- )
-
- 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,
diff --git a/saleor/graphql/order/mutations/order_grant_refund_utils.py b/saleor/graphql/order/mutations/order_grant_refund_utils.py
index 6c1b069731..bec96a296f 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_utils.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_utils.py
@@ -1,14 +1,23 @@
import uuid
from collections import defaultdict
-from typing import Any, cast
+from typing import Any, TypedDict
import graphene
+from django.core.exceptions import ValidationError
from graphql import GraphQLError
from ....order import models
+from ....page.models import Page
from ...core.utils import from_global_id_or_error
+class GrantRefundLineDict(TypedDict, total=False):
+ id: str
+ quantity: int
+ reason: str
+ reason_reference: str
+
+
def shipping_costs_already_granted(
order: models.Order, grant_refund_pk_to_exclude=None
):
@@ -71,24 +80,105 @@ def handle_lines_with_quantity_already_refunded(
)
+def validate_reason_references(
+ lines: list[GrantRefundLineDict],
+ refund_reason_reference_type_pk: int | None,
+ errors: list[dict[str, Any]],
+ line_error_code_enum: Any,
+) -> dict[str, int]:
+ """Validate reason_reference IDs upfront and return a {global_id: page_pk} map."""
+ refs_by_line: list[tuple[str, str]] = []
+ for line in lines:
+ reason_ref = line.get("reason_reference")
+ if reason_ref:
+ refs_by_line.append((line["id"], reason_ref))
+
+ if not refs_by_line:
+ return {}
+
+ if not refund_reason_reference_type_pk:
+ for order_line_id, _ in refs_by_line:
+ errors.append(
+ {
+ "line_id": order_line_id,
+ "field": "reason_reference",
+ "message": "Reason reference type is not configured.",
+ "code": line_error_code_enum.NOT_CONFIGURED.value,
+ }
+ )
+ return {}
+
+ # Parse all global IDs to PKs
+ page_pks: dict[str, int] = {} # reason_reference global_id -> pk
+ for order_line_id, global_id in refs_by_line:
+ try:
+ _, pk_str = from_global_id_or_error(
+ global_id, only_type="Page", raise_error=True
+ )
+ except (GraphQLError, ValueError) as e:
+ errors.append(
+ {
+ "line_id": order_line_id,
+ "field": "reason_reference",
+ "message": str(e),
+ "code": line_error_code_enum.GRAPHQL_ERROR.value,
+ }
+ )
+ continue
+ page_pks[global_id] = int(pk_str)
+
+ if errors:
+ return {}
+
+ existing_page_pks: set[int] = set(
+ Page.objects.filter(
+ pk__in=page_pks.values(),
+ page_type=refund_reason_reference_type_pk,
+ ).values_list("pk", flat=True)
+ )
+
+ reason_reference_map: dict[str, int] = {}
+ for order_line_id, global_id in refs_by_line:
+ page_pk = page_pks[global_id]
+ if page_pk not in existing_page_pks:
+ errors.append(
+ {
+ "line_id": order_line_id,
+ "field": "reason_reference",
+ "message": "Invalid reason reference.",
+ "code": line_error_code_enum.INVALID.value,
+ }
+ )
+ else:
+ reason_reference_map[global_id] = page_pk
+
+ return reason_reference_map
+
+
def get_input_lines_data(
- lines: list[dict[str, str | int]],
+ lines: list[GrantRefundLineDict],
errors: list[dict[str, str]],
error_code: str,
+ reason_reference_map: dict[str, int],
) -> dict[uuid.UUID, models.OrderGrantedRefundLine]:
- granted_refund_lines = {}
+ input_lines: dict[uuid.UUID, models.OrderGrantedRefundLine] = {}
for line in lines:
- order_line_id = cast(str, line["id"])
+ order_line_id = line["id"]
try:
_, pk = from_global_id_or_error(
order_line_id, only_type="OrderLine", raise_error=True
)
uuid_pk = uuid.UUID(pk)
- reason = cast(str | None, line.get("reason"))
- granted_refund_lines[uuid_pk] = models.OrderGrantedRefundLine(
+ reason = line.get("reason")
+ reason_ref_gid = line.get("reason_reference")
+ reason_reference_id = (
+ reason_reference_map.get(reason_ref_gid) if reason_ref_gid else None
+ )
+ input_lines[uuid_pk] = models.OrderGrantedRefundLine(
order_line_id=uuid_pk,
- quantity=int(line["quantity"]),
+ quantity=line["quantity"],
reason=reason,
+ reason_reference_id=reason_reference_id,
)
except (GraphQLError, ValueError) as e:
errors.append(
@@ -99,7 +189,7 @@ def get_input_lines_data(
"message": str(e),
}
)
- return granted_refund_lines
+ return input_lines
def assign_order_lines(
@@ -124,3 +214,70 @@ def assign_order_lines(
)
for line_pk, order_line in lines_dict.items():
input_lines_data[line_pk].order_line = order_line
+
+
+def resolve_reason_reference_page(
+ reason_reference_id: str,
+ reason_reference_type_pk: int,
+ error_code_enum: Any,
+) -> Page:
+ """Resolve a reason_reference global ID to a Page instance.
+
+ Validates the Page belongs to the expected PageType.
+ """
+ try:
+ _, pk = from_global_id_or_error(
+ reason_reference_id, only_type="Page", raise_error=True
+ )
+ except GraphQLError as e:
+ raise ValidationError(
+ {
+ "reason_reference": ValidationError(
+ str(e),
+ code=error_code_enum.GRAPHQL_ERROR.value,
+ )
+ }
+ ) from None
+
+ try:
+ return Page.objects.get(pk=pk, page_type=reason_reference_type_pk)
+ except (Page.DoesNotExist, ValueError):
+ raise ValidationError(
+ {
+ "reason_reference": ValidationError(
+ "Invalid reason reference. Must be an ID of a Model (Page)",
+ code=error_code_enum.INVALID.value,
+ )
+ }
+ ) from None
+
+
+def clean_grant_refund_lines(
+ *,
+ order: models.Order,
+ lines: list[GrantRefundLineDict],
+ refund_reason_reference_type_pk: int | None,
+ errors: list[dict[str, Any]],
+ line_error_code_enum: Any,
+ granted_refund_lines_to_exclude: list[int] | None = None,
+) -> list[models.OrderGrantedRefundLine]:
+ reason_reference_map = validate_reason_references(
+ lines, refund_reason_reference_type_pk, errors, line_error_code_enum
+ )
+ input_lines_data = get_input_lines_data(
+ lines, errors, line_error_code_enum.GRAPHQL_ERROR.value, reason_reference_map
+ )
+ assign_order_lines(
+ order,
+ input_lines_data,
+ errors,
+ line_error_code_enum.NOT_FOUND.value,
+ )
+ handle_lines_with_quantity_already_refunded(
+ order,
+ input_lines_data,
+ errors,
+ line_error_code_enum.QUANTITY_GREATER_THAN_AVAILABLE.value,
+ granted_refund_lines_to_exclude=granted_refund_lines_to_exclude,
+ )
+ return list(input_lines_data.values())
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products_by_app.py b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products_by_app.py
new file mode 100644
index 0000000000..9d8b7ab6f5
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products_by_app.py
@@ -0,0 +1,52 @@
+import graphene
+
+from .....order.models import FulfillmentStatus
+from .....page.models import PageType
+from ....tests.utils import get_graphql_content
+from .test_fulfillment_return_products import ORDER_FULFILL_RETURN_MUTATION
+
+
+def test_fulfillment_return_products_app_omits_reason_reference_when_configured(
+ app_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ site_settings,
+):
+ # given - global reasonReference is always optional for apps
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ order = order_with_lines
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": 1,
+ "replace": False,
+ },
+ ],
+ "reason": "Return reason without reference",
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ ORDER_FULFILL_RETURN_MUTATION,
+ variables,
+ permissions=(permission_manage_orders,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ assert not data["errors"]
+
+ return_fulfillment = data["returnFulfillment"]
+ assert return_fulfillment["status"] == FulfillmentStatus.RETURNED.upper()
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products_reason.py b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products_reason.py
new file mode 100644
index 0000000000..6b7b6ce4a6
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products_reason.py
@@ -0,0 +1,727 @@
+from unittest.mock import patch
+
+import graphene
+
+from .....order.error_codes import OrderErrorCode
+from .....order.models import FulfillmentStatus
+from .....page.models import Page, PageType
+from .....payment import ChargeStatus
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+from .test_fulfillment_return_products import ORDER_FULFILL_RETURN_MUTATION
+
+ORDER_FULFILLMENT_REASONS_QUERY = """
+query Order($id: ID!) {
+ order(id: $id) {
+ fulfillments {
+ status
+ reason
+ reasonReference { id }
+ lines {
+ reason
+ reasonReference { id }
+ }
+ }
+ }
+}
+"""
+
+
+def test_fulfillment_return_products_with_global_reason_and_reason_reference(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ site_settings,
+):
+ # given
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ order = order_with_lines
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+ page_id = to_global_id_or_none(page)
+ reason = "Global return reason"
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": 1,
+ "replace": False,
+ },
+ ],
+ "reason": reason,
+ "reasonReference": page_id,
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ assert not data["errors"]
+
+ return_fulfillment = data["returnFulfillment"]
+ assert return_fulfillment["status"] == FulfillmentStatus.RETURNED.upper()
+ assert len(return_fulfillment["lines"]) == 1
+
+ order.refresh_from_db()
+ fulfillment = order.fulfillments.get(status=FulfillmentStatus.RETURNED)
+ assert fulfillment.reason == reason
+ assert fulfillment.reason_reference == page
+
+
+def test_fulfillment_return_products_staff_omits_reason_reference_when_configured(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ site_settings,
+):
+ # given - global reasonReference is required for staff when configured
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ order = order_with_lines
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": 1,
+ "replace": False,
+ },
+ ],
+ "reason": "Return reason without reference",
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "reasonReference"
+ assert errors[0]["code"] == OrderErrorCode.REQUIRED.name
+ assert (
+ errors[0]["message"]
+ == "Reason reference is required when reason reference type is configured."
+ )
+
+
+def test_fulfillment_return_products_with_per_line_reason(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ site_settings,
+):
+ # given
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ order = order_with_lines
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+ page_id = to_global_id_or_none(page)
+ line_reason = "Per-line reason"
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": 1,
+ "replace": False,
+ "reason": line_reason,
+ "reasonReference": page_id,
+ },
+ ],
+ "reasonReference": page_id,
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ fulfillment = order.fulfillments.get(status=FulfillmentStatus.RETURNED)
+ fulfillment_line = fulfillment.lines.first()
+ assert fulfillment_line.reason == line_reason
+ assert fulfillment_line.reason_reference == page
+
+
+def test_fulfillment_return_products_per_line_reason_reference_when_not_configured(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ site_settings,
+):
+ # given - no return_reason_reference_type configured; per-line ref is an error
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+
+ order = order_with_lines
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+ page_id = to_global_id_or_none(page)
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": 1,
+ "replace": False,
+ "reasonReference": page_id,
+ },
+ ],
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "reasonReference"
+ assert errors[0]["code"] == OrderErrorCode.INVALID.name
+ assert errors[0]["message"] == "Reason reference type is not configured."
+
+
+def test_fulfillment_return_products_per_line_reason_reference_wrong_page_type(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ site_settings,
+):
+ # given
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ wrong_page_type = PageType.objects.create(name="Blog Posts", slug="blog-posts")
+ wrong_page = Page.objects.create(
+ slug="blog-post",
+ title="Blog Post",
+ page_type=wrong_page_type,
+ is_published=True,
+ )
+ valid_page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ order = order_with_lines
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": 1,
+ "replace": False,
+ "reasonReference": to_global_id_or_none(wrong_page),
+ },
+ ],
+ "reasonReference": to_global_id_or_none(valid_page),
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "reasonReference"
+ assert errors[0]["code"] == OrderErrorCode.INVALID.name
+ assert (
+ errors[0]["message"]
+ == "Invalid reason reference. Must be an ID of a Model (Page)"
+ )
+
+
+def test_fulfillment_return_products_reason_fields_resolve(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ site_settings,
+):
+ # given - return with a global reason and a per-line reason/reasonReference
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ order = order_with_lines
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+ page_id = to_global_id_or_none(page)
+ global_reason = "Global return reason"
+ line_reason = "Per-line reason"
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ return_response = staff_api_client.post_graphql(
+ ORDER_FULFILL_RETURN_MUTATION,
+ {
+ "order": order_id,
+ "input": {
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": 1,
+ "replace": False,
+ "reason": line_reason,
+ "reasonReference": page_id,
+ },
+ ],
+ "reason": global_reason,
+ "reasonReference": page_id,
+ },
+ },
+ )
+ assert not get_graphql_content(return_response)["data"][
+ "orderFulfillmentReturnProducts"
+ ]["errors"]
+
+ # when - the reason fields are resolved through GraphQL
+ response = staff_api_client.post_graphql(
+ ORDER_FULFILLMENT_REASONS_QUERY, {"id": order_id}
+ )
+
+ # then
+ content = get_graphql_content(response)
+ fulfillments = content["data"]["order"]["fulfillments"]
+ returned = next(
+ f for f in fulfillments if f["status"] == FulfillmentStatus.RETURNED.upper()
+ )
+ assert returned["reason"] == global_reason
+ assert returned["reasonReference"]["id"] == page_id
+ returned_line = returned["lines"][0]
+ assert returned_line["reason"] == line_reason
+ assert returned_line["reasonReference"]["id"] == page_id
+
+
+def test_fulfillment_return_products_fulfillment_lines_with_global_and_per_line_reasons(
+ staff_api_client,
+ permission_group_manage_orders,
+ fulfilled_order,
+ site_settings,
+):
+ # given - a return via fulfillmentLines with a global reason and distinct
+ # per-line reasons on each fulfillment line
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ global_page = Page.objects.create(
+ slug="customer-return",
+ title="Customer return",
+ page_type=page_type,
+ is_published=True,
+ )
+ line_page_1 = Page.objects.create(
+ slug="damaged", title="Damaged", page_type=page_type, is_published=True
+ )
+ line_page_2 = Page.objects.create(
+ slug="wrong-size", title="Wrong size", page_type=page_type, is_published=True
+ )
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ order = fulfilled_order
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ fulfillment = order.fulfillments.first()
+ line_1 = fulfillment.lines.first()
+ line_2 = fulfillment.lines.last()
+ global_reason = "Customer return request"
+ line_1_reason = "Item arrived damaged"
+ line_2_reason = "Wrong size"
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": False,
+ "fulfillmentLines": [
+ {
+ "fulfillmentLineId": to_global_id_or_none(line_1),
+ "quantity": 1,
+ "replace": False,
+ "reason": line_1_reason,
+ "reasonReference": to_global_id_or_none(line_page_1),
+ },
+ {
+ "fulfillmentLineId": to_global_id_or_none(line_2),
+ "quantity": 1,
+ "replace": False,
+ "reason": line_2_reason,
+ "reasonReference": to_global_id_or_none(line_page_2),
+ },
+ ],
+ "reason": global_reason,
+ "reasonReference": to_global_id_or_none(global_page),
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ return_fulfillment = order.fulfillments.get(status=FulfillmentStatus.RETURNED)
+ assert return_fulfillment.reason == global_reason
+ assert return_fulfillment.reason_reference == global_page
+
+ lines_by_order_line = {
+ line.order_line_id: line for line in return_fulfillment.lines.all()
+ }
+ returned_line_1 = lines_by_order_line[line_1.order_line_id]
+ returned_line_2 = lines_by_order_line[line_2.order_line_id]
+ assert returned_line_1.reason == line_1_reason
+ assert returned_line_1.reason_reference == line_page_1
+ assert returned_line_2.reason == line_2_reason
+ assert returned_line_2.reason_reference == line_page_2
+
+
+def test_fulfillment_return_products_fulfillment_lines_mixed_per_line_reason(
+ staff_api_client,
+ permission_group_manage_orders,
+ fulfilled_order,
+ site_settings,
+):
+ # given - global reasonReference set; only one fulfillment line has a per-line
+ # reference. The other line must store null (no inheritance from the global one).
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ global_page = Page.objects.create(
+ slug="customer-return",
+ title="Customer return",
+ page_type=page_type,
+ is_published=True,
+ )
+ line_page = Page.objects.create(
+ slug="damaged", title="Damaged", page_type=page_type, is_published=True
+ )
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ order = fulfilled_order
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ fulfillment = order.fulfillments.first()
+ line_with_reason = fulfillment.lines.first()
+ line_without_reason = fulfillment.lines.last()
+ line_reason = "Damaged"
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": False,
+ "fulfillmentLines": [
+ {
+ "fulfillmentLineId": to_global_id_or_none(line_with_reason),
+ "quantity": 1,
+ "replace": False,
+ "reason": line_reason,
+ "reasonReference": to_global_id_or_none(line_page),
+ },
+ {
+ "fulfillmentLineId": to_global_id_or_none(line_without_reason),
+ "quantity": 1,
+ "replace": False,
+ },
+ ],
+ "reasonReference": to_global_id_or_none(global_page),
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ return_fulfillment = order.fulfillments.get(status=FulfillmentStatus.RETURNED)
+ assert return_fulfillment.reason_reference == global_page
+
+ lines_by_order_line = {
+ line.order_line_id: line for line in return_fulfillment.lines.all()
+ }
+ assert (
+ lines_by_order_line[line_with_reason.order_line_id].reason_reference
+ == line_page
+ )
+ assert (
+ lines_by_order_line[line_without_reason.order_line_id].reason_reference is None
+ )
+
+
+def test_fulfillment_return_products_refund_requires_reason_reference_for_staff(
+ staff_api_client,
+ permission_group_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+ site_settings,
+):
+ # given - refund=true uses the same validation as refund=false: staff must
+ # provide the global reasonReference when the type is configured
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ payment_dummy.total = fulfilled_order.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfilled_order.payments.add(payment_dummy)
+
+ order = fulfilled_order
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ fulfillment_line = order.fulfillments.first().lines.first()
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "fulfillmentLines": [
+ {
+ "fulfillmentLineId": to_global_id_or_none(fulfillment_line),
+ "quantity": 1,
+ "replace": False,
+ },
+ ],
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "reasonReference"
+ assert errors[0]["code"] == OrderErrorCode.REQUIRED.name
+ assert not order.fulfillments.filter(
+ status__in=[
+ FulfillmentStatus.RETURNED,
+ FulfillmentStatus.REFUNDED_AND_RETURNED,
+ ]
+ ).exists()
+
+
+@patch("saleor.payment.gateway.refund")
+def test_fulfillment_return_products_refund_stores_reason_reference(
+ mocked_refund,
+ staff_api_client,
+ permission_group_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+ site_settings,
+):
+ # given - refund=true with a valid global reasonReference stores the reference
+ # on the resulting fulfillment, same as refund=false
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ page = Page.objects.create(
+ slug="customer-return",
+ title="Customer return",
+ page_type=page_type,
+ is_published=True,
+ )
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ payment_dummy.total = fulfilled_order.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfilled_order.payments.add(payment_dummy)
+
+ order = fulfilled_order
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ fulfillment_line = order.fulfillments.first().lines.first()
+ global_reason = "Customer return request"
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "fulfillmentLines": [
+ {
+ "fulfillmentLineId": to_global_id_or_none(fulfillment_line),
+ "quantity": 1,
+ "replace": False,
+ },
+ ],
+ "reason": global_reason,
+ "reasonReference": to_global_id_or_none(page),
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ assert not data["errors"]
+ mocked_refund.assert_called_once()
+
+ order.refresh_from_db()
+ return_fulfillment = order.fulfillments.get(
+ status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ assert return_fulfillment.reason == global_reason
+ assert return_fulfillment.reason_reference == page
+
+
+def test_fulfillment_return_products_replace_with_per_line_reasons(
+ staff_api_client,
+ permission_group_manage_orders,
+ fulfilled_order,
+ site_settings,
+):
+ # given - one line is replaced and one is returned, each with its own
+ # per-line reasonReference (refund disabled)
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ replace_page = Page.objects.create(
+ slug="damaged", title="Damaged", page_type=page_type, is_published=True
+ )
+ return_page = Page.objects.create(
+ slug="wrong-size", title="Wrong size", page_type=page_type, is_published=True
+ )
+ global_page = Page.objects.create(
+ slug="customer-return",
+ title="Customer return",
+ page_type=page_type,
+ is_published=True,
+ )
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save(update_fields=["return_reason_reference_type"])
+
+ order = fulfilled_order
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ fulfillment = order.fulfillments.first()
+ line_to_replace = fulfillment.lines.first()
+ line_to_return = fulfillment.lines.last()
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": False,
+ "fulfillmentLines": [
+ {
+ "fulfillmentLineId": to_global_id_or_none(line_to_replace),
+ "quantity": 1,
+ "replace": True,
+ "reason": "Damaged",
+ "reasonReference": to_global_id_or_none(replace_page),
+ },
+ {
+ "fulfillmentLineId": to_global_id_or_none(line_to_return),
+ "quantity": 1,
+ "replace": False,
+ "reason": "Wrong size",
+ "reasonReference": to_global_id_or_none(return_page),
+ },
+ ],
+ "reasonReference": to_global_id_or_none(global_page),
+ },
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ assert not data["errors"]
+ assert data["replaceFulfillment"]["status"] == FulfillmentStatus.REPLACED.upper()
+ assert data["returnFulfillment"]["status"] == FulfillmentStatus.RETURNED.upper()
+ assert data["replaceOrder"]
+
+ order.refresh_from_db()
+ replace_fulfillment = order.fulfillments.get(status=FulfillmentStatus.REPLACED)
+ assert replace_fulfillment.reason_reference == global_page
+ replaced_line = replace_fulfillment.lines.get(
+ order_line_id=line_to_replace.order_line_id
+ )
+ assert replaced_line.reason_reference == replace_page
+
+ return_fulfillment = order.fulfillments.get(status=FulfillmentStatus.RETURNED)
+ assert return_fulfillment.reason_reference == global_page
+ returned_line = return_fulfillment.lines.get(
+ order_line_id=line_to_return.order_line_id
+ )
+ assert returned_line.reason_reference == return_page
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 3de91f7895..59edf1ebf3 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,7 +5,6 @@ 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,
@@ -1151,488 +1150,3 @@ 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_create_line_reason.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create_line_reason.py
new file mode 100644
index 0000000000..047255b2d4
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create_line_reason.py
@@ -0,0 +1,407 @@
+from decimal import Decimal
+
+import graphene
+
+from .....page.models import Page, PageType
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+from ...enums import (
+ OrderGrantRefundCreateErrorCode,
+ OrderGrantRefundCreateLineErrorCode,
+)
+
+ORDER_GRANT_REFUND_CREATE = """
+mutation OrderGrantRefundCreate(
+ $id: ID!, $input: OrderGrantRefundCreateInput!
+){
+ orderGrantRefundCreate(id: $id, input:$input){
+ grantedRefund{
+ id
+ amount{
+ amount
+ }
+ reason
+ reasonReference { id }
+ lines{
+ id
+ orderLine{
+ id
+ }
+ quantity
+ reason
+ reasonReference { id }
+ }
+ }
+ errors{
+ field
+ code
+ message
+ lines{
+ field
+ code
+ lineId
+ message
+ }
+ }
+ }
+}
+"""
+
+
+def test_with_per_line_reason_reference(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ order = order_with_lines
+ 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)
+
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ 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,
+ "transactionId": transaction_item_id,
+ "reasonReference": page_id,
+ "lines": [
+ {
+ "id": line_id,
+ "quantity": 1,
+ "reason": "Line damaged",
+ "reasonReference": page_id,
+ }
+ ],
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ assert not data["errors"]
+
+ granted_refund = data["grantedRefund"]
+ assert len(granted_refund["lines"]) == 1
+
+ refund_line = granted_refund["lines"][0]
+ assert refund_line["reason"] == "Line damaged"
+ assert refund_line["reasonReference"]["id"] == page_id
+
+ granted_refund_line_from_db = order.granted_refunds.first().lines.first()
+ assert granted_refund_line_from_db.reason_reference == page
+
+
+def test_with_per_line_reason_reference_multiple_lines(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ order = order_with_lines
+ page_type = PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+ page1 = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+ page2 = Page.objects.create(
+ slug="wrong-size",
+ title="Wrong Size",
+ 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)
+ page1_id = to_global_id_or_none(page1)
+ page2_id = to_global_id_or_none(page2)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ lines = order.lines.all()
+ line1_id = graphene.Node.to_global_id("OrderLine", lines[0].pk)
+ line2_id = graphene.Node.to_global_id("OrderLine", lines[1].pk)
+
+ amount = Decimal("20.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,
+ "transactionId": transaction_item_id,
+ "reasonReference": page1_id,
+ "lines": [
+ {
+ "id": line1_id,
+ "quantity": 1,
+ "reason": "Damaged",
+ "reasonReference": page1_id,
+ },
+ {
+ "id": line2_id,
+ "quantity": 1,
+ "reason": "Wrong size",
+ "reasonReference": page2_id,
+ },
+ ],
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ assert not data["errors"]
+
+ granted_refund = data["grantedRefund"]
+ assert len(granted_refund["lines"]) == 2
+
+ lines_by_reason = {line["reason"]: line for line in granted_refund["lines"]}
+ assert lines_by_reason["Damaged"]["reasonReference"]["id"] == page1_id
+ assert lines_by_reason["Wrong size"]["reasonReference"]["id"] == page2_id
+
+
+def test_with_per_line_reason_reference_no_config_rejects(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given - refund_reason_reference_type is NOT configured
+ order = order_with_lines
+ 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)
+
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ 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,
+ "transactionId": transaction_item_id,
+ "lines": [
+ {
+ "id": line_id,
+ "quantity": 1,
+ "reason": "Damaged",
+ "reasonReference": page_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
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["code"] == OrderGrantRefundCreateErrorCode.INVALID.name
+ line_errors = errors[0]["lines"]
+ assert len(line_errors) == 1
+ assert line_errors[0]["field"] == "reason_reference"
+ assert line_errors[0]["lineId"] == line_id
+ assert (
+ line_errors[0]["code"]
+ == OrderGrantRefundCreateLineErrorCode.NOT_CONFIGURED.name
+ )
+ assert line_errors[0]["message"] == "Reason reference type is not configured."
+
+
+def test_with_per_line_reason_reference_wrong_page_type(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ order = order_with_lines
+ page_type_configured = PageType.objects.create(
+ name="Refund Reasons", slug="refund-reasons"
+ )
+ page_type_other = PageType.objects.create(name="Other Type", slug="other-type")
+ page_wrong_type = Page.objects.create(
+ slug="wrong-type-page",
+ title="Wrong Type Page",
+ page_type=page_type_other,
+ is_published=True,
+ )
+
+ site_settings.refund_reason_reference_type = page_type_configured
+ 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_wrong_type)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ # Need a valid top-level reasonReference too
+ page_correct = Page.objects.create(
+ slug="correct-page",
+ title="Correct Page",
+ page_type=page_type_configured,
+ is_published=True,
+ )
+ correct_page_id = to_global_id_or_none(page_correct)
+
+ 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,
+ "transactionId": transaction_item_id,
+ "reasonReference": correct_page_id,
+ "lines": [
+ {
+ "id": line_id,
+ "quantity": 1,
+ "reason": "Damaged",
+ "reasonReference": page_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
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["code"] == OrderGrantRefundCreateErrorCode.INVALID.name
+ line_errors = errors[0]["lines"]
+ assert len(line_errors) == 1
+ assert line_errors[0]["field"] == "reason_reference"
+ assert line_errors[0]["lineId"] == line_id
+ assert line_errors[0]["code"] == OrderGrantRefundCreateLineErrorCode.INVALID.name
+ assert line_errors[0]["message"] == "Invalid reason reference."
+
+
+def test_line_without_reason_reference_when_not_configured(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given - no refund_reason_reference_type configured, no reason_reference on line
+ order = order_with_lines
+ assert site_settings.refund_reason_reference_type is None
+
+ order_id = to_global_id_or_none(order)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ 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,
+ "transactionId": transaction_item_id,
+ "lines": [
+ {
+ "id": line_id,
+ "quantity": 1,
+ "reason": "Damaged",
+ }
+ ],
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ assert not data["errors"]
+
+ refund_line = data["grantedRefund"]["lines"][0]
+ assert refund_line["reason"] == "Damaged"
+ assert refund_line["reasonReference"] is None
diff --git a/saleor/graphql/order/tests/mutations/test_order_grant_refund_create_reason.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create_reason.py
new file mode 100644
index 0000000000..9b1d0390f6
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create_reason.py
@@ -0,0 +1,581 @@
+from decimal import Decimal
+
+import graphene
+
+from .....page.models import Page, PageType
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import (
+ get_graphql_content,
+)
+from ...enums import (
+ OrderGrantRefundCreateErrorCode,
+)
+
+ORDER_GRANT_REFUND_CREATE = """
+mutation OrderGrantRefundCreate(
+ $id: ID!, $input: OrderGrantRefundCreateInput!
+){
+ orderGrantRefundCreate(id: $id, input:$input){
+ grantedRefund{
+ id
+ createdAt
+ updatedAt
+ amount{
+ amount
+ }
+ reason
+ reasonReference { id }
+ user{
+ id
+ }
+ app{
+ id
+ }
+ shippingCostsIncluded
+ lines{
+ id
+ orderLine{
+ id
+ }
+ quantity
+ reason
+ }
+ status
+ transactionEvents{
+ id
+ }
+ transaction{
+ id
+ }
+ }
+ order{
+ id
+ chargeStatus
+ grantedRefunds{
+ id
+ amount{
+ amount
+ }
+ createdAt
+ updatedAt
+ reason
+ reasonReference { id }
+ app{
+ id
+ }
+ user{
+ id
+ }
+ shippingCostsIncluded
+ lines{
+ id
+ orderLine{
+ id
+ }
+ quantity
+ reason
+ }
+ status
+ transactionEvents{
+ id
+ }
+ transaction{
+ id
+ }
+ }
+ }
+ errors{
+ field
+ code
+ lines{
+ field
+ code
+ lineId
+ message
+ }
+ }
+ }
+}
+"""
+
+
+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 4d6405a5bb..ddda61c70e 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,7 +6,6 @@ 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,
@@ -2258,632 +2257,3 @@ def test_granted_refund_update_when_status_allows_update(
) == quantize_price(
Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency
)
-
-
- "granted_refund_status",
- [OrderGrantedRefundStatus.SUCCESS, OrderGrantedRefundStatus.PENDING],
-)
-def test_granted_refund_updated_when_status_blocks_action_and_only_reason_provided(
- granted_refund_status,
- app_api_client,
- staff_user,
- permission_manage_orders,
- order_with_lines,
- transaction_item_generator,
-):
- # given
- max_granted_charged_value = Decimal("1.00")
- transaction_item = transaction_item_generator(
- order_id=order_with_lines.id, charged_value=max_granted_charged_value
- )
- current_reason = "Granted refund reason."
- current_amount = Decimal("0.50")
- granted_refund = order_with_lines.granted_refunds.create(
- amount_value=current_amount,
- currency=order_with_lines.currency,
- reason=current_reason,
- user=staff_user,
- status=granted_refund_status,
- transaction_item=transaction_item,
- )
- granted_refund_id = to_global_id_or_none(granted_refund)
-
- app_api_client.app.permissions.set([permission_manage_orders])
-
- expected_reason = "New reason"
- variables = {
- "id": granted_refund_id,
- "input": {"reason": expected_reason},
- }
-
- # when
- response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
-
- # then
- granted_refund.refresh_from_db()
- content = get_graphql_content(response)
- data = content["data"]["orderGrantRefundUpdate"]
-
- assert not data["errors"]
-
- assert len(data["order"]["grantedRefunds"]) == 1
- granted_refund_data = data["order"]["grantedRefunds"][0]
-
- 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/tests/mutations/test_order_grant_refund_update_line_reason.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update_line_reason.py
new file mode 100644
index 0000000000..dbc109e374
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update_line_reason.py
@@ -0,0 +1,285 @@
+from decimal import Decimal
+
+import graphene
+
+from .....page.models import Page, PageType
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+from ...enums import (
+ OrderGrantRefundUpdateErrorCode,
+ OrderGrantRefundUpdateLineErrorCode,
+)
+
+ORDER_GRANT_REFUND_UPDATE = """
+mutation OrderGrantRefundUpdate(
+ $id: ID!, $input: OrderGrantRefundUpdateInput!
+){
+ orderGrantRefundUpdate(id: $id, input:$input) {
+ grantedRefund {
+ id
+ amount {
+ amount
+ }
+ reason
+ reasonReference { id }
+ lines{
+ id
+ orderLine{
+ id
+ }
+ quantity
+ reason
+ reasonReference { id }
+ }
+ }
+ errors{
+ field
+ code
+ message
+ addLines{
+ field
+ code
+ lineId
+ message
+ }
+ }
+ }
+}
+"""
+
+
+def test_add_line_with_reason_reference(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ order = order_with_lines
+ 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"])
+
+ 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
+ )
+
+ granted_refund = order.granted_refunds.create(
+ amount_value=amount,
+ currency=order.currency,
+ reason="Original reason",
+ reason_reference=page,
+ user=staff_api_client.user,
+ transaction_item=transaction_item,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ page_id = to_global_id_or_none(page)
+
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "reasonReference": page_id,
+ "addLines": [
+ {
+ "id": line_id,
+ "quantity": 1,
+ "reason": "Line damaged",
+ "reasonReference": page_id,
+ }
+ ],
+ },
+ }
+
+ # When
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # Then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ assert not data["errors"]
+
+ granted_refund_data = data["grantedRefund"]
+ assert len(granted_refund_data["lines"]) == 1
+
+ refund_line = granted_refund_data["lines"][0]
+ assert refund_line["reason"] == "Line damaged"
+ assert refund_line["reasonReference"]["id"] == page_id
+
+ refund_line_from_db = granted_refund.lines.first()
+ assert refund_line_from_db.reason_reference == page
+
+
+def test_add_line_with_reason_reference_wrong_page_type(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given
+ order = order_with_lines
+ page_type_configured = PageType.objects.create(
+ name="Refund Reasons", slug="refund-reasons"
+ )
+ page_correct = Page.objects.create(
+ slug="correct-page",
+ title="Correct Page",
+ page_type=page_type_configured,
+ is_published=True,
+ )
+
+ page_type_other = PageType.objects.create(name="Other Type", slug="other-type")
+ page_wrong = Page.objects.create(
+ slug="wrong-page",
+ title="Wrong Page",
+ page_type=page_type_other,
+ is_published=True,
+ )
+
+ site_settings.refund_reason_reference_type = page_type_configured
+ site_settings.save(update_fields=["refund_reason_reference_type"])
+
+ 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
+ )
+
+ granted_refund = order.granted_refunds.create(
+ amount_value=amount,
+ currency=order.currency,
+ reason="Original reason",
+ reason_reference=page_correct,
+ user=staff_api_client.user,
+ transaction_item=transaction_item,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ correct_page_id = to_global_id_or_none(page_correct)
+ wrong_page_id = to_global_id_or_none(page_wrong)
+
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "reasonReference": correct_page_id,
+ "addLines": [
+ {
+ "id": line_id,
+ "quantity": 1,
+ "reason": "Line damaged",
+ "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
+ assert errors[0]["field"] == "addLines"
+ assert errors[0]["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name
+ line_errors = errors[0]["addLines"]
+ assert len(line_errors) == 1
+ assert line_errors[0]["field"] == "reason_reference"
+ assert line_errors[0]["lineId"] == line_id
+ assert line_errors[0]["code"] == OrderGrantRefundUpdateLineErrorCode.INVALID.name
+ assert line_errors[0]["message"] == "Invalid reason reference."
+
+
+def test_add_line_with_reason_reference_not_configured(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+ site_settings,
+):
+ # Given - refund_reason_reference_type is NOT configured
+ order = order_with_lines
+ 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
+
+ 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
+ )
+
+ granted_refund = order.granted_refunds.create(
+ amount_value=amount,
+ currency=order.currency,
+ reason="Original reason",
+ user=staff_api_client.user,
+ transaction_item=transaction_item,
+ )
+
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ page_id = to_global_id_or_none(page)
+
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.pk)
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "addLines": [
+ {
+ "id": line_id,
+ "quantity": 1,
+ "reason": "Damaged",
+ "reasonReference": 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
+ assert errors[0]["field"] == "addLines"
+ assert errors[0]["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name
+ line_errors = errors[0]["addLines"]
+ assert len(line_errors) == 1
+ assert line_errors[0]["field"] == "reason_reference"
+ assert line_errors[0]["lineId"] == line_id
+ assert (
+ line_errors[0]["code"]
+ == OrderGrantRefundUpdateLineErrorCode.NOT_CONFIGURED.name
+ )
+ assert line_errors[0]["message"] == "Reason reference type is not configured."
diff --git a/saleor/graphql/order/tests/mutations/test_order_grant_refund_update_reason.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update_reason.py
new file mode 100644
index 0000000000..1788fddeff
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update_reason.py
@@ -0,0 +1,737 @@
+from decimal import Decimal
+
+import graphene
+import pytest
+
+from .....order import OrderGrantedRefundStatus
+from .....page.models import Page, PageType
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import (
+ get_graphql_content,
+)
+from ...enums import (
+ OrderGrantRefundUpdateErrorCode,
+)
+
+ORDER_GRANT_REFUND_UPDATE = """
+mutation OrderGrantRefundUpdate(
+ $id: ID!, $input: OrderGrantRefundUpdateInput!
+){
+ orderGrantRefundUpdate(id: $id, input:$input) {
+ grantedRefund {
+ id
+ createdAt
+ updatedAt
+ amount {
+ amount
+ }
+ reason
+ reasonReference { id }
+ user {
+ id
+ }
+ app {
+ id
+ }
+ shippingCostsIncluded
+ lines{
+ id
+ orderLine{
+ id
+ }
+ quantity
+ reason
+ }
+ status
+ transactionEvents{
+ id
+ }
+ transaction{
+ id
+ }
+ }
+ order {
+ id
+ grantedRefunds{
+ id
+ amount{
+ amount
+ }
+ createdAt
+ updatedAt
+ reason
+ reasonReference { id }
+ app{
+ id
+ }
+ user{
+ id
+ }
+ shippingCostsIncluded
+ lines{
+ id
+ orderLine{
+ id
+ }
+ quantity
+ reason
+ }
+ status
+ transactionEvents{
+ id
+ }
+ transaction{
+ id
+ }
+ }
+ }
+ errors {
+ field
+ code
+ message
+ addLines{
+ field
+ code
+ lineId
+ message
+ }
+ removeLines{
+ field
+ code
+ lineId
+ message
+ }
+ }
+ }
+}
+
+"""
+
+
+ "granted_refund_status",
+ [OrderGrantedRefundStatus.SUCCESS, OrderGrantedRefundStatus.PENDING],
+)
+def test_granted_refund_updated_when_status_blocks_action_and_only_reason_provided(
+ granted_refund_status,
+ app_api_client,
+ staff_user,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+):
+ # given
+ max_granted_charged_value = Decimal("1.00")
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.id, charged_value=max_granted_charged_value
+ )
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("0.50")
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order_with_lines.currency,
+ reason=current_reason,
+ user=staff_user,
+ status=granted_refund_status,
+ transaction_item=transaction_item,
+ )
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ expected_reason = "New reason"
+ variables = {
+ "id": granted_refund_id,
+ "input": {"reason": expected_reason},
+ }
+
+ # when
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ granted_refund.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+
+ assert not data["errors"]
+
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund_data = data["order"]["grantedRefunds"][0]
+
+ 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/tests/mutations/test_order_grant_refund_utils.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_utils.py
new file mode 100644
index 0000000000..a98379720c
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_utils.py
@@ -0,0 +1,294 @@
+import graphene
+import pytest
+from django.core.exceptions import ValidationError
+
+from .....order.error_codes import OrderGrantRefundCreateLineErrorCode
+from .....page.models import Page, PageType
+from ....core.utils import to_global_id_or_none
+from ...enums import OrderGrantRefundCreateErrorCode
+from ...mutations.order_grant_refund_utils import (
+ resolve_reason_reference_page,
+ validate_reason_references,
+)
+
+
+def refund_page_type(db):
+ return PageType.objects.create(name="Refund Reasons", slug="refund-reasons")
+
+
+def refund_page(refund_page_type):
+ return Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=refund_page_type,
+ is_published=True,
+ )
+
+
+def test_resolves_valid_page(refund_page_type, refund_page):
+ # Given
+ page_id = to_global_id_or_none(refund_page)
+
+ # When
+ result = resolve_reason_reference_page(
+ page_id, refund_page_type, OrderGrantRefundCreateErrorCode
+ )
+
+ # Then
+ assert result == refund_page
+
+
+def test_raises_graphql_error_for_wrong_type_id(refund_page_type):
+ # Given
+ invalid_id = graphene.Node.to_global_id("Product", 12345)
+
+ # When / Then
+ with pytest.raises(ValidationError) as exc_info:
+ resolve_reason_reference_page(
+ invalid_id, refund_page_type, OrderGrantRefundCreateErrorCode
+ )
+ error = exc_info.value.error_dict["reason_reference"][0]
+ assert error.code == OrderGrantRefundCreateErrorCode.GRAPHQL_ERROR.value
+
+
+def test_raises_invalid_for_wrong_page_type(refund_page_type):
+ # Given
+ other_type = PageType.objects.create(name="Other", slug="other")
+ page = Page.objects.create(
+ slug="other-page",
+ title="Other Page",
+ page_type=other_type,
+ is_published=True,
+ )
+ page_id = to_global_id_or_none(page)
+
+ # When / Then
+ with pytest.raises(ValidationError) as exc_info:
+ resolve_reason_reference_page(
+ page_id, refund_page_type, OrderGrantRefundCreateErrorCode
+ )
+ error = exc_info.value.error_dict["reason_reference"][0]
+ assert error.code == OrderGrantRefundCreateErrorCode.INVALID.value
+ assert error.message == (
+ "Invalid reason reference. Must be an ID of a Model (Page)"
+ )
+
+
+def test_raises_invalid_for_nonexistent_page(refund_page_type):
+ # Given
+ page_id = graphene.Node.to_global_id("Page", 99999)
+
+ # When / Then
+ with pytest.raises(ValidationError) as exc_info:
+ resolve_reason_reference_page(
+ page_id, refund_page_type, OrderGrantRefundCreateErrorCode
+ )
+ error = exc_info.value.error_dict["reason_reference"][0]
+ assert error.code == OrderGrantRefundCreateErrorCode.INVALID.value
+ assert error.message == (
+ "Invalid reason reference. Must be an ID of a Model (Page)"
+ )
+
+
+def test_validate_reason_references_resolves_valid_page(
+ refund_page_type, refund_page, order_with_lines
+):
+ # Given
+ order_line = order_with_lines.lines.first()
+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.pk)
+ page_id = to_global_id_or_none(refund_page)
+ lines = [
+ {
+ "id": order_line_id,
+ "quantity": 1,
+ "reason": "Damaged",
+ "reason_reference": page_id,
+ }
+ ]
+ errors: list = []
+
+ # When
+ result = validate_reason_references(
+ lines=lines,
+ refund_reason_reference_type_pk=refund_page_type.pk,
+ errors=errors,
+ line_error_code_enum=OrderGrantRefundCreateLineErrorCode,
+ )
+
+ # Then
+ assert not errors
+ assert result == {page_id: refund_page.pk}
+
+
+def test_validate_reason_references_skips_lines_without_reference(
+ refund_page_type, order_with_lines
+):
+ # Given
+ order_line = order_with_lines.lines.first()
+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.pk)
+ lines = [{"id": order_line_id, "quantity": 1, "reason": "Damaged"}]
+ errors: list = []
+
+ # When
+ result = validate_reason_references(
+ lines=lines,
+ refund_reason_reference_type_pk=refund_page_type.pk,
+ errors=errors,
+ line_error_code_enum=OrderGrantRefundCreateLineErrorCode,
+ )
+
+ # Then
+ assert not errors
+ assert result == {}
+
+
+def test_validate_reason_references_reports_not_configured_per_line(
+ page, order_with_lines
+):
+ # Given
+ order_line = order_with_lines.lines.first()
+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.pk)
+ page_id = to_global_id_or_none(page)
+ lines = [
+ {
+ "id": order_line_id,
+ "quantity": 1,
+ "reason": "Damaged",
+ "reason_reference": page_id,
+ }
+ ]
+ errors: list = []
+
+ # When
+ validate_reason_references(
+ lines=lines,
+ refund_reason_reference_type_pk=None,
+ errors=errors,
+ line_error_code_enum=OrderGrantRefundCreateLineErrorCode,
+ )
+
+ # Then
+ assert len(errors) == 1
+ line_error = errors[0]
+ assert (
+ line_error["code"] == OrderGrantRefundCreateLineErrorCode.NOT_CONFIGURED.value
+ )
+ assert line_error["message"] == "Reason reference type is not configured."
+ assert line_error["line_id"] == order_line_id
+
+
+def test_validate_reason_references_reports_invalid_per_line(
+ refund_page_type, order_with_lines
+):
+ # Given
+ other_type = PageType.objects.create(name="Other", slug="other")
+ page = Page.objects.create(
+ slug="wrong-page",
+ title="Wrong Page",
+ page_type=other_type,
+ is_published=True,
+ )
+ order_line = order_with_lines.lines.first()
+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.pk)
+ page_id = to_global_id_or_none(page)
+ lines = [
+ {
+ "id": order_line_id,
+ "quantity": 1,
+ "reason": "Damaged",
+ "reason_reference": page_id,
+ }
+ ]
+ errors: list = []
+
+ # When
+ validate_reason_references(
+ lines=lines,
+ refund_reason_reference_type_pk=refund_page_type.pk,
+ errors=errors,
+ line_error_code_enum=OrderGrantRefundCreateLineErrorCode,
+ )
+
+ # Then
+ assert len(errors) == 1
+ line_error = errors[0]
+ assert line_error["code"] == OrderGrantRefundCreateLineErrorCode.INVALID.value
+ assert line_error["message"] == "Invalid reason reference."
+ assert line_error["line_id"] == order_line_id
+
+
+def test_validate_reason_references_reports_graphql_error_per_line(
+ refund_page_type, order_with_lines
+):
+ # Given
+ order_line = order_with_lines.lines.first()
+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.pk)
+ invalid_id = graphene.Node.to_global_id("Product", 12345)
+ lines = [
+ {
+ "id": order_line_id,
+ "quantity": 1,
+ "reason": "Damaged",
+ "reason_reference": invalid_id,
+ }
+ ]
+ errors: list = []
+
+ # When
+ validate_reason_references(
+ lines=lines,
+ refund_reason_reference_type_pk=refund_page_type.pk,
+ errors=errors,
+ line_error_code_enum=OrderGrantRefundCreateLineErrorCode,
+ )
+
+ # Then
+ assert len(errors) == 1
+ line_error = errors[0]
+ assert line_error["code"] == OrderGrantRefundCreateLineErrorCode.GRAPHQL_ERROR.value
+ assert line_error["message"] == (
+ f"Invalid ID: {invalid_id}. Expected: Page, received: Product."
+ )
+ assert line_error["line_id"] == order_line_id
+
+
+def test_validate_reason_references_batches_db_queries(
+ refund_page_type, order_with_lines, django_assert_num_queries
+):
+ # Given
+ page1 = Page.objects.create(
+ slug="reason-1",
+ title="Reason 1",
+ page_type=refund_page_type,
+ is_published=True,
+ )
+ page2 = Page.objects.create(
+ slug="reason-2",
+ title="Reason 2",
+ page_type=refund_page_type,
+ is_published=True,
+ )
+ lines_qs = order_with_lines.lines.all()
+ line1_id = graphene.Node.to_global_id("OrderLine", lines_qs[0].pk)
+ line2_id = graphene.Node.to_global_id("OrderLine", lines_qs[1].pk)
+ page1_id = to_global_id_or_none(page1)
+ page2_id = to_global_id_or_none(page2)
+ lines = [
+ {"id": line1_id, "quantity": 1, "reason_reference": page1_id},
+ {"id": line2_id, "quantity": 1, "reason_reference": page2_id},
+ ]
+ errors: list = []
+
+ # When / Then — only 1 DB query regardless of number of lines
+ with django_assert_num_queries(1):
+ result = validate_reason_references(
+ lines=lines,
+ refund_reason_reference_type_pk=refund_page_type.pk,
+ errors=errors,
+ line_error_code_enum=OrderGrantRefundCreateLineErrorCode,
+ )
+
+ assert not errors
+ assert result == {page1_id: page1.pk, page2_id: page2.pk}
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 3daa67adaa..c320061658 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -80,6 +80,7 @@ from ..core.descriptions import (
ADDED_IN_320,
ADDED_IN_321,
ADDED_IN_322,
+ ADDED_IN_323,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
)
@@ -153,6 +154,7 @@ from ..tax.types import TaxClass
from ..warehouse.types import Allocation, Stock, Warehouse
from .dataloaders import (
AllocationsByOrderLineIdLoader,
+ FulfillmentByIdLoader,
FulfillmentLinesByFulfillmentIdLoader,
FulfillmentLinesByIdLoader,
FulfillmentsByOrderIdLoader,
@@ -160,6 +162,7 @@ from .dataloaders import (
OrderByNumberLoader,
OrderEventsByIdLoader,
OrderEventsByOrderIdLoader,
+ OrderGrantedRefundByIdLoader,
OrderGrantedRefundLinesByOrderGrantedRefundIdLoader,
OrderGrantedRefundsByOrderIdLoader,
OrderLineByIdLoader,
@@ -250,6 +253,12 @@ class OrderGrantedRefundLine(
required=True,
)
reason = graphene.String(description="Reason for refunding the line.")
+ reason_reference = graphene.Field(
+ Page,
+ required=False,
+ description="Reason Model (Page) reference for this refund line."
+ + ADDED_IN_323,
+ )
class Meta:
default_resolver = (
@@ -273,6 +282,40 @@ class OrderGrantedRefundLine(
.then(_wrap_with_sync_webhook_control_context)
)
+ @staticmethod
+ def resolve_reason_reference(
+ root: SyncWebhookControlContext[models.OrderGrantedRefundLine], info
+ ):
+ if not root.node.reason_reference_id:
+ return None
+
+ def wrap_page_with_context(page):
+ if not page:
+ return None
+
+ def _wrap_with_channel(granted_refund):
+ return (
+ ChannelByOrderIdLoader(info.context)
+ .load(granted_refund.order_id)
+ .then(
+ lambda channel: ChannelContext(
+ node=page, channel_slug=channel.slug
+ )
+ )
+ )
+
+ return (
+ OrderGrantedRefundByIdLoader(info.context)
+ .load(root.node.granted_refund_id)
+ .then(_wrap_with_channel)
+ )
+
+ return (
+ PageByIdLoader(info.context)
+ .load(root.node.reason_reference_id)
+ .then(wrap_page_with_context)
+ )
+
class OrderGrantedRefund(
SyncWebhookControlContextModelObjectType[ModelObjectType[models.OrderGrantedRefund]]
@@ -410,7 +453,7 @@ class OrderGrantedRefund(
def resolve_reason_reference(
root: SyncWebhookControlContext[models.OrderGrantedRefund], info
):
- if not root.node.reason_reference:
+ if not root.node.reason_reference_id:
return None
def wrap_page_with_context(page):
@@ -821,6 +864,15 @@ class FulfillmentLine(
lambda: OrderLine,
description="The order line to which the fulfillment line is related.",
)
+ reason = graphene.String(
+ description="Reason for returning this fulfillment line." + ADDED_IN_323,
+ )
+ reason_reference = graphene.Field(
+ Page,
+ required=False,
+ description="Reason Model (Page) reference for this fulfillment line."
+ + ADDED_IN_323,
+ )
class Meta:
default_resolver = (
@@ -845,6 +897,37 @@ class FulfillmentLine(
.then(_wrap_with_sync_webhook_control_context)
)
+ @staticmethod
+ def resolve_reason_reference(
+ root: SyncWebhookControlContext[models.FulfillmentLine], info
+ ):
+ if not root.node.reason_reference_id:
+ return None
+
+ def wrap_page_with_context(page):
+ if not page:
+ return None
+
+ return (
+ FulfillmentByIdLoader(info.context)
+ .load(root.node.fulfillment_id)
+ .then(
+ lambda fulfillment: ChannelByOrderIdLoader(info.context)
+ .load(fulfillment.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 Fulfillment(
SyncWebhookControlContextModelObjectType[ModelObjectType[models.Fulfillment]]
@@ -880,6 +963,15 @@ class Fulfillment(
description="Total refunded amount assigned to this fulfillment.",
required=False,
)
+ reason = graphene.String(
+ description="Reason for returning this fulfillment." + ADDED_IN_323,
+ )
+ reason_reference = graphene.Field(
+ Page,
+ required=False,
+ description="Reason Model (Page) reference for this fulfillment."
+ + ADDED_IN_323,
+ )
class Meta:
default_resolver = (
@@ -978,6 +1070,31 @@ class Fulfillment(
.then(_resolve_total_refund_amount)
)
+ @staticmethod
+ def resolve_reason_reference(
+ root: SyncWebhookControlContext[models.Fulfillment], info
+ ):
+ if not root.node.reason_reference_id:
+ 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 OrderLine(
SyncWebhookControlContextModelObjectType[ModelObjectType[models.OrderLine]]
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
index e19d43b810..c171740f7d 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
@@ -34,7 +34,7 @@ from ....plugins.dataloaders import get_plugin_manager_promise
from ....site.dataloaders import get_site_promise
from ...enums import TransactionActionEnum
from ...types import TransactionItem
-from ...utils import validate_and_resolve_refund_reason_context
+from ...utils import validate_reason_reference_context
from .utils import create_transaction_event_requested, get_transaction_item
if TYPE_CHECKING:
@@ -212,28 +212,28 @@ class TransactionRequestAction(BaseMutation):
site = get_site_promise(info.context).get()
- refund_reason_context = validate_and_resolve_refund_reason_context(
+ refund_reason_reference_type = site.settings.refund_reason_reference_type
+ should_apply = validate_reason_reference_context(
reason_reference_id=reason_reference_id,
requestor_is_user=bool(requestor_is_user),
- refund_reference_field_name="refund_reason_reference",
+ reason_reference_field_name="refund_reason_reference",
error_code_enum=TransactionRequestActionErrorCode,
- site_settings=site.settings,
+ reason_reference_type=refund_reason_reference_type,
+ )
+ refund_reason_reference_type_pk = (
+ refund_reason_reference_type.pk if refund_reason_reference_type else None
)
-
- refund_reason_reference_type = refund_reason_context[
- "refund_reason_reference_type"
- ]
reason_reference_instance: Page | None = None
- if refund_reason_context["should_apply"]:
+ if should_apply and refund_reason_reference_type_pk:
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
+ pk=reason_reference_pk, page_type=refund_reason_reference_type_pk
)
except (Page.DoesNotExist, ValueError):
diff --git a/saleor/graphql/payment/tests/mutations/conftest.py b/saleor/graphql/payment/tests/mutations/conftest.py
new file mode 100644
index 0000000000..e2928c09b0
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/conftest.py
@@ -0,0 +1,18 @@
+import pytest
+
+from .....app.models import App
+
+
+def transaction_request_webhook(permission_manage_payments):
+ app = App.objects.create(
+ name="Sample app objects",
+ is_active=True,
+ identifier="saleor.app.payment",
+ )
+ app.permissions.set([permission_manage_payments])
+ webhook = app.webhooks.create(
+ name="Request", is_active=True, target_url="http://localhost:8000/endpoint/"
+ )
+
+ return webhook
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 14cf010976..71f6b4211b 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -4,21 +4,18 @@ from unittest.mock import patch
import graphene
import pytest
-from .....app.models import App
from .....checkout import CheckoutAuthorizeStatus
from .....checkout.payment_utils import update_checkout_payment_statuses
from .....giftcard import GiftCardEvents
from .....giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from .....giftcard.models import GiftCardEvent
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 .....tests.e2e.utils import assign_permissions
from .....webhook.event_types import WebhookEventSyncType
from ....core.enums import TransactionRequestActionErrorCode
-from ....core.utils import to_global_id_or_none
from ....tests.utils import (
assert_no_permission,
get_graphql_content,
@@ -258,21 +255,6 @@ def test_transaction_request_action_amount_with_lot_of_decimal_places(
)
-def transaction_request_webhook(permission_manage_payments):
- app = App.objects.create(
- name="Sample app objects",
- is_active=True,
- identifier="saleor.app.payment",
- )
- app.permissions.set([permission_manage_payments])
- webhook = app.webhooks.create(
- name="Request", is_active=True, target_url="http://localhost:8000/endpoint/"
- )
-
- return webhook
-
-
@pytest.mark.parametrize(
("charge_amount", "expected_called_charge_amount"),
[
@@ -1329,715 +1311,6 @@ def test_transaction_request_cancel_sets_user_to_request_event(
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
-
-
-@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
-@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
-def test_transaction_request_charge_without_reason_when_refund_reasons_enabled(
- mocked_payment_action_request,
- mocked_is_active,
- order_with_lines,
- 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_CHARGE_REQUESTED
- )
-
- authorization_amount = Decimal("10.00")
- transaction = transaction_item_generator(
- order_id=order_with_lines.pk,
- authorized_value=authorization_amount,
- app=transaction_request_webhook.app,
- )
-
- transaction.events.create(
- amount_value=authorization_amount,
- currency=transaction.currency,
- type=TransactionEventType.AUTHORIZATION_SUCCESS,
- )
-
- variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
- "action_type": TransactionActionEnum.CHARGE.name,
- "amount": authorization_amount,
- }
- 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, f"Expected no errors but got: {errors}"
-
- request_event = TransactionEvent.objects.filter(
- type=TransactionEventType.CHARGE_REQUEST,
- ).first()
-
- assert request_event
- assert request_event.amount_value == authorization_amount
- assert request_event.user == staff_api_client.user
- assert request_event.message is None
- assert request_event.reason_reference is None
-
- assert mocked_payment_action_request.called
-
-
@pytest.mark.parametrize(
(
"amount",
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action_reason.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action_reason.py
new file mode 100644
index 0000000000..dbb15cb2ec
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action_reason.py
@@ -0,0 +1,807 @@
+from decimal import Decimal
+from unittest.mock import patch
+
+import graphene
+
+from .....page.models import Page, PageType
+from .....payment import TransactionEventType
+from .....payment.models import TransactionEvent
+from .....webhook.event_types import WebhookEventSyncType
+from ....core.enums import TransactionRequestActionErrorCode
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import (
+ get_graphql_content,
+)
+from ...enums import TransactionActionEnum
+
+MUTATION_TRANSACTION_REQUEST_ACTION = """
+mutation TransactionRequestAction(
+ $id: ID
+ $action_type: TransactionActionEnum!
+ $amount: PositiveDecimal
+ $refund_reason: String
+ $refund_reason_reference: ID
+ ){
+ transactionRequestAction(
+ id: $id,
+ actionType: $action_type,
+ amount: $amount,
+ refundReason: $refund_reason,
+ refundReasonReference: $refund_reason_reference
+ ){
+ transaction{
+ id
+ actions
+ pspReference
+ modifiedAt
+ createdAt
+ authorizedAmount{
+ amount
+ currency
+ }
+ chargedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+MUTATION_TRANSACTION_REQUEST_ACTION_BY_TOKEN = """
+mutation TransactionRequestAction(
+ $token: UUID
+ $action_type: TransactionActionEnum!
+ $amount: PositiveDecimal
+ $reason: String
+ $reason_reference: ID
+ ){
+ transactionRequestAction(
+ token: $token,
+ actionType: $action_type,
+ amount: $amount,
+ refundReason: $reason,
+ refundReasonReference: $reason_reference
+ ){
+ transaction{
+ id
+ actions
+ pspReference
+ modifiedAt
+ createdAt
+ authorizedAmount{
+ amount
+ currency
+ }
+ chargedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
+@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
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_transaction_request_charge_without_reason_when_refund_reasons_enabled(
+ mocked_payment_action_request,
+ mocked_is_active,
+ order_with_lines,
+ 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_CHARGE_REQUESTED
+ )
+
+ authorization_amount = Decimal("10.00")
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ authorized_value=authorization_amount,
+ app=transaction_request_webhook.app,
+ )
+
+ transaction.events.create(
+ amount_value=authorization_amount,
+ currency=transaction.currency,
+ type=TransactionEventType.AUTHORIZATION_SUCCESS,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.CHARGE.name,
+ "amount": authorization_amount,
+ }
+ 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, f"Expected no errors but got: {errors}"
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST,
+ ).first()
+
+ assert request_event
+ assert request_event.amount_value == authorization_amount
+ assert request_event.user == staff_api_client.user
+ assert request_event.message is None
+ assert request_event.reason_reference is None
+
+ assert mocked_payment_action_request.called
diff --git a/saleor/graphql/payment/tests/test_utils.py b/saleor/graphql/payment/tests/test_utils.py
index 594c8d1853..c83c73520f 100644
--- a/saleor/graphql/payment/tests/test_utils.py
+++ b/saleor/graphql/payment/tests/test_utils.py
@@ -6,46 +6,32 @@ from ....payment.error_codes import (
TransactionRequestActionErrorCode,
TransactionRequestRefundForGrantedRefundErrorCode,
)
-from ..utils import validate_and_resolve_refund_reason_context
+from ..utils import validate_reason_reference_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(
+def test_no_reference_type_configured_no_reference_id_provided():
+ # Given / When
+ should_apply = validate_reason_reference_context(
reason_reference_id=None,
requestor_is_user=True,
- refund_reference_field_name="refundReasonReference",
+ reason_reference_field_name="refundReasonReference",
error_code_enum=TransactionRequestActionErrorCode,
- site_settings=site_settings,
+ reason_reference_type=None,
)
# Then
- assert result == {
- "is_passing_reason_reference_required": False,
- "refund_reason_reference_type": None,
- "should_apply": False,
- }
-
+ assert should_apply is 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
+def test_no_reference_type_configured_reference_id_provided_raises_invalid():
+ # Given / When / Then
with pytest.raises(ValidationError) as exc_info:
- validate_and_resolve_refund_reason_context(
+ validate_reason_reference_context(
reason_reference_id="some-id",
requestor_is_user=True,
- refund_reference_field_name="refundReasonReference",
+ reason_reference_field_name="refundReasonReference",
error_code_enum=TransactionRequestActionErrorCode,
- site_settings=site_settings,
+ reason_reference_type=None,
)
error_dict = exc_info.value.error_dict
@@ -59,23 +45,19 @@ def test_no_reference_type_configured_reference_id_provided_raises_invalid(
)
-def test_reference_type_configured_no_reference_id_user_requestor_raises_required(
- site_settings,
-):
+def test_reference_type_configured_no_reference_id_user_requestor_raises_required():
# 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(
+ validate_reason_reference_context(
reason_reference_id=None,
requestor_is_user=True,
- refund_reference_field_name="refundReasonReference",
+ reason_reference_field_name="refundReasonReference",
error_code_enum=TransactionRequestActionErrorCode,
- site_settings=site_settings,
+ reason_reference_type=page_type,
)
error_dict = exc_info.value.error_dict
@@ -87,99 +69,75 @@ def test_reference_type_configured_no_reference_id_user_requestor_raises_require
assert "Reason reference is required" in str(error_dict["refundReasonReference"][0])
-def test_reference_type_configured_no_reference_id_app_requestor_success(
- site_settings,
-):
+def test_reference_type_configured_no_reference_id_app_requestor_success():
"""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(
+ should_apply = validate_reason_reference_context(
reason_reference_id=None,
requestor_is_user=False, # App requestor
- refund_reference_field_name="refundReasonReference",
+ reason_reference_field_name="refundReasonReference",
error_code_enum=TransactionRequestActionErrorCode,
- site_settings=site_settings,
+ reason_reference_type=page_type,
)
# Then
- assert result == {
- "is_passing_reason_reference_required": True,
- "refund_reason_reference_type": page_type,
- "should_apply": False,
- }
+ assert should_apply is False
-def test_reference_type_configured_reference_id_provided_success(site_settings):
+def test_reference_type_configured_reference_id_provided_success():
"""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(
+ should_apply = validate_reason_reference_context(
reason_reference_id="some-reference-id",
requestor_is_user=True,
- refund_reference_field_name="refundReasonReference",
+ reason_reference_field_name="refundReasonReference",
error_code_enum=TransactionRequestActionErrorCode,
- site_settings=site_settings,
+ reason_reference_type=page_type,
)
# Then
- assert result == {
- "is_passing_reason_reference_required": True,
- "refund_reason_reference_type": page_type,
- "should_apply": True,
- }
+ assert should_apply is True
-def test_reference_type_configured_reference_id_provided_app_requestor_success(
- site_settings,
-):
+def test_reference_type_configured_reference_id_provided_app_requestor_success():
"""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(
+ should_apply = validate_reason_reference_context(
reason_reference_id="some-reference-id",
requestor_is_user=False, # App requestor
- refund_reference_field_name="refundReasonReference",
+ reason_reference_field_name="refundReasonReference",
error_code_enum=TransactionRequestActionErrorCode,
- site_settings=site_settings,
+ reason_reference_type=page_type,
)
# Then
- assert result == {
- "is_passing_reason_reference_required": True,
- "refund_reason_reference_type": page_type,
- "should_apply": True,
- }
+ assert should_apply is True
-def test_custom_field_name_in_error_message(site_settings):
+def test_custom_field_name_in_error_message():
# 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(
+ validate_reason_reference_context(
reason_reference_id="some-id",
requestor_is_user=True,
- refund_reference_field_name=custom_field_name,
+ reason_reference_field_name=custom_field_name,
error_code_enum=TransactionRequestActionErrorCode,
- site_settings=site_settings,
+ reason_reference_type=None,
)
error_dict = exc_info.value.error_dict
@@ -190,22 +148,20 @@ def test_custom_field_name_in_error_message(site_settings):
)
-def test_custom_field_name_in_required_error_message(site_settings):
+def test_custom_field_name_in_required_error_message():
# 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(
+ validate_reason_reference_context(
reason_reference_id=None,
requestor_is_user=True,
- refund_reference_field_name=custom_field_name,
+ reason_reference_field_name=custom_field_name,
error_code_enum=TransactionRequestActionErrorCode,
- site_settings=site_settings,
+ reason_reference_type=page_type,
)
error_dict = exc_info.value.error_dict
@@ -216,20 +172,16 @@ def test_custom_field_name_in_required_error_message(site_settings):
)
-def test_different_error_code_enum(site_settings):
+def test_different_error_code_enum():
"""Test that the function works with different error code enums."""
- # Given
- site_settings.refund_reason_reference_type = None
- site_settings.save()
-
- # When / Then
+ # Given / When / Then
with pytest.raises(ValidationError) as exc_info:
- validate_and_resolve_refund_reason_context(
+ validate_reason_reference_context(
reason_reference_id="some-id",
requestor_is_user=True,
- refund_reference_field_name="refundReasonReference",
+ reason_reference_field_name="refundReasonReference",
error_code_enum=TransactionRequestRefundForGrantedRefundErrorCode,
- site_settings=site_settings,
+ reason_reference_type=None,
)
error_dict = exc_info.value.error_dict
@@ -238,43 +190,3 @@ def test_different_error_code_enum(site_settings):
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,
- site_settings=site_settings,
- )
-
- # 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,
- site_settings=site_settings,
- )
-
- # Then
- assert result["is_passing_reason_reference_required"] is True
diff --git a/saleor/graphql/payment/utils.py b/saleor/graphql/payment/utils.py
index 18ce2531d2..49ce543c74 100644
--- a/saleor/graphql/payment/utils.py
+++ b/saleor/graphql/payment/utils.py
@@ -2,8 +2,8 @@ from typing import TYPE_CHECKING, Optional
from django.core.exceptions import ValidationError
+from ...page.models import PageType
from ...payment import models as payment_models
-from ...site.models import SiteSettings
if TYPE_CHECKING:
from ...account.models import User
@@ -46,50 +46,49 @@ def check_if_requestor_has_access(
return False
-def validate_and_resolve_refund_reason_context(
+def validate_reason_reference_context(
*,
reason_reference_id: str | None,
requestor_is_user: bool,
- refund_reference_field_name: str,
+ reason_reference_field_name: str,
error_code_enum,
- site_settings: SiteSettings,
-):
- refund_reason_reference_type = site_settings.refund_reason_reference_type
+ reason_reference_type: PageType | None,
+) -> bool:
+ """Validate conditions for applying reason reference.
+
+ This does not verify that ``reason_reference_id`` points to a Page of
+ ``reason_reference_type``.
- is_passing_reason_reference_required: bool = (
- refund_reason_reference_type is not None
- )
+ The caller must supply ``reason_reference_type`` (e.g. the refund or return
+ reason reference type from the site settings); passing ``None`` means no
+ reference type is configured.
- if not refund_reason_reference_type and reason_reference_id:
+ Returns ``should_apply`` — whether a reason reference should be resolved and
+ applied. When it is ``True`` the supplied ``reason_reference_type`` is
+ guaranteed to be set, so the caller can resolve against it directly.
+ """
+ if not reason_reference_type and reason_reference_id:
raise ValidationError(
{
- refund_reference_field_name: ValidationError(
+ reason_reference_field_name: ValidationError(
"Reason reference type is not configured.",
code=error_code_enum.INVALID.value,
)
}
- ) from None
+ )
if (
- is_passing_reason_reference_required
+ reason_reference_type is not None
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.",
+ reason_reference_field_name: ValidationError(
+ "Reason reference is required when 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,
- }
+ return bool(reason_reference_id is not None and reason_reference_type)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index e577c20f04..c44367740d 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -266,6 +266,11 @@ type Query {
"""
refundSettings: RefundSettings! @doc(category: "Shop")
+ """
+ Returns related settings. Returns `ReturnSettings` configuration, global for the entire shop.
+ """
+ returnSettings: ReturnSettings! @doc(category: "Shop")
+
"""
Look up a shipping zone by ID.
@@ -12178,6 +12183,20 @@ type Fulfillment implements Node & ObjectWithMetadata @doc(category: "Orders") {
"""Total refunded amount assigned to this fulfillment."""
totalRefundedAmount: Money
+
+ """
+ Reason for returning this fulfillment.
+
+ Added in Saleor 3.23.
+ """
+ reason: String
+
+ """
+ Reason Model (Page) reference for this fulfillment.
+
+ Added in Saleor 3.23.
+ """
+ reasonReference: Page
}
enum FulfillmentStatus @doc(category: "Orders") {
@@ -12200,6 +12219,20 @@ type FulfillmentLine implements Node @doc(category: "Orders") {
"""The order line to which the fulfillment line is related."""
orderLine: OrderLine
+
+ """
+ Reason for returning this fulfillment line.
+
+ Added in Saleor 3.23.
+ """
+ reason: String
+
+ """
+ Reason Model (Page) reference for this fulfillment line.
+
+ Added in Saleor 3.23.
+ """
+ reasonReference: Page
}
"""Represents order line of particular order."""
@@ -12444,6 +12477,215 @@ enum OrderDiscountType @doc(category: "Discounts") {
ORDER_PROMOTION
}
+"""
+A static page that can be manually added by a shop operator through the dashboard.
+"""
+type Page implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(category: "Pages") {
+ """ID of the page."""
+ id: ID!
+
+ """List of private metadata items. Requires staff permissions to access."""
+ privateMetadata: [MetadataItem!]!
+
+ """
+ A single key from private metadata. Requires staff permissions to access.
+
+ Tip: Use GraphQL aliases to fetch multiple keys.
+ """
+ privateMetafield(key: String!): String
+
+ """
+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.
+ """
+ privateMetafields(keys: [String!]): Metadata
+
+ """List of public metadata items. Can be accessed without permissions."""
+ metadata: [MetadataItem!]!
+
+ """
+ A single key from public metadata.
+
+ Tip: Use GraphQL aliases to fetch multiple keys.
+ """
+ metafield(key: String!): String
+
+ """
+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.
+ """
+ metafields(keys: [String!]): Metadata
+
+ """
+ Get a single attribute attached to page by attribute slug.
+
+ Added in Saleor 3.22.
+ """
+ assignedAttribute(
+ """Slug of the attribute"""
+ slug: String!
+ ): AssignedAttribute
+
+ """
+ List of attributes assigned to this page.
+
+ Added in Saleor 3.22.
+ """
+ assignedAttributes(
+ """Maximum number of attributes to return. Default is 100."""
+ limit: PositiveInt = 100
+ ): [AssignedAttribute!]!
+
+ """Title of the page for SEO."""
+ seoTitle: String
+
+ """Description of the page for SEO."""
+ seoDescription: String
+
+ """Title of the page."""
+ title: String!
+
+ """
+ Content of the page.
+
+ Rich text format. For reference see https://editorjs.io/
+ """
+ content: JSONString
+ publicationDate: Date @deprecated(reason: "Use the `publishedAt` field to fetch the publication date.")
+
+ """The page publication date."""
+ publishedAt: DateTime
+
+ """Determines if the page is published."""
+ isPublished: Boolean!
+
+ """Slug of the page."""
+ slug: String!
+
+ """Determines the type of page"""
+ pageType: PageType!
+
+ """Date and time at which page was created."""
+ created: DateTime!
+
+ """
+ Content of the page.
+
+ Rich text format. For reference see https://editorjs.io/
+ """
+ contentJson: JSONString! @deprecated(reason: "Use the `content` field instead.")
+
+ """Returns translated page fields for the given language code."""
+ translation(
+ """A language code to return the translation for page."""
+ languageCode: LanguageCodeEnum!
+ ): PageTranslation
+
+ """Get a single attribute attached to page by attribute slug."""
+ attribute(
+ """Slug of the attribute"""
+ slug: String!
+ ): SelectedAttribute @deprecated(reason: "Use `assignedAttribute` field instead.")
+
+ """List of attributes assigned to this page."""
+ attributes: [SelectedAttribute!]! @deprecated(reason: "Use `assignedAttributes` field instead.")
+}
+
+"""Represents page translations."""
+type PageTranslation implements Node @doc(category: "Pages") {
+ """The ID of the page translation."""
+ id: ID!
+
+ """Translation language."""
+ language: LanguageDisplay!
+
+ """Translated SEO title."""
+ seoTitle: String
+
+ """Translated SEO description."""
+ seoDescription: String
+
+ """
+ Translated page slug.
+
+ Added in Saleor 3.21.
+ """
+ slug: String
+
+ """Translated page title."""
+ title: String
+
+ """
+ Translated content of the page.
+
+ Rich text format. For reference see https://editorjs.io/
+ """
+ content: JSONString
+
+ """
+ Translated description of the page.
+
+ Rich text format. For reference see https://editorjs.io/
+ """
+ contentJson: JSONString @deprecated(reason: "Use the `content` field instead.")
+
+ """Represents the page fields to translate."""
+ translatableContent: PageTranslatableContent
+}
+
+"""
+Represents page's original translatable fields and related translations.
+"""
+type PageTranslatableContent implements Node @doc(category: "Pages") {
+ """The ID of the page translatable content."""
+ id: ID!
+
+ """The ID of the page to translate."""
+ pageId: ID!
+
+ """SEO title to translate."""
+ seoTitle: String
+
+ """SEO description to translate."""
+ seoDescription: String
+
+ """
+ Slug to translate.
+
+ Added in Saleor 3.21.
+ """
+ slug: String
+
+ """Page title to translate."""
+ title: String!
+
+ """
+ Content of the page to translate.
+
+ Rich text format. For reference see https://editorjs.io/
+ """
+ content: JSONString
+
+ """
+ Content of the page.
+
+ Rich text format. For reference see https://editorjs.io/
+ """
+ contentJson: JSONString @deprecated(reason: "Use the `content` field instead.")
+
+ """Returns translated page fields for the given language code."""
+ translation(
+ """A language code to return the translation for page."""
+ languageCode: LanguageCodeEnum!
+ ): PageTranslation
+
+ """
+ A static page that can be manually added by a shop operator through the dashboard.
+ """
+ page: Page @deprecated(reason: "Get model fields from the root level queries.")
+
+ """List of page content attribute values that can be translated."""
+ attributeValues: [AttributeValueTranslatableContent!]!
+}
+
enum OrderAction @doc(category: "Payments") {
"""Represents the capture action."""
CAPTURE
@@ -13035,310 +13277,101 @@ enum OrderErrorCode @doc(category: "Orders") {
NOT_EDITABLE
FULFILL_ORDER_LINE
GRAPHQL_ERROR
- INVALID
- PRODUCT_NOT_PUBLISHED
- PRODUCT_UNAVAILABLE_FOR_PURCHASE
- NOT_FOUND
- ORDER_NO_SHIPPING_ADDRESS
- PAYMENT_ERROR
- PAYMENT_MISSING
- TRANSACTION_ERROR
- REQUIRED
- SHIPPING_METHOD_NOT_APPLICABLE
- SHIPPING_METHOD_REQUIRED
- TAX_ERROR
- UNIQUE
- VOID_INACTIVE_PAYMENT
- ZERO_QUANTITY
- INVALID_QUANTITY
- INSUFFICIENT_STOCK
- DUPLICATED_INPUT_ITEM
- NOT_AVAILABLE_IN_CHANNEL
- CHANNEL_INACTIVE
- INVALID_VOUCHER
- INVALID_VOUCHER_CODE
- NON_EDITABLE_GIFT_LINE
- NON_REMOVABLE_GIFT_LINE
- MISSING_ADDRESS_DATA
-}
-
-enum AddressTypeEnum {
- BILLING
- SHIPPING
-}
-
-"""The details of granted refund."""
-type OrderGrantedRefund @doc(category: "Orders") {
- id: ID!
-
- """Time of creation."""
- createdAt: DateTime!
-
- """Time of last update."""
- updatedAt: DateTime!
-
- """Refund amount."""
- amount: Money!
-
- """
- 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.
- """
- user: User
-
- """App that performed the action."""
- app: App
-
- """
- If true, the refunded amount includes the shipping price.If false, the refunded amount does not include the shipping price.
- """
- shippingCostsIncluded: Boolean!
-
- """Lines assigned to the granted refund."""
- lines: [OrderGrantedRefundLine!]
-
- """
- Status of the granted refund calculated based on transactionItem assigned to granted refund.
-
- Added in Saleor 3.20.
- """
- status: OrderGrantedRefundStatusEnum!
-
- """
- List of refund events associated with the granted refund.
-
- Added in Saleor 3.20.
- """
- transactionEvents: [TransactionEvent!]
-
- """
- The transaction assigned to the granted refund.
-
- Added in Saleor 3.20.
- """
- transaction: TransactionItem
-}
-
-"""
-A static page that can be manually added by a shop operator through the dashboard.
-"""
-type Page implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(category: "Pages") {
- """ID of the page."""
- id: ID!
-
- """List of private metadata items. Requires staff permissions to access."""
- privateMetadata: [MetadataItem!]!
-
- """
- A single key from private metadata. Requires staff permissions to access.
-
- Tip: Use GraphQL aliases to fetch multiple keys.
- """
- privateMetafield(key: String!): String
-
- """
- Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.
- """
- privateMetafields(keys: [String!]): Metadata
-
- """List of public metadata items. Can be accessed without permissions."""
- metadata: [MetadataItem!]!
-
- """
- A single key from public metadata.
-
- Tip: Use GraphQL aliases to fetch multiple keys.
- """
- metafield(key: String!): String
-
- """
- Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.
- """
- metafields(keys: [String!]): Metadata
-
- """
- Get a single attribute attached to page by attribute slug.
-
- Added in Saleor 3.22.
- """
- assignedAttribute(
- """Slug of the attribute"""
- slug: String!
- ): AssignedAttribute
-
- """
- List of attributes assigned to this page.
-
- Added in Saleor 3.22.
- """
- assignedAttributes(
- """Maximum number of attributes to return. Default is 100."""
- limit: PositiveInt = 100
- ): [AssignedAttribute!]!
-
- """Title of the page for SEO."""
- seoTitle: String
-
- """Description of the page for SEO."""
- seoDescription: String
-
- """Title of the page."""
- title: String!
-
- """
- Content of the page.
-
- Rich text format. For reference see https://editorjs.io/
- """
- content: JSONString
- publicationDate: Date @deprecated(reason: "Use the `publishedAt` field to fetch the publication date.")
-
- """The page publication date."""
- publishedAt: DateTime
-
- """Determines if the page is published."""
- isPublished: Boolean!
-
- """Slug of the page."""
- slug: String!
-
- """Determines the type of page"""
- pageType: PageType!
-
- """Date and time at which page was created."""
- created: DateTime!
-
- """
- Content of the page.
-
- Rich text format. For reference see https://editorjs.io/
- """
- contentJson: JSONString! @deprecated(reason: "Use the `content` field instead.")
-
- """Returns translated page fields for the given language code."""
- translation(
- """A language code to return the translation for page."""
- languageCode: LanguageCodeEnum!
- ): PageTranslation
-
- """Get a single attribute attached to page by attribute slug."""
- attribute(
- """Slug of the attribute"""
- slug: String!
- ): SelectedAttribute @deprecated(reason: "Use `assignedAttribute` field instead.")
+ INVALID
+ PRODUCT_NOT_PUBLISHED
+ PRODUCT_UNAVAILABLE_FOR_PURCHASE
+ NOT_FOUND
+ ORDER_NO_SHIPPING_ADDRESS
+ PAYMENT_ERROR
+ PAYMENT_MISSING
+ TRANSACTION_ERROR
+ REQUIRED
+ SHIPPING_METHOD_NOT_APPLICABLE
+ SHIPPING_METHOD_REQUIRED
+ TAX_ERROR
+ UNIQUE
+ VOID_INACTIVE_PAYMENT
+ ZERO_QUANTITY
+ INVALID_QUANTITY
+ INSUFFICIENT_STOCK
+ DUPLICATED_INPUT_ITEM
+ NOT_AVAILABLE_IN_CHANNEL
+ CHANNEL_INACTIVE
+ INVALID_VOUCHER
+ INVALID_VOUCHER_CODE
+ NON_EDITABLE_GIFT_LINE
+ NON_REMOVABLE_GIFT_LINE
+ MISSING_ADDRESS_DATA
+}
- """List of attributes assigned to this page."""
- attributes: [SelectedAttribute!]! @deprecated(reason: "Use `assignedAttributes` field instead.")
+enum AddressTypeEnum {
+ BILLING
+ SHIPPING
}
-"""Represents page translations."""
-type PageTranslation implements Node @doc(category: "Pages") {
- """The ID of the page translation."""
+"""The details of granted refund."""
+type OrderGrantedRefund @doc(category: "Orders") {
id: ID!
- """Translation language."""
- language: LanguageDisplay!
+ """Time of creation."""
+ createdAt: DateTime!
- """Translated SEO title."""
- seoTitle: String
+ """Time of last update."""
+ updatedAt: DateTime!
- """Translated SEO description."""
- seoDescription: String
+ """Refund amount."""
+ amount: Money!
"""
- Translated page slug.
+ Reason of the refund.
- Added in Saleor 3.21.
+ Added in Saleor 3.22.
"""
- slug: String
-
- """Translated page title."""
- title: String
+ reason: String
"""
- Translated content of the page.
+ Reason Model (Page) reference for refund.
- Rich text format. For reference see https://editorjs.io/
+ Added in Saleor 3.22.
"""
- content: JSONString
+ reasonReference: Page
"""
- Translated description of the page.
-
- Rich text format. For reference see https://editorjs.io/
+ User who performed the action. Requires of of the following permissions: MANAGE_USERS, MANAGE_STAFF, OWNER.
"""
- contentJson: JSONString @deprecated(reason: "Use the `content` field instead.")
-
- """Represents the page fields to translate."""
- translatableContent: PageTranslatableContent
-}
-
-"""
-Represents page's original translatable fields and related translations.
-"""
-type PageTranslatableContent implements Node @doc(category: "Pages") {
- """The ID of the page translatable content."""
- id: ID!
-
- """The ID of the page to translate."""
- pageId: ID!
-
- """SEO title to translate."""
- seoTitle: String
+ user: User
- """SEO description to translate."""
- seoDescription: String
+ """App that performed the action."""
+ app: App
"""
- Slug to translate.
-
- Added in Saleor 3.21.
+ If true, the refunded amount includes the shipping price.If false, the refunded amount does not include the shipping price.
"""
- slug: String
+ shippingCostsIncluded: Boolean!
- """Page title to translate."""
- title: String!
+ """Lines assigned to the granted refund."""
+ lines: [OrderGrantedRefundLine!]
"""
- Content of the page to translate.
+ Status of the granted refund calculated based on transactionItem assigned to granted refund.
- Rich text format. For reference see https://editorjs.io/
+ Added in Saleor 3.20.
"""
- content: JSONString
+ status: OrderGrantedRefundStatusEnum!
"""
- Content of the page.
+ List of refund events associated with the granted refund.
- Rich text format. For reference see https://editorjs.io/
+ Added in Saleor 3.20.
"""
- contentJson: JSONString @deprecated(reason: "Use the `content` field instead.")
-
- """Returns translated page fields for the given language code."""
- translation(
- """A language code to return the translation for page."""
- languageCode: LanguageCodeEnum!
- ): PageTranslation
+ transactionEvents: [TransactionEvent!]
"""
- A static page that can be manually added by a shop operator through the dashboard.
+ The transaction assigned to the granted refund.
+
+ Added in Saleor 3.20.
"""
- page: Page @deprecated(reason: "Get model fields from the root level queries.")
-
- """List of page content attribute values that can be translated."""
- attributeValues: [AttributeValueTranslatableContent!]!
+ transaction: TransactionItem
}
"""Represents granted refund line."""
@@ -13353,6 +13386,13 @@ type OrderGrantedRefundLine {
"""Reason for refunding the line."""
reason: String
+
+ """
+ Reason Model (Page) reference for this refund line.
+
+ Added in Saleor 3.23.
+ """
+ reasonReference: Page
}
"""
@@ -15297,6 +15337,20 @@ type RefundSettings @doc(category: "Orders") {
reasonReferenceType: PageType
}
+"""
+Return related settings from site settings.
+
+Added in Saleor 3.23.
+"""
+type ReturnSettings @doc(category: "Orders") {
+ """
+ Model type used for return reasons.
+
+ Added in Saleor 3.23.
+ """
+ reasonReferenceType: PageType
+}
+
input ShippingZoneFilterInput @doc(category: "Shipping") {
search: String
channels: [ID!]
@@ -17821,6 +17875,27 @@ type Mutation {
"""
refundReasonReferenceClear: RefundReasonReferenceTypeClear @doc(category: "Orders")
+ """
+ Update return settings across all channels.
+
+ Added in Saleor 3.23.
+
+ Requires one of the following permissions: MANAGE_SETTINGS.
+ """
+ returnSettingsUpdate(
+ """Fields required to update return settings."""
+ input: ReturnSettingsUpdateInput!
+ ): ReturnSettingsUpdate @doc(category: "Shop")
+
+ """
+ Updates ReturnSettings. The `Page` (Model) Type will be cleared from `reasonReferenceType`. When it's cleared, passing reason reference to return mutations is no longer accepted and will raise error.
+
+ Added in Saleor 3.23.
+
+ Requires one of the following permissions: MANAGE_SETTINGS.
+ """
+ returnReasonReferenceClear: ReturnReasonReferenceTypeClear @doc(category: "Orders")
+
"""
Calculates available delivery options for a checkout.
@@ -23427,6 +23502,76 @@ type RefundReasonReferenceTypeClearError @doc(category: "Shop") {
code: RefundSettingsErrorCode!
}
+"""
+Update return settings across all channels.
+
+Added in Saleor 3.23.
+
+Requires one of the following permissions: MANAGE_SETTINGS.
+"""
+type ReturnSettingsUpdate @doc(category: "Shop") {
+ """Return settings."""
+ returnSettings: ReturnSettings
+ returnSettingsErrors: [ReturnSettingsUpdateError!]! @deprecated(reason: "Use `errors` field instead.")
+ errors: [ReturnSettingsUpdateError!]!
+}
+
+type ReturnSettingsUpdateError @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 Return Settings"""
+ code: ReturnSettingsErrorCode!
+}
+
+enum ReturnSettingsErrorCode @doc(category: "Shop") {
+ INVALID
+ NOT_FOUND
+ REQUIRED
+ GRAPHQL_ERROR
+}
+
+input ReturnSettingsUpdateInput @doc(category: "Shop") {
+ """
+ The ID of a model type, that will be used to reference return reasons. All models of this type will be accepted as return reasons.
+
+ Added in Saleor 3.23.
+ """
+ returnReasonReferenceType: ID!
+}
+
+"""
+Updates ReturnSettings. The `Page` (Model) Type will be cleared from `reasonReferenceType`. When it's cleared, passing reason reference to return mutations is no longer accepted and will raise error.
+
+Added in Saleor 3.23.
+
+Requires one of the following permissions: MANAGE_SETTINGS.
+"""
+type ReturnReasonReferenceTypeClear @doc(category: "Orders") {
+ """Return settings."""
+ returnSettings: ReturnSettings
+ returnSettingsErrors: [ReturnReasonReferenceTypeClearError!]! @deprecated(reason: "Use `errors` field instead.")
+ errors: [ReturnReasonReferenceTypeClearError!]!
+}
+
+type ReturnReasonReferenceTypeClearError @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 return reason reference type"""
+ code: ReturnSettingsErrorCode!
+}
+
"""
Calculates available delivery options for a checkout.
@@ -27485,6 +27630,20 @@ input OrderReturnProductsInput @doc(category: "Orders") {
"""If true, Saleor will call refund action for all lines."""
refund: Boolean = false
+
+ """
+ Reason for returning this order.
+
+ Added in Saleor 3.23.
+ """
+ reason: String
+
+ """
+ ID of a `Page` (Model) to reference in reason for this return.
+
+ Added in Saleor 3.23.
+ """
+ reasonReference: ID
}
input OrderReturnLineInput @doc(category: "Orders") {
@@ -27496,6 +27655,20 @@ input OrderReturnLineInput @doc(category: "Orders") {
"""Determines, if the line should be added to replace order."""
replace: Boolean = false
+
+ """
+ Reason for returning this line.
+
+ Added in Saleor 3.23.
+ """
+ reason: String
+
+ """
+ ID of a `Page` (Model) to reference in reason for this line.
+
+ Added in Saleor 3.23.
+ """
+ reasonReference: ID
}
input OrderReturnFulfillmentLineInput @doc(category: "Orders") {
@@ -27507,6 +27680,20 @@ input OrderReturnFulfillmentLineInput @doc(category: "Orders") {
"""Determines, if the line should be added to replace order."""
replace: Boolean = false
+
+ """
+ Reason for returning this fulfillment line.
+
+ Added in Saleor 3.23.
+ """
+ reason: String
+
+ """
+ ID of a `Page` (Model) to reference in reason for this fulfillment line.
+
+ Added in Saleor 3.23.
+ """
+ reasonReference: ID
}
"""
@@ -27542,6 +27729,7 @@ type OrderGrantRefundCreateError @doc(category: "Orders") {
enum OrderGrantRefundCreateErrorCode @doc(category: "Orders") {
GRAPHQL_ERROR
NOT_FOUND
+ NOT_CONFIGURED
SHIPPING_COSTS_ALREADY_GRANTED
AMOUNT_GREATER_THAN_AVAILABLE
REQUIRED
@@ -27568,6 +27756,8 @@ enum OrderGrantRefundCreateLineErrorCode {
GRAPHQL_ERROR
NOT_FOUND
QUANTITY_GREATER_THAN_AVAILABLE
+ INVALID
+ NOT_CONFIGURED
}
input OrderGrantRefundCreateInput @doc(category: "Orders") {
@@ -27611,6 +27801,13 @@ input OrderGrantRefundCreateLineInput @doc(category: "Orders") {
"""Reason of the granted refund for the line."""
reason: String
+
+ """
+ ID of a `Page` (Model) to reference in reason for the line.
+
+ Added in Saleor 3.23.
+ """
+ reasonReference: ID
}
"""
@@ -27649,6 +27846,7 @@ type OrderGrantRefundUpdateError @doc(category: "Orders") {
enum OrderGrantRefundUpdateErrorCode @doc(category: "Orders") {
GRAPHQL_ERROR
NOT_FOUND
+ NOT_CONFIGURED
REQUIRED
INVALID
AMOUNT_GREATER_THAN_AVAILABLE
@@ -27675,6 +27873,8 @@ enum OrderGrantRefundUpdateLineErrorCode {
GRAPHQL_ERROR
NOT_FOUND
QUANTITY_GREATER_THAN_AVAILABLE
+ INVALID
+ NOT_CONFIGURED
}
input OrderGrantRefundUpdateInput @doc(category: "Orders") {
@@ -27721,6 +27921,13 @@ input OrderGrantRefundUpdateLineAddInput @doc(category: "Orders") {
"""Reason of the granted refund for the line."""
reason: String
+
+ """
+ ID of a `Page` (Model) to reference in reason for the line.
+
+ Added in Saleor 3.23.
+ """
+ reasonReference: ID
}
"""
diff --git a/saleor/graphql/shop/mutations/__init__.py b/saleor/graphql/shop/mutations/__init__.py
index 9d279c962c..9def9fd02f 100644
--- a/saleor/graphql/shop/mutations/__init__.py
+++ b/saleor/graphql/shop/mutations/__init__.py
@@ -2,6 +2,8 @@ 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 .return_reason_reference_type_clear import ReturnReasonReferenceTypeClear
+from .return_settings_update import ReturnSettingsUpdate
from .shop_address_update import ShopAddressUpdate
from .shop_domain_update import ShopDomainUpdate
from .shop_fetch_tax_rates import ShopFetchTaxRates
@@ -15,6 +17,8 @@ __all__ = [
"OrderSettingsUpdate",
"RefundSettingsUpdate",
"RefundReasonReferenceTypeClear",
+ "ReturnSettingsUpdate",
+ "ReturnReasonReferenceTypeClear",
"ShopAddressUpdate",
"ShopDomainUpdate",
"ShopFetchTaxRates",
diff --git a/saleor/graphql/shop/mutations/refund_settings_update.py b/saleor/graphql/shop/mutations/refund_settings_update.py
index a068b7948f..c9012338ec 100644
--- a/saleor/graphql/shop/mutations/refund_settings_update.py
+++ b/saleor/graphql/shop/mutations/refund_settings_update.py
@@ -1,12 +1,15 @@
import graphene
+from django.core.exceptions import ValidationError
from ....permission.enums import SitePermissions
+from ....site.error_codes import RefundSettingsErrorCode
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 ...page.types import PageType
from ...site.dataloaders import get_site_promise
from ..types import RefundSettings
@@ -46,19 +49,27 @@ class RefundSettingsUpdate(BaseMutation):
):
refund_reason_reference_type = input.get("refund_reason_reference_type")
+ if not refund_reason_reference_type:
+ raise ValidationError(
+ {
+ "refund_reason_reference_type": ValidationError(
+ "This field is required.",
+ code=RefundSettingsErrorCode.REQUIRED.value,
+ )
+ }
+ )
+
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]
+ model_type = cls.get_node_or_error(
+ info,
+ refund_reason_reference_type,
+ only_type=PageType,
+ field="refund_reason_reference_type",
+ )
- settings.save(update_fields=["refund_reason_reference_type"])
+ settings.refund_reason_reference_type = model_type
+ settings.save(update_fields=["refund_reason_reference_type"])
return RefundSettingsUpdate(refund_settings=settings)
diff --git a/saleor/graphql/shop/mutations/return_reason_reference_type_clear.py b/saleor/graphql/shop/mutations/return_reason_reference_type_clear.py
new file mode 100644
index 0000000000..c8c774496a
--- /dev/null
+++ b/saleor/graphql/shop/mutations/return_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_323
+from ...core.doc_category import DOC_CATEGORY_ORDERS
+from ...core.mutations import BaseMutation
+from ...core.types.common import ReturnReasonReferenceTypeClearError
+from ...site.dataloaders import get_site_promise
+from ..types import ReturnSettings
+
+
+class ReturnReasonReferenceTypeClear(BaseMutation):
+ return_settings = graphene.Field(ReturnSettings, description="Return settings.")
+
+ class Meta:
+ description = (
+ "Updates ReturnSettings. The `Page` (Model) Type will be cleared from "
+ "`reasonReferenceType`. When it's cleared, passing reason reference to "
+ "return mutations is no longer accepted and will raise error."
+ + ADDED_IN_323
+ )
+ doc_category = DOC_CATEGORY_ORDERS
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = ReturnReasonReferenceTypeClearError
+ error_type_field = "return_settings_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ site = get_site_promise(info.context).get()
+ settings = site.settings
+
+ settings.return_reason_reference_type = None
+
+ settings.save(update_fields=["return_reason_reference_type"])
+
+ return ReturnReasonReferenceTypeClear(return_settings=settings)
diff --git a/saleor/graphql/shop/mutations/return_settings_update.py b/saleor/graphql/shop/mutations/return_settings_update.py
new file mode 100644
index 0000000000..8ece051759
--- /dev/null
+++ b/saleor/graphql/shop/mutations/return_settings_update.py
@@ -0,0 +1,75 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....permission.enums import SitePermissions
+from ....site.error_codes import ReturnSettingsErrorCode
+from ...core import ResolveInfo
+from ...core.descriptions import ADDED_IN_323
+from ...core.doc_category import DOC_CATEGORY_SHOP
+from ...core.mutations import BaseMutation
+from ...core.types import BaseInputObjectType
+from ...core.types.common import ReturnSettingsUpdateError
+from ...page.types import PageType
+from ...site.dataloaders import get_site_promise
+from ..types import ReturnSettings
+
+
+class ReturnSettingsUpdateInput(BaseInputObjectType):
+ return_reason_reference_type = graphene.ID(
+ description=(
+ "The ID of a model type, that will be used to reference return reasons. "
+ "All models of this type will be accepted as return reasons. "
+ f"{ADDED_IN_323}"
+ ),
+ required=True,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_SHOP
+
+
+class ReturnSettingsUpdate(BaseMutation):
+ return_settings = graphene.Field(ReturnSettings, description="Return settings.")
+
+ class Arguments:
+ input = ReturnSettingsUpdateInput(
+ required=True, description="Fields required to update return settings."
+ )
+
+ class Meta:
+ description = "Update return settings across all channels." + ADDED_IN_323
+ doc_category = DOC_CATEGORY_SHOP
+ permissions = (SitePermissions.MANAGE_SETTINGS,)
+ error_type_class = ReturnSettingsUpdateError
+ error_type_field = "return_settings_errors"
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, input
+ ):
+ return_reason_reference_type = input.get("return_reason_reference_type")
+
+ if not return_reason_reference_type:
+ raise ValidationError(
+ {
+ "return_reason_reference_type": ValidationError(
+ "This field is required.",
+ code=ReturnSettingsErrorCode.REQUIRED.value,
+ )
+ }
+ )
+
+ site = get_site_promise(info.context).get()
+ settings = site.settings
+
+ model_type = cls.get_node_or_error(
+ info,
+ return_reason_reference_type,
+ only_type=PageType,
+ field="return_reason_reference_type",
+ )
+
+ settings.return_reason_reference_type = model_type
+ settings.save(update_fields=["return_reason_reference_type"])
+
+ return ReturnSettingsUpdate(return_settings=settings)
diff --git a/saleor/graphql/shop/schema.py b/saleor/graphql/shop/schema.py
index f1a690c883..d2f5dfc567 100644
--- a/saleor/graphql/shop/schema.py
+++ b/saleor/graphql/shop/schema.py
@@ -18,6 +18,8 @@ from .mutations import (
OrderSettingsUpdate,
RefundReasonReferenceTypeClear,
RefundSettingsUpdate,
+ ReturnReasonReferenceTypeClear,
+ ReturnSettingsUpdate,
ShopAddressUpdate,
ShopDomainUpdate,
ShopFetchTaxRates,
@@ -26,7 +28,7 @@ from .mutations import (
StaffNotificationRecipientDelete,
StaffNotificationRecipientUpdate,
)
-from .types import GiftCardSettings, RefundSettings, Shop
+from .types import GiftCardSettings, RefundSettings, ReturnSettings, Shop
class ShopQueries(graphene.ObjectType):
@@ -60,6 +62,13 @@ class ShopQueries(graphene.ObjectType):
permissions=[],
doc_category=DOC_CATEGORY_SHOP,
)
+ return_settings = PermissionsField(
+ ReturnSettings,
+ description="Returns related settings. Returns `ReturnSettings` configuration, global for the entire shop.",
+ required=True,
+ permissions=[],
+ doc_category=DOC_CATEGORY_SHOP,
+ )
def resolve_shop(self, _info):
return Shop()
@@ -92,6 +101,10 @@ class ShopQueries(graphene.ObjectType):
def resolve_refund_settings(self, _info, site):
return site.settings
+ @load_site_callback
+ def resolve_return_settings(self, _info, site):
+ return site.settings
+
class ShopMutations(graphene.ObjectType):
staff_notification_recipient_create = StaffNotificationRecipientCreate.Field()
@@ -114,3 +127,5 @@ class ShopMutations(graphene.ObjectType):
gift_card_settings_update = GiftCardSettingsUpdate.Field()
refund_settings_update = RefundSettingsUpdate.Field()
refund_reason_reference_clear = RefundReasonReferenceTypeClear.Field()
+ return_settings_update = ReturnSettingsUpdate.Field()
+ return_reason_reference_clear = ReturnReasonReferenceTypeClear.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
index 413a26d659..a038ac199b 100644
--- a/saleor/graphql/shop/tests/mutations/test_reason_reference_type_clear.py
+++ b/saleor/graphql/shop/tests/mutations/test_reason_reference_type_clear.py
@@ -29,10 +29,8 @@ def test_refund_reason_reference_type_clear_by_staff_success(
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(
@@ -59,10 +57,8 @@ def test_refund_reason_reference_type_clear_by_app_success(
# 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(
@@ -90,10 +86,8 @@ def test_refund_reason_reference_type_clear_when_already_none(
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(
@@ -125,10 +119,8 @@ def test_refund_reason_reference_type_clear_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(
diff --git a/saleor/graphql/shop/tests/mutations/test_refund_settings_update.py b/saleor/graphql/shop/tests/mutations/test_refund_settings_update.py
index 265e19bd87..fec9147b3d 100644
--- a/saleor/graphql/shop/tests/mutations/test_refund_settings_update.py
+++ b/saleor/graphql/shop/tests/mutations/test_refund_settings_update.py
@@ -119,7 +119,7 @@ def test_refund_settings_update_change_page_type(
assert site_settings.refund_reason_reference_type == page_type
-def test_refund_settings_update_empty_id_success(
+def test_refund_settings_update_empty_id_returns_error(
staff_api_client, permission_manage_settings, site_settings
):
# given
@@ -138,9 +138,11 @@ def test_refund_settings_update_empty_id_success(
content = get_graphql_content(response)
data = content["data"]["refundSettingsUpdate"]
- assert not data["errors"]
- assert data["refundSettings"]
- assert data["refundSettings"]["reasonReferenceType"] is None
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "refundReasonReferenceType"
+ assert data["errors"][0]["code"] == RefundSettingsErrorCode.REQUIRED.name
+ assert data["errors"][0]["message"] == "This field is required."
+ assert data["refundSettings"] is None
def test_refund_settings_update_invalid_id_format(
@@ -176,7 +178,10 @@ def test_refund_settings_update_nonexistent_page_type(
staff_user = staff_api_client.user
staff_user.user_permissions.add(permission_manage_settings)
- nonexistent_id = graphene.Node.to_global_id("PageType", 99999)
+ page_type_id = 99999
+ assert not PageType.objects.filter(pk=page_type_id).exists()
+
+ nonexistent_id = graphene.Node.to_global_id("PageType", page_type_id)
variables = {"input": {"refundReasonReferenceType": nonexistent_id}}
# when
diff --git a/saleor/graphql/shop/tests/mutations/test_return_reason_reference_type_clear.py b/saleor/graphql/shop/tests/mutations/test_return_reason_reference_type_clear.py
new file mode 100644
index 0000000000..303f67cf1d
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_return_reason_reference_type_clear.py
@@ -0,0 +1,140 @@
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+RETURN_REASON_REFERENCE_TYPE_CLEAR_MUTATION = """
+ mutation returnReasonReferenceClear {
+ returnReasonReferenceClear {
+ returnSettings {
+ reasonReferenceType {
+ id
+ name
+ slug
+ }
+ }
+ errors {
+ code
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_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)
+
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save()
+
+ # when
+ response = staff_api_client.post_graphql(
+ RETURN_REASON_REFERENCE_TYPE_CLEAR_MUTATION,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnReasonReferenceClear"]
+
+ assert not data["errors"]
+ assert data["returnSettings"]
+ assert data["returnSettings"]["reasonReferenceType"] is None
+
+ site_settings.refresh_from_db()
+ assert site_settings.return_reason_reference_type is None
+
+
+def test_by_app_success(
+ app_api_client, site_settings, permission_manage_settings, page_type
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_settings)
+
+ site_settings.return_reason_reference_type = page_type
+ site_settings.save()
+
+ # when
+ response = app_api_client.post_graphql(
+ RETURN_REASON_REFERENCE_TYPE_CLEAR_MUTATION,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnReasonReferenceClear"]
+
+ assert not data["errors"]
+ assert data["returnSettings"]
+ assert data["returnSettings"]["reasonReferenceType"] is None
+
+ site_settings.refresh_from_db()
+ assert site_settings.return_reason_reference_type is None
+
+
+def test_when_already_none(staff_api_client, site_settings, permission_manage_settings):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ site_settings.return_reason_reference_type = None
+ site_settings.save()
+
+ # when
+ response = staff_api_client.post_graphql(
+ RETURN_REASON_REFERENCE_TYPE_CLEAR_MUTATION,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnReasonReferenceClear"]
+
+ assert not data["errors"]
+ assert data["returnSettings"]
+ assert data["returnSettings"]["reasonReferenceType"] is None
+
+ site_settings.refresh_from_db()
+ assert site_settings.return_reason_reference_type is None
+
+
+def test_no_permission_staff(
+ staff_api_client,
+):
+ # when
+ response = staff_api_client.post_graphql(
+ RETURN_REASON_REFERENCE_TYPE_CLEAR_MUTATION
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_no_permission_customer(
+ user_api_client,
+):
+ # when
+ response = user_api_client.post_graphql(RETURN_REASON_REFERENCE_TYPE_CLEAR_MUTATION)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_no_permission_anonymous(
+ api_client,
+):
+ # when
+ response = api_client.post_graphql(RETURN_REASON_REFERENCE_TYPE_CLEAR_MUTATION)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_app_no_permission(
+ app_api_client,
+):
+ # when
+ response = app_api_client.post_graphql(RETURN_REASON_REFERENCE_TYPE_CLEAR_MUTATION)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/shop/tests/mutations/test_return_settings_update.py b/saleor/graphql/shop/tests/mutations/test_return_settings_update.py
new file mode 100644
index 0000000000..e183708115
--- /dev/null
+++ b/saleor/graphql/shop/tests/mutations/test_return_settings_update.py
@@ -0,0 +1,270 @@
+import graphene
+
+from .....page.models import PageType
+from .....site.error_codes import ReturnSettingsErrorCode
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+RETURN_SETTINGS_UPDATE_MUTATION = """
+ mutation returnSettingsUpdate($input: ReturnSettingsUpdateInput!) {
+ returnSettingsUpdate(input: $input) {
+ returnSettings {
+ reasonReferenceType {
+ id
+ name
+ slug
+ }
+ }
+ errors {
+ code
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_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.return_reason_reference_type is None
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"returnReasonReferenceType": page_type_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ RETURN_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnSettingsUpdate"]
+
+ assert not data["errors"]
+ assert data["returnSettings"]
+ assert data["returnSettings"]["reasonReferenceType"]["id"] == page_type_id
+ assert data["returnSettings"]["reasonReferenceType"]["name"] == page_type.name
+ assert data["returnSettings"]["reasonReferenceType"]["slug"] == page_type.slug
+
+ # Verify database update
+ site_settings.refresh_from_db()
+ assert site_settings.return_reason_reference_type == page_type
+
+
+def test_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.return_reason_reference_type is None
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"returnReasonReferenceType": page_type_id}}
+
+ # when
+ response = app_api_client.post_graphql(
+ RETURN_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnSettingsUpdate"]
+
+ assert not data["errors"]
+ assert data["returnSettings"]
+ assert data["returnSettings"]["reasonReferenceType"]["id"] == page_type_id
+
+ # Verify database update
+ site_settings.refresh_from_db()
+ assert site_settings.return_reason_reference_type == page_type
+
+
+def test_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.return_reason_reference_type = initial_page_type
+ site_settings.save()
+
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"returnReasonReferenceType": page_type_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ RETURN_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnSettingsUpdate"]
+
+ assert not data["errors"]
+ assert data["returnSettings"]["reasonReferenceType"]["id"] == page_type_id
+
+ # Verify database update
+ site_settings.refresh_from_db()
+ assert site_settings.return_reason_reference_type == page_type
+
+
+def test_empty_id_returns_error(
+ 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": {"returnReasonReferenceType": ""}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ RETURN_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnSettingsUpdate"]
+
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "returnReasonReferenceType"
+ assert data["errors"][0]["code"] == ReturnSettingsErrorCode.REQUIRED.name
+ assert data["errors"][0]["message"] == "This field is required."
+ assert data["returnSettings"] is None
+
+
+def test_nonexistent_page_type(staff_api_client, permission_manage_settings):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_settings)
+
+ page_type_id = 99999
+ assert not PageType.objects.filter(pk=page_type_id).exists()
+
+ nonexistent_id = graphene.Node.to_global_id("PageType", page_type_id)
+ variables = {"input": {"returnReasonReferenceType": nonexistent_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ RETURN_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnSettingsUpdate"]
+
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "returnReasonReferenceType"
+ assert data["errors"][0]["code"] == ReturnSettingsErrorCode.NOT_FOUND.name
+ assert (
+ data["errors"][0]["message"] == f"Couldn't resolve to a node: {nonexistent_id}"
+ )
+ assert data["returnSettings"] is None
+
+
+def test_wrong_node_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": {"returnReasonReferenceType": product_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ RETURN_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnSettingsUpdate"]
+
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "returnReasonReferenceType"
+ assert data["errors"][0]["code"] == ReturnSettingsErrorCode.GRAPHQL_ERROR.name
+ assert data["returnSettings"] is None
+
+
+def test_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": {"returnReasonReferenceType": "invalid-id-format"}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ RETURN_SETTINGS_UPDATE_MUTATION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["returnSettingsUpdate"]
+
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "returnReasonReferenceType"
+ assert data["errors"][0]["code"] == ReturnSettingsErrorCode.GRAPHQL_ERROR.name
+ assert data["returnSettings"] is None
+
+
+def test_no_permission_staff(staff_api_client, page_type):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"returnReasonReferenceType": page_type_id}}
+
+ # when
+ response = staff_api_client.post_graphql(RETURN_SETTINGS_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_no_permission_customer(user_api_client, page_type):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"returnReasonReferenceType": page_type_id}}
+
+ # when
+ response = user_api_client.post_graphql(RETURN_SETTINGS_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_no_permission_anonymous(api_client, page_type):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"returnReasonReferenceType": page_type_id}}
+
+ # when
+ response = api_client.post_graphql(RETURN_SETTINGS_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_app_no_permission(app_api_client, page_type):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ variables = {"input": {"returnReasonReferenceType": page_type_id}}
+
+ # when
+ response = app_api_client.post_graphql(RETURN_SETTINGS_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 07b7bd1e4d..74c50097a2 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -98,6 +98,22 @@ class RefundSettings(ModelObjectType[site_models.SiteSettings]):
return root.refund_reason_reference_type
+class ReturnSettings(ModelObjectType[site_models.SiteSettings]):
+ reason_reference_type = graphene.Field(
+ PageType,
+ description="Model type used for return reasons." + ADDED_IN_323,
+ )
+
+ class Meta:
+ description = "Return related settings from site settings." + ADDED_IN_323
+ doc_category = DOC_CATEGORY_ORDERS
+ model = site_models.SiteSettings
+
+ @staticmethod
+ def resolve_reason_reference_type(root, info):
+ return root.return_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/__init__.py b/saleor/order/__init__.py
index 0065a8953c..e0693c4a3a 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -2,6 +2,7 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
+ from ..page.models import Page
from .models import FulfillmentLine
@@ -308,6 +309,8 @@ class FulfillmentLineData:
line: "FulfillmentLine"
quantity: int
replace: bool = False
+ reason: str | None = None
+ reason_reference: "Page | None" = None
class StockUpdatePolicy:
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 0ad3936737..d7e61f7a0e 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -73,6 +73,7 @@ from .utils import (
if TYPE_CHECKING:
from ..app.models import App
+ from ..page.models import Page
from ..site.models import SiteSettings
from ..warehouse.models import Warehouse
from ..webhook.models import Webhook
@@ -1386,6 +1387,7 @@ def _move_order_lines_to_target_fulfillment(
target_fulfillment: Fulfillment,
site_settings: "SiteSettings",
requestor: "App | User | None",
+ order_lines_reason_data: dict[UUID, tuple[str | None, "Page | None"]] | None = None,
) -> list[FulfillmentLine]:
"""Move order lines with given quantity to the target fulfillment."""
fulfillment_lines_to_create: list[FulfillmentLine] = []
@@ -1404,11 +1406,19 @@ def _move_order_lines_to_target_fulfillment(
)
line_to_move.quantity_fulfilled += unfulfilled_to_move
+ reason = ""
+ reason_reference = None
+ if order_lines_reason_data and line_to_move.id in order_lines_reason_data:
+ raw_reason, reason_reference = order_lines_reason_data[line_to_move.id]
+ reason = raw_reason or ""
+
fulfillment_line = FulfillmentLine(
fulfillment=target_fulfillment,
order_line_id=line_to_move.id,
stock_id=None,
quantity=unfulfilled_to_move,
+ reason=reason,
+ reason_reference=reason_reference,
)
# update current lines with new value of quantity
@@ -1467,6 +1477,10 @@ def _move_fulfillment_lines_to_target_fulfillment(
moved_line.quantity += fulfilled_to_move
fulfillment_line.quantity -= fulfilled_to_move
+ # Apply return reason data (latest wins when consolidating lines).
+ moved_line.reason = fulfillment_line_data.reason or ""
+ moved_line.reason_reference = fulfillment_line_data.reason_reference
+
if fulfillment_line.quantity == 0:
# the fulfillment line without any items will be deleted
empty_fulfillment_lines_to_delete.append(fulfillment_line)
@@ -1484,7 +1498,10 @@ def _move_fulfillment_lines_to_target_fulfillment(
fulfillment_lines_to_update.append(moved_line)
# update the fulfillment lines with new values
- FulfillmentLine.objects.bulk_update(fulfillment_lines_to_update, ["quantity"])
+ FulfillmentLine.objects.bulk_update(
+ fulfillment_lines_to_update,
+ ["quantity", "reason", "reason_reference"],
+ )
FulfillmentLine.objects.bulk_create(fulfillment_lines_to_create)
# Remove the empty fulfillment lines
@@ -1684,18 +1701,24 @@ def _move_lines_to_return_fulfillment(
shipping_refund_amount: Decimal | None,
site_settings: "SiteSettings",
requestor: "App | User | None",
+ reason: str = "",
+ reason_reference: "Page | None" = None,
+ order_lines_reason_data: dict[UUID, tuple[str | None, "Page | None"]] | None = None,
) -> Fulfillment:
target_fulfillment = Fulfillment.objects.create(
status=fulfillment_status,
order=order,
total_refund_amount=total_refund_amount,
shipping_refund_amount=shipping_refund_amount,
+ reason=reason,
+ reason_reference=reason_reference,
)
lines_in_target_fulfillment = _move_order_lines_to_target_fulfillment(
order_lines_to_move=order_lines,
target_fulfillment=target_fulfillment,
site_settings=site_settings,
requestor=requestor,
+ order_lines_reason_data=order_lines_reason_data,
)
fulfillment_lines_already_refunded = FulfillmentLine.objects.filter(
@@ -1725,7 +1748,10 @@ def _move_lines_to_return_fulfillment(
refund_and_return_fulfillment = target_fulfillment
else:
refund_and_return_fulfillment = Fulfillment.objects.create(
- status=FulfillmentStatus.REFUNDED_AND_RETURNED, order=order
+ status=FulfillmentStatus.REFUNDED_AND_RETURNED,
+ order=order,
+ reason=reason,
+ reason_reference=reason_reference,
)
_move_fulfillment_lines_to_target_fulfillment(
fulfillment_lines_to_move=refunded_fulfillment_lines_to_return,
@@ -1742,15 +1768,22 @@ def _move_lines_to_replace_fulfillment(
order: "Order",
site_settings: "SiteSettings",
requestor: "App | User | None",
+ reason: str = "",
+ reason_reference: "Page | None" = None,
+ order_lines_reason_data: dict[UUID, tuple[str | None, "Page | None"]] | None = None,
) -> Fulfillment:
target_fulfillment = Fulfillment.objects.create(
- status=FulfillmentStatus.REPLACED, order=order
+ status=FulfillmentStatus.REPLACED,
+ order=order,
+ reason=reason,
+ reason_reference=reason_reference,
)
lines_in_target_fulfillment = _move_order_lines_to_target_fulfillment(
order_lines_to_move=order_lines_to_replace,
target_fulfillment=target_fulfillment,
site_settings=site_settings,
requestor=requestor,
+ order_lines_reason_data=order_lines_reason_data,
)
_move_fulfillment_lines_to_target_fulfillment(
fulfillment_lines_to_move=fulfillment_lines_to_replace,
@@ -1769,6 +1802,9 @@ def create_return_fulfillment(
total_refund_amount: Decimal | None,
shipping_refund_amount: Decimal | None,
site_settings: "SiteSettings",
+ reason: str = "",
+ reason_reference: "Page | None" = None,
+ order_lines_reason_data: dict[UUID, tuple[str | None, "Page | None"]] | None = None,
) -> Fulfillment:
status = FulfillmentStatus.RETURNED
if total_refund_amount is not None:
@@ -1783,6 +1819,9 @@ def create_return_fulfillment(
shipping_refund_amount=shipping_refund_amount,
site_settings=site_settings,
requestor=app or user,
+ reason=reason,
+ reason_reference=reason_reference,
+ order_lines_reason_data=order_lines_reason_data,
)
returned_lines: dict[OrderLineIDType, tuple[QuantityType, OrderLine]] = {}
order_lines_with_fulfillment = OrderLine.objects.in_bulk(
@@ -1823,6 +1862,9 @@ def process_replace(
fulfillment_lines: list[FulfillmentLineData],
manager: "PluginsManager",
site_settings: "SiteSettings",
+ reason: str = "",
+ reason_reference: "Page | None" = None,
+ order_lines_reason_data: dict[UUID, tuple[str | None, "Page | None"]] | None = None,
) -> tuple[Fulfillment, Optional["Order"]]:
"""Create replace fulfillment and new draft order.
@@ -1837,6 +1879,9 @@ def process_replace(
order=order,
site_settings=site_settings,
requestor=app or user,
+ reason=reason,
+ reason_reference=reason_reference,
+ order_lines_reason_data=order_lines_reason_data,
)
new_order = create_replace_order(
user=user,
@@ -1873,6 +1918,9 @@ def create_fulfillments_for_returned_products(
refund: bool = False,
amount: Decimal | None = None,
refund_shipping_costs=False,
+ reason: str = "",
+ reason_reference: "Page | None" = None,
+ order_lines_reason_data: dict[UUID, tuple[str | None, "Page | None"]] | None = None,
) -> tuple[Fulfillment, Fulfillment | None, Order | None]:
"""Process the request for replacing or returning the products.
@@ -1929,6 +1977,9 @@ def create_fulfillments_for_returned_products(
fulfillment_lines=replace_fulfillment_lines,
manager=manager,
site_settings=site_settings,
+ reason=reason,
+ reason_reference=reason_reference,
+ order_lines_reason_data=order_lines_reason_data,
)
return_fulfillment = create_return_fulfillment(
user=user,
@@ -1939,6 +1990,9 @@ def create_fulfillments_for_returned_products(
total_refund_amount=total_refund_amount,
shipping_refund_amount=shipping_refund_amount,
site_settings=site_settings,
+ reason=reason,
+ reason_reference=reason_reference,
+ order_lines_reason_data=order_lines_reason_data,
)
Fulfillment.objects.filter(
order=order,
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 5ec02d5b1d..857d780d16 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -44,6 +44,7 @@ class OrderErrorCode(Enum):
class OrderGrantRefundCreateErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
NOT_FOUND = "not_found"
+ NOT_CONFIGURED = "not_configured"
SHIPPING_COSTS_ALREADY_GRANTED = "shipping_costs_already_granted"
AMOUNT_GREATER_THAN_AVAILABLE = "amount_greater_than_available"
REQUIRED = "required"
@@ -53,6 +54,7 @@ class OrderGrantRefundCreateErrorCode(Enum):
class OrderGrantRefundUpdateErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
NOT_FOUND = "not_found"
+ NOT_CONFIGURED = "not_configured"
REQUIRED = "required"
INVALID = "invalid"
AMOUNT_GREATER_THAN_AVAILABLE = "amount_greater_than_available"
@@ -63,12 +65,16 @@ class OrderGrantRefundCreateLineErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
NOT_FOUND = "not_found"
QUANTITY_GREATER_THAN_AVAILABLE = "quantity_greater_than_available"
+ INVALID = "invalid"
+ NOT_CONFIGURED = "not_configured"
class OrderGrantRefundUpdateLineErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
NOT_FOUND = "not_found"
QUANTITY_GREATER_THAN_AVAILABLE = "quantity_greater_than_available"
+ INVALID = "invalid"
+ NOT_CONFIGURED = "not_configured"
class OrderBulkCreateErrorCode(Enum):
diff --git a/saleor/order/migrations/0222_ordergrantedrefundline_reason_reference.py b/saleor/order/migrations/0222_ordergrantedrefundline_reason_reference.py
new file mode 100644
index 0000000000..f6ca1b65d7
--- /dev/null
+++ b/saleor/order/migrations/0222_ordergrantedrefundline_reason_reference.py
@@ -0,0 +1,26 @@
+# Generated by Django 5.2.11 on 2026-03-09 06:06
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0221_remove_digital_orderevents"),
+ ("page", "0031_alter_page_metadata_alter_page_private_metadata_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="ordergrantedrefundline",
+ name="reason_reference",
+ field=models.ForeignKey(
+ blank=True,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="page.page",
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0223_add_reason_to_fulfillment_and_fulfillmentline.py b/saleor/order/migrations/0223_add_reason_to_fulfillment_and_fulfillmentline.py
new file mode 100644
index 0000000000..ac52f262a8
--- /dev/null
+++ b/saleor/order/migrations/0223_add_reason_to_fulfillment_and_fulfillmentline.py
@@ -0,0 +1,72 @@
+# Generated by Django 5.2.14 on 2026-06-02 06:38
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0222_ordergrantedrefundline_reason_reference"),
+ ("page", "0035_page_page_slug_btree_idx"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="fulfillment",
+ name="reason",
+ field=models.TextField(blank=True, default=""),
+ ),
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE order_fulfillment
+ ALTER COLUMN reason
+ SET DEFAULT '';
+ """,
+ reverse_sql="""
+ ALTER TABLE order_fulfillment
+ ALTER COLUMN reason
+ DROP DEFAULT;
+ """,
+ ),
+ migrations.AddField(
+ model_name="fulfillment",
+ name="reason_reference",
+ field=models.ForeignKey(
+ blank=True,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="page.page",
+ ),
+ ),
+ migrations.AddField(
+ model_name="fulfillmentline",
+ name="reason",
+ field=models.TextField(blank=True, default=""),
+ ),
+ migrations.RunSQL(
+ sql="""
+ ALTER TABLE order_fulfillmentline
+ ALTER COLUMN reason
+ SET DEFAULT '';
+ """,
+ reverse_sql="""
+ ALTER TABLE order_fulfillmentline
+ ALTER COLUMN reason
+ DROP DEFAULT;
+ """,
+ ),
+ migrations.AddField(
+ model_name="fulfillmentline",
+ name="reason_reference",
+ field=models.ForeignKey(
+ blank=True,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="page.page",
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0224_fulfillment_reason_ref_idx.py b/saleor/order/migrations/0224_fulfillment_reason_ref_idx.py
new file mode 100644
index 0000000000..ab1d82371c
--- /dev/null
+++ b/saleor/order/migrations/0224_fulfillment_reason_ref_idx.py
@@ -0,0 +1,23 @@
+from django.contrib.postgres.indexes import BTreeIndex
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations
+from django.db.models import Q
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("order", "0223_add_reason_to_fulfillment_and_fulfillmentline"),
+ ]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="fulfillment",
+ index=BTreeIndex(
+ fields=["reason_reference"],
+ name="fulfillment_reason_ref_idx",
+ condition=Q(reason_reference__isnull=False),
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0225_fulfillmentline_reason_ref_idx.py b/saleor/order/migrations/0225_fulfillmentline_reason_ref_idx.py
new file mode 100644
index 0000000000..ee73e78c84
--- /dev/null
+++ b/saleor/order/migrations/0225_fulfillmentline_reason_ref_idx.py
@@ -0,0 +1,23 @@
+from django.contrib.postgres.indexes import BTreeIndex
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations
+from django.db.models import Q
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("order", "0224_fulfillment_reason_ref_idx"),
+ ]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="fulfillmentline",
+ index=BTreeIndex(
+ fields=["reason_reference"],
+ name="fulfillmentline_reason_ref_idx",
+ condition=Q(reason_reference__isnull=False),
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0226_grantedrefundline_reason_ref_idx.py b/saleor/order/migrations/0226_grantedrefundline_reason_ref_idx.py
new file mode 100644
index 0000000000..e148b78f3d
--- /dev/null
+++ b/saleor/order/migrations/0226_grantedrefundline_reason_ref_idx.py
@@ -0,0 +1,23 @@
+from django.contrib.postgres.indexes import BTreeIndex
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations
+from django.db.models import Q
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("order", "0225_fulfillmentline_reason_ref_idx"),
+ ]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="ordergrantedrefundline",
+ index=BTreeIndex(
+ fields=["reason_reference"],
+ name="grantedrefundline_reason_ref_idx",
+ condition=Q(reason_reference__isnull=False),
+ ),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 9cd5b46390..0a68987b50 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -9,7 +9,7 @@ from django.contrib.postgres.indexes import BTreeIndex, GinIndex
from django.contrib.postgres.search import SearchVectorField
from django.core.validators import MinValueValidator
from django.db import connection, models
-from django.db.models import F, JSONField, Max
+from django.db.models import F, JSONField, Max, Q
from django.db.models.expressions import Exists, OuterRef
from django.utils.timezone import now
from django_measurement.models import MeasurementField
@@ -762,6 +762,15 @@ class Fulfillment(ModelWithMetadata):
)
tracking_number = models.CharField(max_length=255, default="", blank=True)
created_at = models.DateTimeField(auto_now_add=True)
+ reason = models.TextField(blank=True, default="")
+ reason_reference = models.ForeignKey(
+ "page.Page",
+ related_name="+",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_index=False,
+ )
shipping_refund_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
@@ -781,6 +790,11 @@ class Fulfillment(ModelWithMetadata):
indexes = [
*ModelWithMetadata.Meta.indexes,
BTreeIndex(fields=["status"], name="fulfillment_status_idx"),
+ BTreeIndex(
+ fields=["reason_reference"],
+ name="fulfillment_reason_ref_idx",
+ condition=Q(reason_reference__isnull=False),
+ ),
]
def __str__(self):
@@ -830,6 +844,24 @@ class FulfillmentLine(models.Model):
blank=True,
null=True,
)
+ reason = models.TextField(blank=True, default="")
+ reason_reference = models.ForeignKey(
+ "page.Page",
+ related_name="+",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_index=False,
+ )
+
+ class Meta:
+ indexes = [
+ BTreeIndex(
+ fields=["reason_reference"],
+ name="fulfillmentline_reason_ref_idx",
+ condition=Q(reason_reference__isnull=False),
+ ),
+ ]
class OrderEvent(models.Model):
@@ -944,3 +976,20 @@ class OrderGrantedRefundLine(models.Model):
)
reason = models.TextField(blank=True, null=True, default="")
+ reason_reference = models.ForeignKey(
+ "page.Page",
+ related_name="+",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_index=False,
+ )
+
+ class Meta:
+ indexes = [
+ BTreeIndex(
+ fields=["reason_reference"],
+ name="grantedrefundline_reason_ref_idx",
+ condition=Q(reason_reference__isnull=False),
+ ),
+ ]
diff --git a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
index 26a28febec..d62fa5863d 100644
--- a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
+++ b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
@@ -3,6 +3,7 @@ from unittest.mock import ANY, patch
from prices import Money, TaxedMoney
+from ...page.models import Page, PageType
from ...payment.interface import RefundData
from ...plugins.manager import get_plugins_manager
from ...warehouse.models import Allocation, Stock
@@ -680,6 +681,104 @@ def test_create_return_fulfillment_with_lines_already_refunded(
mocked_draft_order_created.assert_not_called()
+@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_create_return_fulfillment_with_already_refunded_lines_persists_reason(
+ mocked_order_updated,
+ mocked_draft_order_created,
+ fulfilled_order,
+ staff_user,
+ variant,
+ warehouse,
+ django_capture_on_commit_callbacks,
+ site_settings,
+):
+ # given - a return (without a new refund, so the primary fulfillment status is
+ # RETURNED) that includes an already-refunded line. The already-refunded line is
+ # split into a secondary REFUNDED_AND_RETURNED fulfillment. The order-level reason
+ # must be recorded on both fulfillments.
+ page_type = PageType.objects.create(name="Return Reasons", slug="return-reasons")
+ page = Page.objects.create(
+ slug="damaged-product",
+ title="Damaged Product",
+ page_type=page_type,
+ is_published=True,
+ )
+ reason = "Order-level return reason"
+
+ order_line_ids = fulfilled_order.lines.all().values_list("id", flat=True)
+ fulfillment_lines_to_return = list(
+ FulfillmentLine.objects.filter(order_line_id__in=order_line_ids)
+ )
+
+ stock = Stock.objects.create(
+ warehouse=warehouse, product_variant=variant, quantity=5
+ )
+ channel_listing = variant.channel_listings.get()
+ net = variant.get_price(channel_listing)
+ gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
+ unit_price = TaxedMoney(net=net, gross=gross)
+ order_line = fulfilled_order.lines.create(
+ product_name=str(variant.product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=5,
+ quantity_fulfilled=2,
+ variant=variant,
+ unit_price=unit_price,
+ tax_rate=Decimal("0.23"),
+ total_price=unit_price * 5,
+ )
+ Allocation.objects.create(
+ order_line=order_line, stock=stock, quantity_allocated=order_line.quantity
+ )
+ refunded_fulfillment = Fulfillment.objects.create(
+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED
+ )
+ refunded_fulfillment_line = refunded_fulfillment.lines.create(
+ order_line=order_line, quantity=2
+ )
+
+ fulfillment_lines_to_process = [
+ FulfillmentLineData(line=line, quantity=2)
+ for line in fulfillment_lines_to_return
+ ]
+ fulfillment_lines_to_process.append(
+ FulfillmentLineData(line=refunded_fulfillment_line, quantity=2)
+ )
+
+ # when - returned without a refund
+ with django_capture_on_commit_callbacks(execute=True):
+ create_fulfillments_for_returned_products(
+ user=staff_user,
+ app=None,
+ order=fulfilled_order,
+ payment=None,
+ order_lines=[],
+ fulfillment_lines=fulfillment_lines_to_process,
+ manager=get_plugins_manager(allow_replica=False),
+ site_settings=site_settings,
+ refund=False,
+ reason=reason,
+ reason_reference=page,
+ )
+
+ # then - both produced fulfillments carry the order-level reason
+ returned_fulfillment = Fulfillment.objects.get(
+ order=fulfilled_order, status=FulfillmentStatus.RETURNED
+ )
+ refunded_and_returned_fulfillment = Fulfillment.objects.get(
+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ assert returned_fulfillment.reason == reason
+ assert returned_fulfillment.reason_reference == page
+ assert refunded_and_returned_fulfillment.reason == reason
+ assert refunded_and_returned_fulfillment.reason_reference == page
+
+
@patch("saleor.plugins.manager.PluginsManager.draft_order_created")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.payment.gateway.refund")
diff --git a/saleor/site/error_codes.py b/saleor/site/error_codes.py
index c25755771c..2b801d68da 100644
--- a/saleor/site/error_codes.py
+++ b/saleor/site/error_codes.py
@@ -20,3 +20,10 @@ class RefundSettingsErrorCode(Enum):
INVALID = "invalid"
REQUIRED = "required"
GRAPHQL_ERROR = "graphql_error"
+
+
+class ReturnSettingsErrorCode(Enum):
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ REQUIRED = "required"
+ GRAPHQL_ERROR = "graphql_error"
diff --git a/saleor/site/migrations/0049_alter_sitesettings_refund_reason_reference_type.py b/saleor/site/migrations/0049_alter_sitesettings_refund_reason_reference_type.py
new file mode 100644
index 0000000000..424bc5d60c
--- /dev/null
+++ b/saleor/site/migrations/0049_alter_sitesettings_refund_reason_reference_type.py
@@ -0,0 +1,25 @@
+# Generated by Django 5.2.11 on 2026-03-09 00:00
+
+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", "0048_sitesettings_include_shipping_zones_in_stock_availability"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="sitesettings",
+ name="refund_reason_reference_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="page.pagetype",
+ ),
+ ),
+ ]
diff --git a/saleor/site/migrations/0050_sitesettings_return_reason_reference_type.py b/saleor/site/migrations/0050_sitesettings_return_reason_reference_type.py
new file mode 100644
index 0000000000..26d739e5a0
--- /dev/null
+++ b/saleor/site/migrations/0050_sitesettings_return_reason_reference_type.py
@@ -0,0 +1,25 @@
+# Generated by Django 5.2.11 on 2026-03-09 00:00
+
+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", "0049_alter_sitesettings_refund_reason_reference_type"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sitesettings",
+ name="return_reason_reference_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="page.pagetype",
+ ),
+ ),
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 146f8a32bb..6c59362d57 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -105,7 +105,20 @@ class SiteSettings(ModelWithMetadata):
# refund settings
refund_reason_reference_type = models.ForeignKey(
- null=True, blank=True, on_delete=models.SET_NULL, to="page.PageType"
+ null=True,
+ blank=True,
+ on_delete=models.SET_NULL,
+ to="page.PageType",
+ related_name="+",
+ )
+
+ # return settings
+ return_reason_reference_type = models.ForeignKey(
+ null=True,
+ blank=True,
+ on_delete=models.SET_NULL,
+ to="page.PageType",
+ related_name="+",
)
# usage telemetry