Skip to content

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

Include transaction item in refund flow (#15590)

Maciej Korycinskif7b3cb5f512f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0817889b10..caa81dc778 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ All notable, unreleased changes to this project will be documented in this file.
# 3.20.0 [Unreleased]
### Highlights
+- Include transaction item in refund flow - #15590 by @korycins
### Breaking changes
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index 3a6f244a39..7222ce07ae 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -13,7 +13,7 @@ from ...order.models import (
OrderGrantedRefundLine,
OrderLine,
)
-from ...payment.models import TransactionItem
+from ...payment.models import TransactionEvent, TransactionItem
from ...warehouse.models import Allocation
from ..core.dataloaders import DataLoader
@@ -234,3 +234,18 @@ class TransactionItemsByOrderIDLoader(DataLoader):
for transaction in transactions:
transactions_map[transaction.order_id].append(transaction)
return [transactions_map.get(order_id, []) for order_id in keys]
+
+
+class TransactionEventsByOrderGrantedRefundIdLoader(DataLoader):
+ context_key = "transaction_event_by_order_granted_refund_id"
+
+ def batch_load(self, keys):
+ events = (
+ TransactionEvent.objects.using(self.database_connection_name)
+ .filter(related_granted_refund__in=keys)
+ .order_by("-created_at")
+ )
+ event_map = defaultdict(list)
+ for event in events:
+ event_map[event.related_granted_refund_id].append(event)
+ return [event_map.get(granted_refund_id, []) for granted_refund_id in keys]
diff --git a/saleor/graphql/order/enums.py b/saleor/graphql/order/enums.py
index e79e81a99d..f8df9fd656 100644
--- a/saleor/graphql/order/enums.py
+++ b/saleor/graphql/order/enums.py
@@ -6,6 +6,7 @@ from ...order import (
OrderChargeStatus,
OrderEvents,
OrderEventsEmails,
+ OrderGrantedRefundStatus,
OrderOrigin,
OrderStatus,
StockUpdatePolicy,
@@ -69,6 +70,12 @@ OrderGrantRefundUpdateErrorCode = graphene.Enum.from_enum(
OrderGrantRefundUpdateErrorCode.doc_category = DOC_CATEGORY_ORDERS
+OrderGrantedRefundStatusEnum = to_enum(
+ OrderGrantedRefundStatus, description=OrderGrantedRefundStatus.__doc__
+)
+OrderGrantedRefundStatusEnum.doc_category = DOC_CATEGORY_ORDERS
+
+
class OrderStatusFilter(BaseEnum):
READY_TO_FULFILL = "ready_to_fulfill"
READY_TO_CAPTURE = "ready_to_capture"
diff --git a/saleor/graphql/order/mutations/order_grant_refund_create.py b/saleor/graphql/order/mutations/order_grant_refund_create.py
index f1c771e715..8b8440bdbf 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_create.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_create.py
@@ -9,12 +9,18 @@ from ....order import models
from ....order.utils import update_order_charge_data
from ....permission.enums import OrderPermissions
from ...core import ResolveInfo
-from ...core.descriptions import ADDED_IN_313, ADDED_IN_315, PREVIEW_FEATURE
+from ...core.descriptions import (
+ ADDED_IN_313,
+ ADDED_IN_315,
+ ADDED_IN_320,
+ 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 ..enums import OrderGrantRefundCreateErrorCode, OrderGrantRefundCreateLineErrorCode
from ..types import Order, OrderGrantedRefund
from .order_grant_refund_utils import (
@@ -81,6 +87,20 @@ class OrderGrantRefundCreateInput(BaseInputObjectType):
+ PREVIEW_FEATURE,
required=False,
)
+ transaction_id = graphene.ID(
+ description=(
+ "The ID of the transaction item related to the granted refund. "
+ "If `amount` provided in the input, the transaction.chargedAmount needs to "
+ "be equal or greater than provided `amount`."
+ "If `amount` is not provided in the input and calculated automatically by "
+ "Saleor, the `min(calculatedAmount, transaction.chargedAmount)` will be "
+ "used."
+ "Field will be required starting from Saleor 3.21."
+ + ADDED_IN_320
+ + PREVIEW_FEATURE
+ ),
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -179,11 +199,13 @@ class OrderGrantRefundCreate(BaseMutation):
@classmethod
def clean_input(
cls,
+ info: ResolveInfo,
order: models.Order,
input: dict[str, Any],
):
amount = input.get("amount")
reason = input.get("reason") or ""
+ transaction_id = input.get("transaction_id")
input_lines = input.get("lines", [])
grant_refund_for_shipping = input.get("grant_refund_for_shipping", None)
@@ -191,14 +213,16 @@ class OrderGrantRefundCreate(BaseMutation):
cleaned_input_lines: list[models.OrderGrantedRefundLine] = []
if input_lines:
- cleaned_input_lines, errors = cls.clean_input_lines(order, input_lines)
- if errors:
+ cleaned_input_lines, lines_errors = cls.clean_input_lines(
+ order, input_lines
+ )
+ if lines_errors:
raise ValidationError(
{
"lines": ValidationError(
"Provided input for lines is invalid.",
code=OrderGrantRefundCreateErrorCode.INVALID.value,
- params={"lines": errors},
+ params={"lines": lines_errors},
),
}
)
@@ -213,16 +237,43 @@ class OrderGrantRefundCreate(BaseMutation):
}
)
+ max_grant_amount = None
+ transaction_item = None
+ if transaction_id is not None:
+ transaction_item = get_transaction_item(
+ id=transaction_id,
+ token=None,
+ error_field_name="transaction_id",
+ qs=order.payment_transactions.all(),
+ )
+ max_grant_amount = transaction_item.charged_value
+
if amount is None:
amount = cls.calculate_amount(
order, cleaned_input_lines, grant_refund_for_shipping
)
+ if max_grant_amount is not None:
+ amount = min(amount, max_grant_amount)
+ elif max_grant_amount is not None and amount > max_grant_amount:
+ error_code = (
+ OrderGrantRefundCreateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.value
+ )
+ raise ValidationError(
+ {
+ "amount": ValidationError(
+ "Amount cannot be greater than the charged amount of provided "
+ "transaction.",
+ code=error_code,
+ )
+ }
+ )
return {
"amount": amount,
"reason": reason,
"lines": cleaned_input_lines,
"grant_refund_for_shipping": grant_refund_for_shipping,
+ "transaction_item": transaction_item,
}
@classmethod
@@ -230,11 +281,12 @@ class OrderGrantRefundCreate(BaseMutation):
cls, _root, info: ResolveInfo, /, *, id, input
):
order = cls.get_node_or_error(info, id, only_type=Order)
- cleaned_input = cls.clean_input(order, input)
+ cleaned_input = cls.clean_input(info, order, input)
amount = cleaned_input["amount"]
reason = cleaned_input["reason"]
cleaned_input_lines = cleaned_input["lines"]
grant_refund_for_shipping = cleaned_input["grant_refund_for_shipping"]
+ transaction_item = cleaned_input["transaction_item"]
with transaction.atomic():
granted_refund = order.granted_refunds.create(
@@ -244,6 +296,7 @@ class OrderGrantRefundCreate(BaseMutation):
user=info.context.user,
app=info.context.app,
shipping_costs_included=grant_refund_for_shipping or False,
+ transaction_item=transaction_item,
)
if cleaned_input_lines:
for line in cleaned_input_lines:
diff --git a/saleor/graphql/order/mutations/order_grant_refund_update.py b/saleor/graphql/order/mutations/order_grant_refund_update.py
index 24ce07ed10..d4fdebb6af 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_update.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_update.py
@@ -1,21 +1,27 @@
-from typing import Any, Union
+from typing import Any, Union, cast
import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
from graphql import GraphQLError
-from ....order import models
+from ....order import OrderGrantedRefundStatus, models
from ....order.utils import update_order_charge_data
from ....permission.enums import OrderPermissions
from ...core import ResolveInfo
-from ...core.descriptions import ADDED_IN_313, ADDED_IN_315, PREVIEW_FEATURE
+from ...core.descriptions import (
+ ADDED_IN_313,
+ ADDED_IN_315,
+ ADDED_IN_320,
+ 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 ...core.utils import from_global_id_or_error
+from ...payment.types import TransactionItem
from ..enums import OrderGrantRefundUpdateErrorCode, OrderGrantRefundUpdateLineErrorCode
from ..types import Order, OrderGrantedRefund
from .order_grant_refund_utils import (
@@ -97,6 +103,20 @@ class OrderGrantRefundUpdateInput(BaseInputObjectType):
+ PREVIEW_FEATURE,
required=False,
)
+ transaction_id = graphene.ID(
+ description=(
+ "The ID of the transaction item related to the granted refund. "
+ "If `amount` provided in the input, the transaction.chargedAmount needs to "
+ "be equal or greater than provided `amount`."
+ "If `amount` is not provided in the input and calculated automatically by "
+ "Saleor, the `min(calculatedAmount, transaction.chargedAmount)` will be "
+ "used."
+ "Field will be required starting from Saleor 3.21."
+ + ADDED_IN_320
+ + PREVIEW_FEATURE
+ ),
+ required=False,
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -124,18 +144,22 @@ class OrderGrantRefundUpdate(BaseMutation):
doc_category = DOC_CATEGORY_ORDERS
@classmethod
- def validate_input(cls, input: dict[str, Any]):
+ def validate_input(
+ cls, input: dict[str, Any], granted_refund: models.OrderGrantedRefund
+ ):
amount = input.get("amount")
reason = input.get("reason")
input_lines = input.get("add_lines", [])
remove_lines = input.get("remove_lines", [])
grant_refund_for_shipping = input.get("grant_refund_for_shipping", False)
+ transaction_id = input.get("transaction_id")
if (
amount is None
and reason is None
and not input_lines
and not grant_refund_for_shipping
and not remove_lines
+ and not transaction_id
):
error_msg = "At least one field needs to be provided to process update."
raise ValidationError(
@@ -145,6 +169,27 @@ class OrderGrantRefundUpdate(BaseMutation):
)
}
)
+ only_reason_provided = reason is not None and len(input) == 1
+ if (
+ granted_refund.status
+ in [OrderGrantedRefundStatus.PENDING, OrderGrantedRefundStatus.SUCCESS]
+ and not only_reason_provided
+ ):
+ fields_from_input = set(input.keys())
+ if "reason" in fields_from_input:
+ fields_from_input.remove("reason")
+ error_msg = (
+ "Only reason can be updated when `OrderGrantedRefund.status` is PENDING"
+ " or SUCCESS."
+ )
+ raise ValidationError(
+ {
+ error_field: ValidationError(
+ error_msg, code=OrderGrantRefundUpdateErrorCode.INVALID.value
+ )
+ for error_field in fields_from_input
+ }
+ )
@classmethod
def clean_remove_lines(
@@ -216,16 +261,18 @@ class OrderGrantRefundUpdate(BaseMutation):
@classmethod
def clean_input(
cls,
+ info: ResolveInfo,
granted_refund: models.OrderGrantedRefund,
input: dict[str, Any],
):
add_errors: list[dict[str, Any]] = []
remove_errors: list[dict[str, Any]] = []
errors = {}
- cls.validate_input(input)
+ cls.validate_input(input, granted_refund)
order = granted_refund.order
amount = input.get("amount")
reason = input.get("reason", None)
+ transaction_id = input.get("transaction_id")
add_lines = input.get("add_lines", [])
remove_lines = input.get("remove_lines", [])
grant_refund_for_shipping = input.get("grant_refund_for_shipping", None)
@@ -258,23 +305,68 @@ class OrderGrantRefundUpdate(BaseMutation):
params={"add_lines": add_errors},
)
- if grant_refund_for_shipping and shipping_costs_already_granted(order):
+ if grant_refund_for_shipping and shipping_costs_already_granted(
+ order, grant_refund_pk_to_exclude=granted_refund.pk
+ ):
error_code = OrderGrantRefundUpdateErrorCode.SHIPPING_COSTS_ALREADY_GRANTED
errors["grant_refund_for_shipping"] = ValidationError(
"Shipping costs have already been granted.",
code=error_code.value,
)
+ transaction_item = granted_refund.transaction_item
+ if transaction_id is not None:
+ transaction_item = cls.get_node_or_error(
+ info, transaction_id, only_type=TransactionItem
+ )
+
+ amount_not_changed = (
+ not add_lines
+ and not remove_lines
+ and amount is None
+ and not grant_refund_for_shipping
+ )
+
+ # if transaction item is assigned, we need to validate if the provider amount is
+ # not greater than the current charged amount of the transaction.
+ if transaction_item and amount is not None:
+ if amount > transaction_item.charged_value:
+ code = (
+ OrderGrantRefundUpdateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.value
+ )
+ errors["amount"] = ValidationError(
+ "Amount cannot be greater than the charged amount of provided "
+ "transaction.",
+ code=code,
+ )
+ # if transaction id is provided in the input, we need to validate if the
+ # provided transaction have enough charged amount to cover the granted
+ # refund.
+ elif transaction_id and transaction_item and amount_not_changed:
+ amount = granted_refund.amount_value
+ charged_value = cast(Decimal, transaction_item.charged_value)
+ if amount > charged_value:
+ code = (
+ OrderGrantRefundUpdateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.value
+ )
+ errors["transaction_id"] = ValidationError(
+ "Provided transaction does not have enough charged amount to cover"
+ " the granted refund.",
+ code=code,
+ )
+
if errors:
raise ValidationError(errors)
- return {
+ cleaned_input = {
"amount": amount,
"reason": reason,
"add_lines": lines_to_add,
"remove_lines": line_ids_to_remove,
"grant_refund_for_shipping": grant_refund_for_shipping,
+ "transaction_item": transaction_item,
}
+ return cleaned_input
@classmethod
def process_update_for_granted_refund(
@@ -289,6 +381,9 @@ class OrderGrantRefundUpdate(BaseMutation):
if grant_refund_for_shipping is not None:
granted_refund.shipping_costs_included = grant_refund_for_shipping
+ transaction_item = cleaned_input.get("transaction_item")
+ if transaction_item:
+ granted_refund.transaction_item = transaction_item
with transaction.atomic():
if lines_to_remove:
granted_refund.lines.filter(id__in=lines_to_remove).delete()
@@ -310,6 +405,8 @@ class OrderGrantRefundUpdate(BaseMutation):
)
if granted_refund.shipping_costs_included:
amount += order.shipping_price_gross_amount
+ if transaction_item:
+ amount = min(amount, transaction_item.charged_value)
granted_refund.amount_value = amount
reason = cleaned_input.get("reason")
@@ -322,6 +419,7 @@ class OrderGrantRefundUpdate(BaseMutation):
"reason",
"shipping_costs_included",
"updated_at",
+ "transaction_item",
]
)
@@ -329,10 +427,15 @@ class OrderGrantRefundUpdate(BaseMutation):
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, id, input
):
- granted_refund = cls.get_node_or_error(info, id, only_type=OrderGrantedRefund)
+ granted_refund = cls.get_node_or_error(
+ info,
+ id,
+ only_type=OrderGrantedRefund,
+ qs=models.OrderGrantedRefund.objects.select_related("transaction_item"),
+ )
order = granted_refund.order
- cleaned_input = cls.clean_input(granted_refund, input)
+ cleaned_input = cls.clean_input(info, granted_refund, input)
cls.process_update_for_granted_refund(order, granted_refund, cleaned_input)
update_order_charge_data(order)
return cls(order=order, granted_refund=granted_refund)
diff --git a/saleor/graphql/order/mutations/order_grant_refund_utils.py b/saleor/graphql/order/mutations/order_grant_refund_utils.py
index dad9f306bb..718771f34b 100644
--- a/saleor/graphql/order/mutations/order_grant_refund_utils.py
+++ b/saleor/graphql/order/mutations/order_grant_refund_utils.py
@@ -9,8 +9,13 @@ from ....order import models
from ...core.utils import from_global_id_or_error
-def shipping_costs_already_granted(order: models.Order):
- if order.granted_refunds.filter(shipping_costs_included=True):
+def shipping_costs_already_granted(
+ order: models.Order, grant_refund_pk_to_exclude=None
+):
+ qs = order.granted_refunds.filter(shipping_costs_included=True)
+ if grant_refund_pk_to_exclude:
+ qs = qs.exclude(pk=grant_refund_pk_to_exclude)
+ if qs.exists():
return True
return False
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 de23c8e5bd..217ee73b2b 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
@@ -9,6 +9,7 @@ from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import (
OrderChargeStatusEnum,
+ OrderGrantedRefundStatusEnum,
OrderGrantRefundCreateErrorCode,
OrderGrantRefundCreateLineErrorCode,
)
@@ -41,6 +42,13 @@ mutation OrderGrantRefundCreate(
quantity
reason
}
+ status
+ transactionEvents{
+ id
+ }
+ transaction{
+ id
+ }
}
order{
id
@@ -68,6 +76,13 @@ mutation OrderGrantRefundCreate(
quantity
reason
}
+ status
+ transactionEvents{
+ id
+ }
+ transaction{
+ id
+ }
}
}
errors{
@@ -130,6 +145,13 @@ def test_grant_refund_by_user(
)
assert not granted_refund_assigned_to_order["app"]
+ assert (
+ granted_refund_assigned_to_order["status"]
+ == OrderGrantedRefundStatusEnum.NONE.name
+ )
+ assert granted_refund_assigned_to_order["transactionEvents"] == []
+ assert not granted_refund_assigned_to_order["transaction"]
+
@pytest.mark.parametrize("reason", ["", "Reason", None])
def test_grant_refund_by_app(reason, app_api_client, permission_manage_orders, order):
@@ -170,6 +192,10 @@ def test_grant_refund_by_app(reason, app_api_client, permission_manage_orders, o
== to_global_id_or_none(granted_refund_from_db.app)
)
+ assert granted_refund["status"] == OrderGrantedRefundStatusEnum.NONE.name
+ assert granted_refund["transactionEvents"] == []
+ assert not granted_refund["transaction"]
+
def test_grant_refund_by_app_missing_permission(app_api_client, order):
# given
@@ -726,3 +752,208 @@ def test_grant_refund_updates_order_charge_status(
assert len(data["order"]["grantedRefunds"]) == 1
assert data["order"]["chargeStatus"] == OrderChargeStatusEnum.OVERCHARGED.name
+
+
+def test_grant_refund_with_transaction_item_and_without_input_amount(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ expected_granted_amount = Decimal("1.23")
+ transaction_item = transaction_item_generator(
+ charged_value=expected_granted_amount, order_id=order.id
+ )
+ order_id = to_global_id_or_none(order)
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ first_line = order.lines.first()
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ expected_reason = "Reason"
+ variables = {
+ "id": order_id,
+ "input": {
+ "transactionId": transaction_item_id,
+ "lines": [
+ {
+ "id": to_global_id_or_none(first_line),
+ "quantity": 1,
+ "reason": expected_reason,
+ },
+ ],
+ },
+ }
+
+ # 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
+
+ granted_refund_from_db = order.granted_refunds.first()
+ assert granted_refund_from_db.amount_value == expected_granted_amount
+ assert granted_refund_from_db.transaction_item == transaction_item
+
+ assert order_id == data["order"]["id"]
+ assert len(data["order"]["grantedRefunds"]) == 1
+
+ order_granted_refund = data["order"]["grantedRefunds"][0]
+ assert data["grantedRefund"]["shippingCostsIncluded"] is False
+ assert len(order_granted_refund["lines"]) == 1
+ assert order_granted_refund["lines"][0]["quantity"] == 1
+ assert order_granted_refund["lines"][0]["orderLine"]["id"] == to_global_id_or_none(
+ first_line
+ )
+ assert order_granted_refund["lines"][0]["reason"] == expected_reason
+
+ assert order_granted_refund["status"] == OrderGrantedRefundStatusEnum.NONE.name
+ assert order_granted_refund["transactionEvents"] == []
+ assert order_granted_refund["transaction"]["id"] == transaction_item_id
+
+ assert quantize_price(
+ granted_refund_from_db.amount_value, order.currency
+ ) == quantize_price(
+ Decimal(order_granted_refund["amount"]["amount"]), order.currency
+ )
+ granted_refund_line = granted_refund_from_db.lines.first()
+ assert granted_refund_line.order_line == first_line
+ assert granted_refund_line.quantity == 1
+ assert granted_refund_line.reason == expected_reason
+
+
+def test_grant_refund_with_transaction_item_and_amount_greater_than_charged_amount(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ expected_granted_amount = Decimal("1.23")
+ transaction_item = transaction_item_generator(
+ charged_value=expected_granted_amount, order_id=order.id
+ )
+ order_id = to_global_id_or_none(order)
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ first_line = order.lines.first()
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ expected_reason = "Reason"
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": expected_granted_amount + 1,
+ "transactionId": transaction_item_id,
+ "lines": [
+ {
+ "id": to_global_id_or_none(first_line),
+ "quantity": 1,
+ "reason": expected_reason,
+ },
+ ],
+ },
+ }
+
+ # 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["code"]
+ == OrderGrantRefundCreateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.name
+ )
+ assert error["field"] == "amount"
+
+
[email protected]("expected_granted_amount", [Decimal("1.23"), Decimal("1.00")])
+def test_grant_refund_with_transaction_item_and_amount(
+ expected_granted_amount,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ expected_charged_amount = Decimal("1.23")
+ transaction_item = transaction_item_generator(
+ charged_value=expected_charged_amount, order_id=order.id
+ )
+ order_id = to_global_id_or_none(order)
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ first_line = order.lines.first()
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ expected_reason = "Reason"
+ variables = {
+ "id": order_id,
+ "input": {
+ "amount": expected_granted_amount,
+ "transactionId": transaction_item_id,
+ "lines": [
+ {
+ "id": to_global_id_or_none(first_line),
+ "quantity": 1,
+ "reason": expected_reason,
+ },
+ ],
+ },
+ }
+
+ # 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
+
+ granted_refund_from_db = order.granted_refunds.first()
+ assert granted_refund_from_db.amount_value == expected_granted_amount
+ assert granted_refund_from_db.transaction_item == transaction_item
+
+ assert order_id == data["order"]["id"]
+ assert len(data["order"]["grantedRefunds"]) == 1
+
+ order_granted_refund = data["order"]["grantedRefunds"][0]
+ assert data["grantedRefund"]["shippingCostsIncluded"] is False
+ assert len(order_granted_refund["lines"]) == 1
+ assert order_granted_refund["lines"][0]["quantity"] == 1
+ assert order_granted_refund["lines"][0]["orderLine"]["id"] == to_global_id_or_none(
+ first_line
+ )
+ assert order_granted_refund["lines"][0]["reason"] == expected_reason
+
+ assert order_granted_refund["status"] == OrderGrantedRefundStatusEnum.NONE.name
+ assert order_granted_refund["transactionEvents"] == []
+ assert order_granted_refund["transaction"]["id"] == transaction_item_id
+
+ assert quantize_price(
+ granted_refund_from_db.amount_value, order.currency
+ ) == quantize_price(
+ Decimal(order_granted_refund["amount"]["amount"]), order.currency
+ )
+ granted_refund_line = granted_refund_from_db.lines.first()
+ assert granted_refund_line.order_line == first_line
+ assert granted_refund_line.quantity == 1
+ assert granted_refund_line.reason == expected_reason
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 b0d9051231..f0acff9459 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
@@ -1,8 +1,10 @@
from decimal import Decimal
+import graphene
import pytest
from .....core.prices import quantize_price
+from .....order import OrderGrantedRefundStatus
from .....order.utils import update_order_charge_data
from ....core.utils import to_global_id_or_none
from ....tests.utils import (
@@ -12,6 +14,7 @@ from ....tests.utils import (
)
from ...enums import (
OrderChargeStatusEnum,
+ OrderGrantedRefundStatusEnum,
OrderGrantRefundUpdateErrorCode,
OrderGrantRefundUpdateLineErrorCode,
)
@@ -44,6 +47,13 @@ mutation OrderGrantRefundUpdate(
quantity
reason
}
+ status
+ transactionEvents{
+ id
+ }
+ transaction{
+ id
+ }
}
order {
id
@@ -70,6 +80,13 @@ mutation OrderGrantRefundUpdate(
quantity
reason
}
+ status
+ transactionEvents{
+ id
+ }
+ transaction{
+ id
+ }
}
}
errors {
@@ -142,6 +159,12 @@ def test_grant_refund_update_by_user(
assert granted_refund_assigned_to_order["app"]["id"] == to_global_id_or_none(
granted_refund.app
)
+ assert (
+ granted_refund_assigned_to_order["status"]
+ == OrderGrantedRefundStatusEnum.NONE.name
+ )
+ assert granted_refund_assigned_to_order["transactionEvents"] == []
+ assert not granted_refund_assigned_to_order["transaction"]
@pytest.mark.parametrize("amount", [Decimal("0.00"), Decimal("20.00")])
@@ -324,6 +347,12 @@ def test_grant_refund_update_by_app(
assert granted_refund_assigned_to_order["user"]["id"] == to_global_id_or_none(
granted_refund.user
)
+ assert (
+ granted_refund_assigned_to_order["status"]
+ == OrderGrantedRefundStatusEnum.NONE.name
+ )
+ assert granted_refund_assigned_to_order["transactionEvents"] == []
+ assert not granted_refund_assigned_to_order["transaction"]
@pytest.mark.parametrize("amount", [Decimal("0.00"), Decimal("20.00")])
@@ -463,8 +492,13 @@ def test_grant_refund_update_by_app_missing_input(
assert errors[0]["field"] == "input"
[email protected]("current_include_shipping", [True, False])
def test_grant_refund_update_include_grant_refund_for_shipping(
- app_api_client, staff_user, permission_manage_orders, order_with_lines
+ current_include_shipping,
+ app_api_client,
+ staff_user,
+ permission_manage_orders,
+ order_with_lines,
):
# given
current_reason = "Granted refund reason."
@@ -474,6 +508,7 @@ def test_grant_refund_update_include_grant_refund_for_shipping(
currency=order_with_lines.currency,
reason=current_reason,
user=staff_user,
+ shipping_costs_included=current_include_shipping,
)
granted_refund_id = to_global_id_or_none(granted_refund)
app_api_client.app.permissions.set([permission_manage_orders])
@@ -1277,3 +1312,1000 @@ def test_grant_refund_updates_order_charge_status(
assert len(data["order"]["grantedRefunds"]) == 1
assert order.charge_status == OrderChargeStatusEnum.FULL.value
+
+
+def test_grant_refund_update_with_transaction_item(
+ staff_api_client, app, permission_manage_orders, order, transaction_item_generator
+):
+ # given
+ transaction_item = transaction_item_generator(
+ order_id=order.id, charged_value=Decimal("22.00")
+ )
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+ updated_at = granted_refund.updated_at
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+ variables = {
+ "id": granted_refund_id,
+ "input": {"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"]
+ assert not data["errors"]
+
+ assert data["order"]["id"] == to_global_id_or_none(order)
+ assert len(data["order"]["grantedRefunds"]) == 1
+
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ assert updated_at.isoformat() != data["grantedRefund"]["updatedAt"]
+ granted_refund.refresh_from_db()
+ assert granted_refund.transaction_item == transaction_item
+ assert granted_refund.updated_at.isoformat() == data["grantedRefund"]["updatedAt"]
+ assert (
+ granted_refund_assigned_to_order["amount"]["amount"]
+ == granted_refund.amount_value
+ )
+ assert granted_refund_assigned_to_order["reason"] == granted_refund.reason
+ assert granted_refund_assigned_to_order["app"]["id"] == to_global_id_or_none(
+ granted_refund.app
+ )
+ assert (
+ granted_refund_assigned_to_order["status"]
+ == OrderGrantedRefundStatusEnum.NONE.name
+ )
+ assert granted_refund_assigned_to_order["transactionEvents"] == []
+ assert granted_refund_assigned_to_order["transaction"]["id"] == transaction_item_id
+
+
[email protected]("expected_granted_amount", [Decimal("2.00"), Decimal("1.00")])
+def test_grant_refund_update_with_transaction_and_correct_amount(
+ expected_granted_amount,
+ staff_api_client,
+ app,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+):
+ # given
+ transaction_item = transaction_item_generator(
+ order_id=order.id, charged_value=Decimal("2.00")
+ )
+ current_reason = "Granted refund reason."
+ granted_refund = order.granted_refunds.create(
+ amount_value=expected_granted_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+ updated_at = granted_refund.updated_at
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ transaction_item_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "transactionId": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+ },
+ }
+
+ # 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"]
+
+ assert data["order"]["id"] == to_global_id_or_none(order)
+ assert len(data["order"]["grantedRefunds"]) == 1
+
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ assert updated_at.isoformat() != data["grantedRefund"]["updatedAt"]
+ granted_refund.refresh_from_db()
+ assert granted_refund.transaction_item == transaction_item
+ assert granted_refund.updated_at.isoformat() == data["grantedRefund"]["updatedAt"]
+ assert (
+ granted_refund_assigned_to_order["amount"]["amount"]
+ == granted_refund.amount_value
+ )
+ assert granted_refund_assigned_to_order["reason"] == granted_refund.reason
+ assert granted_refund_assigned_to_order["app"]["id"] == to_global_id_or_none(
+ granted_refund.app
+ )
+ assert (
+ granted_refund_assigned_to_order["status"]
+ == OrderGrantedRefundStatusEnum.NONE.name
+ )
+ assert granted_refund_assigned_to_order["transactionEvents"] == []
+ assert granted_refund_assigned_to_order["transaction"]["id"] == transaction_item_id
+
+
+def test_grant_refund_update_with_input_amount_greater_than_transaction_charged_amount(
+ staff_api_client, app, permission_manage_orders, order, transaction_item_generator
+):
+ # given
+ charged_value = Decimal("10.00")
+ transaction_item = transaction_item_generator(
+ order_id=order.id, charged_value=charged_value
+ )
+ current_reason = "Granted refund 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)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": charged_value + Decimal("1.00"),
+ "transactionId": transaction_id,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "amount"
+ assert (
+ error["code"]
+ == OrderGrantRefundUpdateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.name
+ )
+
+
+def test_grant_refund_update_with_transaction_granted_amount_is_bigger_than_charged(
+ staff_api_client, app, permission_manage_orders, order, transaction_item_generator
+):
+ # given
+ charged_value = Decimal("0.00")
+ transaction_item = transaction_item_generator(
+ order_id=order.id, charged_value=charged_value
+ )
+ current_reason = "Granted refund 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)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {"transactionId": transaction_id},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "transactionId"
+ assert (
+ error["code"]
+ == OrderGrantRefundUpdateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.name
+ )
+
+
[email protected]("input_amount", [Decimal("1.00"), Decimal("2.00")])
+def test_grant_refund_update_with_correct_input_amount_to_transaction_charged_amount(
+ input_amount,
+ staff_api_client,
+ app,
+ permission_manage_orders,
+ order,
+ transaction_item_generator,
+):
+ # given
+ transaction_item = transaction_item_generator(
+ order_id=order.id, charged_value=Decimal("2.00")
+ )
+ current_reason = "Granted refund reason."
+ granted_refund = order.granted_refunds.create(
+ amount_value=Decimal("0.50"),
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+ updated_at = granted_refund.updated_at
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {"transactionId": transaction_id, "amount": input_amount},
+ }
+
+ # 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"]
+
+ assert data["order"]["id"] == to_global_id_or_none(order)
+ assert len(data["order"]["grantedRefunds"]) == 1
+
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ assert updated_at.isoformat() != data["grantedRefund"]["updatedAt"]
+ granted_refund.refresh_from_db()
+ assert granted_refund.transaction_item == transaction_item
+ assert granted_refund.updated_at.isoformat() == data["grantedRefund"]["updatedAt"]
+ assert (
+ granted_refund_assigned_to_order["amount"]["amount"]
+ == granted_refund.amount_value
+ )
+ assert granted_refund_assigned_to_order["reason"] == granted_refund.reason
+ assert granted_refund_assigned_to_order["app"]["id"] == to_global_id_or_none(
+ granted_refund.app
+ )
+ assert (
+ granted_refund_assigned_to_order["status"]
+ == OrderGrantedRefundStatusEnum.NONE.name
+ )
+ assert granted_refund_assigned_to_order["transactionEvents"] == []
+ assert granted_refund_assigned_to_order["transaction"]["id"] == transaction_id
+
+
+def test_grant_refund_update_with_transaction_and_add_lines(
+ transaction_item_generator,
+ app_api_client,
+ staff_user,
+ permission_manage_orders,
+ order_with_lines,
+):
+ # 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("10.00")
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order_with_lines.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+ order_line = order_with_lines.lines.first()
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ expected_quantity = 1
+ expected_reason = "Reason"
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "transactionId": transaction_id,
+ "addLines": [
+ {
+ "id": to_global_id_or_none(order_line),
+ "quantity": expected_quantity,
+ "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 len(granted_refund_data["lines"]) == 1
+ assert granted_refund_data["lines"][0]["orderLine"]["id"] == to_global_id_or_none(
+ order_line
+ )
+ assert granted_refund_data["lines"][0]["quantity"] == expected_quantity
+ assert granted_refund_data["lines"][0]["reason"] == expected_reason
+
+ assert len(granted_refund.lines.all()) == 1
+ granted_refund_line = granted_refund.lines.first()
+ assert granted_refund_line.order_line == order_line
+ assert granted_refund_line.quantity == expected_quantity
+ assert granted_refund_line.reason == expected_reason
+
+ assert granted_refund.amount_value == max_granted_charged_value
+ assert quantize_price(
+ granted_refund.amount_value, order_with_lines.currency
+ ) == quantize_price(
+ Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency
+ )
+ assert granted_refund_data["status"] == OrderGrantedRefundStatusEnum.NONE.name
+ assert granted_refund_data["transactionEvents"] == []
+ assert granted_refund_data["transaction"]["id"] == transaction_id
+
+
+def test_grant_refund_update_with_transaction_and_remove_lines(
+ 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("10.00")
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order_with_lines.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+ order_line = order_with_lines.lines.first()
+ granted_refund_line = granted_refund.lines.create(order_line=order_line, quantity=1)
+ granted_refund_line_id = to_global_id_or_none(granted_refund_line)
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ second_order_line = order_with_lines.lines.last()
+ granted_refund.lines.create(order_line=second_order_line, quantity=1)
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "transactionId": transaction_id,
+ "removeLines": [granted_refund_line_id],
+ },
+ }
+
+ # 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.amount_value == max_granted_charged_value
+ assert quantize_price(
+ granted_refund.amount_value, order_with_lines.currency
+ ) == quantize_price(
+ Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency
+ )
+ assert granted_refund_data["status"] == OrderGrantedRefundStatusEnum.NONE.name
+ assert granted_refund_data["transactionEvents"] == []
+ assert granted_refund_data["transaction"]["id"] == transaction_id
+
+
+def test_grant_refund_update_with_transaction_and_shipping_and_add_and_remove_lines(
+ 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("10.00")
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order_with_lines.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+ order_line = order_with_lines.lines.first()
+ granted_refund_line = granted_refund.lines.create(order_line=order_line, quantity=1)
+ granted_refund_line_id = to_global_id_or_none(granted_refund_line)
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ second_order_line = order_with_lines.lines.last()
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "transactionId": transaction_id,
+ "removeLines": [granted_refund_line_id],
+ "addLines": [
+ {
+ "id": to_global_id_or_none(second_order_line),
+ "quantity": 1,
+ }
+ ],
+ },
+ }
+
+ # 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.amount_value == max_granted_charged_value
+ assert quantize_price(
+ granted_refund.amount_value, order_with_lines.currency
+ ) == quantize_price(
+ Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency
+ )
+ assert granted_refund_data["status"] == OrderGrantedRefundStatusEnum.NONE.name
+ assert granted_refund_data["transactionEvents"] == []
+ assert granted_refund_data["transaction"]["id"] == transaction_id
+
+
+def test_grant_refund_update_with_transaction_add_remove_lines_shipping_invalid_amount(
+ 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,
+ )
+ order_line = order_with_lines.lines.first()
+ granted_refund_line = granted_refund.lines.create(order_line=order_line, quantity=1)
+ granted_refund_line_id = to_global_id_or_none(granted_refund_line)
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ second_order_line = order_with_lines.lines.last()
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": Decimal("20.00"),
+ "transactionId": transaction_id,
+ "grantRefundForShipping": True,
+ "removeLines": [granted_refund_line_id],
+ "addLines": [
+ {
+ "id": to_global_id_or_none(second_order_line),
+ "quantity": 1,
+ }
+ ],
+ },
+ }
+
+ # 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 len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "amount"
+ assert (
+ error["code"]
+ == OrderGrantRefundUpdateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.name
+ )
+
+
+def test_grant_refund_update_with_transaction_add_remove_lines_shipping_amount(
+ 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,
+ )
+ order_line = order_with_lines.lines.first()
+ granted_refund_line = granted_refund.lines.create(order_line=order_line, quantity=1)
+ granted_refund_line_id = to_global_id_or_none(granted_refund_line)
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ second_order_line = order_with_lines.lines.last()
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": max_granted_charged_value,
+ "transactionId": transaction_id,
+ "grantRefundForShipping": True,
+ "removeLines": [granted_refund_line_id],
+ "addLines": [
+ {
+ "id": to_global_id_or_none(second_order_line),
+ "quantity": 1,
+ }
+ ],
+ },
+ }
+
+ # 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.amount_value == max_granted_charged_value
+ assert quantize_price(
+ granted_refund.amount_value, order_with_lines.currency
+ ) == quantize_price(
+ Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency
+ )
+
+ assert granted_refund_data["status"] == OrderGrantedRefundStatusEnum.NONE.name
+ assert granted_refund_data["transactionEvents"] == []
+ assert granted_refund_data["transaction"]["id"] == transaction_id
+
+
+def test_grant_refund_update_with_transaction_add_lines_and_invalid_amount(
+ 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,
+ )
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ second_order_line = order_with_lines.lines.last()
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": max_granted_charged_value + Decimal("1.00"),
+ "transactionId": transaction_id,
+ "addLines": [
+ {
+ "id": to_global_id_or_none(second_order_line),
+ "quantity": 1,
+ }
+ ],
+ },
+ }
+
+ # 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 len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "amount"
+ assert (
+ error["code"]
+ == OrderGrantRefundUpdateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.name
+ )
+
+
+def test_grant_refund_update_with_transaction_remove_lines_and_invalid_amount(
+ 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,
+ )
+ order_line = order_with_lines.lines.first()
+ granted_refund_line = granted_refund.lines.create(order_line=order_line, quantity=1)
+ granted_refund_line_id = to_global_id_or_none(granted_refund_line)
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": max_granted_charged_value + Decimal("1.00"),
+ "transactionId": transaction_id,
+ "grantRefundForShipping": True,
+ "removeLines": [granted_refund_line_id],
+ },
+ }
+
+ # 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 len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "amount"
+ assert (
+ error["code"]
+ == OrderGrantRefundUpdateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.name
+ )
+
+
+def test_grant_refund_update_with_transaction_granted_shipping_and_invalid_amount(
+ 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,
+ )
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": max_granted_charged_value + Decimal("1.00"),
+ "transactionId": transaction_id,
+ "grantRefundForShipping": True,
+ },
+ }
+
+ # 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 len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "amount"
+ assert (
+ error["code"]
+ == OrderGrantRefundUpdateErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.name
+ )
+
+
+ "granted_refund_status",
+ [OrderGrantedRefundStatus.SUCCESS, OrderGrantedRefundStatus.PENDING],
+)
+def test_granted_refund_update_when_status_blocks_action(
+ 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,
+ )
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": max_granted_charged_value,
+ "transactionId": transaction_id,
+ "grantRefundForShipping": True,
+ },
+ }
+
+ # 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 len(data["errors"]) == 3
+ error_fields = {error["field"] for error in data["errors"]}
+ error_codes = {error["code"] for error in data["errors"]}
+ assert error_codes == {OrderGrantRefundUpdateErrorCode.INVALID.name}
+ assert error_fields == {"amount", "transactionId", "grantRefundForShipping"}
+
+
+ "granted_refund_status",
+ [OrderGrantedRefundStatus.FAILURE, OrderGrantedRefundStatus.NONE],
+)
+def test_granted_refund_update_when_status_allows_update(
+ 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,
+ )
+ order_line = order_with_lines.lines.first()
+ granted_refund_line = granted_refund.lines.create(order_line=order_line, quantity=1)
+ granted_refund_line_id = to_global_id_or_none(granted_refund_line)
+ granted_refund_id = to_global_id_or_none(granted_refund)
+
+ second_order_line = order_with_lines.lines.last()
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+
+ variables = {
+ "id": granted_refund_id,
+ "input": {
+ "amount": max_granted_charged_value,
+ "transactionId": transaction_id,
+ "grantRefundForShipping": True,
+ "removeLines": [granted_refund_line_id],
+ "addLines": [
+ {
+ "id": to_global_id_or_none(second_order_line),
+ "quantity": 1,
+ }
+ ],
+ },
+ }
+
+ # 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.amount_value == max_granted_charged_value
+ assert quantize_price(
+ granted_refund.amount_value, order_with_lines.currency
+ ) == 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
diff --git a/saleor/graphql/order/tests/queries/test_order_granted_refunds.py b/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
index 05405a7f63..7d3b6c5975 100644
--- a/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
+++ b/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
@@ -1,9 +1,13 @@
from decimal import Decimal
+import graphene
from prices import Money, TaxedMoney
+from saleor.payment import TransactionEventType
+
from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import OrderGrantedRefundStatusEnum
ORDERS_QUERY = """
query OrdersQuery {
@@ -38,6 +42,13 @@ query OrdersQuery {
}
quantity
}
+ status
+ transactionEvents{
+ id
+ }
+ transaction{
+ id
+ }
}
}
}
@@ -99,6 +110,9 @@ def test_order_granted_refunds_query_without_lines_by_user(
"app": None,
"shippingCostsIncluded": False,
"lines": [],
+ "status": OrderGrantedRefundStatusEnum.NONE.name,
+ "transactionEvents": [],
+ "transaction": None,
},
{
"id": to_global_id_or_none(second_granted_refund),
@@ -113,6 +127,9 @@ def test_order_granted_refunds_query_without_lines_by_user(
"user": None,
"shippingCostsIncluded": False,
"lines": [],
+ "status": OrderGrantedRefundStatusEnum.NONE.name,
+ "transactionEvents": [],
+ "transaction": None,
},
]
@@ -172,6 +189,9 @@ def test_order_granted_refunds_query_without_lines_by_app(
"app": None,
"shippingCostsIncluded": False,
"lines": [],
+ "status": OrderGrantedRefundStatusEnum.NONE.name,
+ "transactionEvents": [],
+ "transaction": None,
},
{
"id": to_global_id_or_none(second_granted_refund),
@@ -186,6 +206,9 @@ def test_order_granted_refunds_query_without_lines_by_app(
"user": None,
"shippingCostsIncluded": False,
"lines": [],
+ "status": OrderGrantedRefundStatusEnum.NONE.name,
+ "transactionEvents": [],
+ "transaction": None,
},
]
@@ -251,6 +274,9 @@ def test_order_granted_refunds_query_by_user(
},
}
],
+ "status": OrderGrantedRefundStatusEnum.NONE.name,
+ "transactionEvents": [],
+ "transaction": None,
},
]
@@ -318,6 +344,9 @@ def test_order_granted_refunds_query_by_app(
},
}
],
+ "status": OrderGrantedRefundStatusEnum.NONE.name,
+ "transactionEvents": [],
+ "transaction": None,
},
]
@@ -472,3 +501,131 @@ def test_order_granted_refunds_query_with_removed_app(
order_data = content["data"]["orders"]["edges"][0]["node"]
granted_refund = order_data["grantedRefunds"][0]
assert granted_refund["app"] is None
+
+
+def test_order_granted_refund_with_assigned_transaction(
+ app,
+ app_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ permission_manage_users,
+ fulfilled_order,
+ transaction_item_generator,
+):
+ # given
+ order = fulfilled_order
+ transaction = transaction_item_generator(
+ order_id=order.pk, charged_value=Decimal("10.0")
+ )
+ order.granted_refunds.create(
+ amount_value=Decimal("10.0"),
+ currency="USD",
+ reason="Test reason",
+ app=app,
+ shipping_costs_included=True,
+ transaction_item=transaction,
+ )
+
+ app_api_client.app.permissions.set(
+ [permission_manage_orders, permission_manage_shipping, permission_manage_users]
+ )
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ granted_refunds = order_data["grantedRefunds"]
+ assert len(granted_refunds) == 1
+ assert granted_refunds[0]["transaction"]["id"] == graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ )
+
+
+def test_order_granted_refund_with_status(
+ app,
+ app_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ permission_manage_users,
+ fulfilled_order,
+ transaction_item_generator,
+):
+ # given
+ order = fulfilled_order
+ transaction = transaction_item_generator(
+ order_id=order.pk, charged_value=Decimal("10.0")
+ )
+ order.granted_refunds.create(
+ amount_value=Decimal("10.0"),
+ currency="USD",
+ reason="Test reason",
+ app=app,
+ shipping_costs_included=True,
+ transaction_item=transaction,
+ )
+
+ app_api_client.app.permissions.set(
+ [permission_manage_orders, permission_manage_shipping, permission_manage_users]
+ )
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ granted_refunds = order_data["grantedRefunds"]
+ assert len(granted_refunds) == 1
+ assert granted_refunds[0]["status"] == OrderGrantedRefundStatusEnum.NONE.name
+
+
+def test_order_granted_refund_with_transaction_events(
+ app,
+ app_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ permission_manage_users,
+ fulfilled_order,
+ transaction_item_generator,
+):
+ # given
+ order = fulfilled_order
+ charged_value = Decimal("10.0")
+ transaction = transaction_item_generator(
+ order_id=order.pk, charged_value=charged_value
+ )
+ granted_refund = order.granted_refunds.create(
+ amount_value=Decimal("10.0"),
+ currency="USD",
+ reason="Test reason",
+ app=app,
+ shipping_costs_included=True,
+ transaction_item=transaction,
+ )
+ event = transaction.events.create(
+ psp_reference="123",
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=charged_value,
+ include_in_calculations=True,
+ currency=transaction.currency,
+ related_granted_refund=granted_refund,
+ )
+
+ app_api_client.app.permissions.set(
+ [permission_manage_orders, permission_manage_shipping, permission_manage_users]
+ )
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ granted_refunds = order_data["grantedRefunds"]
+ assert len(granted_refunds) == 1
+ grant_refund = granted_refunds[0]
+ assert len(grant_refund["transactionEvents"]) == 1
+ event_data = grant_refund["transactionEvents"][0]
+ assert event_data["id"] == graphene.Node.to_global_id("TransactionEvent", event.id)
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 57154d85fa..a3986e38ef 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -79,6 +79,7 @@ from ..core.descriptions import (
ADDED_IN_315,
ADDED_IN_318,
ADDED_IN_319,
+ ADDED_IN_320,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
)
@@ -110,9 +111,17 @@ from ..invoice.dataloaders import InvoicesByOrderIdLoader
from ..invoice.types import Invoice
from ..meta.resolvers import check_private_metadata_privilege, resolve_metadata
from ..meta.types import MetadataItem, ObjectWithMetadata
-from ..payment.dataloaders import TransactionByPaymentIdLoader
+from ..payment.dataloaders import (
+ TransactionByPaymentIdLoader,
+ TransactionItemByIDLoader,
+)
from ..payment.enums import OrderAction
-from ..payment.types import Payment, PaymentChargeStatusEnum, TransactionItem
+from ..payment.types import (
+ Payment,
+ PaymentChargeStatusEnum,
+ TransactionEvent,
+ TransactionItem,
+)
from ..plugins.dataloaders import (
get_plugin_manager_promise,
plugin_manager_promise_callback,
@@ -152,6 +161,7 @@ from .dataloaders import (
OrderGrantedRefundsByOrderIdLoader,
OrderLineByIdLoader,
OrderLinesByOrderIdLoader,
+ TransactionEventsByOrderGrantedRefundIdLoader,
TransactionItemsByOrderIDLoader,
)
from .enums import (
@@ -160,6 +170,7 @@ from .enums import (
OrderChargeStatusEnum,
OrderEventsEmailsEnum,
OrderEventsEnum,
+ OrderGrantedRefundStatusEnum,
OrderOriginEnum,
OrderStatusEnum,
)
@@ -263,6 +274,25 @@ class OrderGrantedRefund(ModelObjectType[models.OrderGrantedRefund]):
+ ADDED_IN_315
+ PREVIEW_FEATURE,
)
+ status = graphene.Field(
+ OrderGrantedRefundStatusEnum,
+ required=True,
+ description=(
+ "Status of the granted refund calculated based on transactionItem assigned "
+ "to granted refund." + ADDED_IN_320
+ ),
+ )
+ transaction_events = NonNullList(
+ TransactionEvent,
+ description=(
+ "List of refund events associated with the granted refund." + ADDED_IN_320
+ ),
+ )
+
+ transaction = graphene.Field(
+ TransactionItem,
+ description="The transaction assigned to the granted refund." + ADDED_IN_320,
+ )
class Meta:
description = "The details of granted refund." + ADDED_IN_313 + PREVIEW_FEATURE
@@ -299,6 +329,22 @@ class OrderGrantedRefund(ModelObjectType[models.OrderGrantedRefund]):
root.id
)
+ @staticmethod
+ @one_of_permissions_required(
+ [OrderPermissions.MANAGE_ORDERS, PaymentPermissions.HANDLE_PAYMENTS]
+ )
+ def resolve_transaction_events(root: models.OrderGrantedRefund, info):
+ return TransactionEventsByOrderGrantedRefundIdLoader(info.context).load(root.id)
+
+ @staticmethod
+ @one_of_permissions_required(
+ [OrderPermissions.MANAGE_ORDERS, PaymentPermissions.HANDLE_PAYMENTS]
+ )
+ def resolve_transaction(root: models.OrderGrantedRefund, info):
+ if not root.transaction_item_id:
+ return None
+ return TransactionItemByIDLoader(info.context).load(root.transaction_item_id)
+
class OrderDiscount(BaseObjectType):
value_type = graphene.Field(
diff --git a/saleor/graphql/payment/dataloaders.py b/saleor/graphql/payment/dataloaders.py
index e4e9d72351..f1bf8d5a8a 100644
--- a/saleor/graphql/payment/dataloaders.py
+++ b/saleor/graphql/payment/dataloaders.py
@@ -1,6 +1,6 @@
from collections import defaultdict
-from ...payment.models import Transaction, TransactionEvent
+from ...payment.models import Transaction, TransactionEvent, TransactionItem
from ..core.dataloaders import DataLoader
@@ -19,6 +19,16 @@ class TransactionEventByTransactionIdLoader(DataLoader):
return [event_map.get(transaction_id, []) for transaction_id in keys]
+class TransactionItemByIDLoader(DataLoader):
+ context_key = "transaction_items_by_id"
+
+ def batch_load(self, keys):
+ transactions = TransactionItem.objects.using(
+ self.database_connection_name
+ ).in_bulk(keys)
+ return [transactions.get(transaction_id) for transaction_id in keys]
+
+
class TransactionByPaymentIdLoader(DataLoader):
context_key = "transaction_by_payment_id"
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index 84234dcb90..87555d8f48 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -12,7 +12,10 @@ from .....order import models as order_models
from .....order.actions import order_transaction_updated
from .....order.fetch import fetch_order_info
from .....order.search import update_order_search_vector
-from .....order.utils import updates_amounts_for_order
+from .....order.utils import (
+ calculate_order_granted_refund_status,
+ updates_amounts_for_order,
+)
from .....payment import TransactionEventType
from .....payment import models as payment_models
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
@@ -165,6 +168,21 @@ class TransactionEventReport(ModelMutation):
fields_to_update.append("app_identifier")
transaction.save(update_fields=fields_to_update)
+ @classmethod
+ def get_related_granted_refund(
+ cls, event_psp_reference: str, transaction: payment_models.TransactionItem
+ ) -> Optional[order_models.OrderGrantedRefund]:
+ request_refund = (
+ payment_models.TransactionEvent.objects.filter(
+ psp_reference=event_psp_reference,
+ transaction_id=transaction.pk,
+ type=TransactionEventType.REFUND_REQUEST,
+ )
+ .select_related("related_granted_refund")
+ .last()
+ )
+ return request_refund.related_granted_refund if request_refund else None
+
@classmethod
def perform_mutation( # type: ignore[override]
cls,
@@ -202,6 +220,12 @@ class TransactionEventReport(ModelMutation):
if app and app.identifier:
app_identifier = app.identifier
+ related_granted_refund = None
+ if type in TransactionEventType.REFUND_RELATED_EVENT_TYPES:
+ related_granted_refund = cls.get_related_granted_refund(
+ psp_reference, transaction
+ )
+
transaction_event_data = {
"psp_reference": psp_reference,
"type": type,
@@ -215,6 +239,7 @@ class TransactionEventReport(ModelMutation):
"app": app,
"user": user,
"include_in_calculations": True,
+ "related_granted_refund": related_granted_refund,
}
transaction_event = cls.get_instance(info, **transaction_event_data)
transaction_event = cast(payment_models.TransactionEvent, transaction_event)
@@ -263,6 +288,8 @@ class TransactionEventReport(ModelMutation):
if error_msg and error_code and error_field:
create_failed_transaction_event(transaction_event, cause=error_msg)
+ if related_granted_refund:
+ calculate_order_granted_refund_status(related_granted_refund)
raise ValidationError({error_field: ValidationError(error_msg, error_code)})
if not already_processed:
previous_authorized_value = transaction.authorized_value
@@ -299,6 +326,8 @@ class TransactionEventReport(ModelMutation):
previous_charged_value=previous_charged_value,
previous_refunded_value=previous_refunded_value,
)
+ if related_granted_refund:
+ calculate_order_granted_refund_status(related_granted_refund)
if transaction.checkout_id:
manager = get_plugin_manager_promise(info.context).get()
transaction_amounts_for_checkout_updated(transaction, manager)
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py b/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
index 03bee9e662..1f2482f782 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
@@ -4,7 +4,9 @@ from typing import TYPE_CHECKING, cast
import graphene
from django.core.exceptions import ValidationError
+from .....order import OrderGrantedRefundStatus
from .....order import models as order_models
+from .....order.utils import calculate_order_granted_refund_status
from .....payment import PaymentError, TransactionEventType
from .....payment import models as payment_models
from .....payment.error_codes import TransactionRequestActionErrorCode
@@ -12,7 +14,7 @@ from .....payment.gateway import request_refund_action
from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
from ....core import ResolveInfo
-from ....core.descriptions import ADDED_IN_314, ADDED_IN_315, PREVIEW_FEATURE
+from ....core.descriptions import ADDED_IN_315, PREVIEW_FEATURE
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.enums import TransactionRequestRefundForGrantedRefundErrorCode
from ....core.mutations import BaseMutation
@@ -33,15 +35,20 @@ class TransactionRequestRefundForGrantedRefund(BaseMutation):
class Arguments:
id = graphene.ID(
description=(
- "The ID of the transaction. One of field id or token is required."
+ "The ID of the transaction. One of field id or token is required, "
+ "if `transactionItem` is not already assigned to the "
+ "`orderGrantedRefund`. If `transactionItem` is already assigned to the "
+ "grantedRefund the field will be ignored."
),
required=False,
)
token = UUID(
description=(
- "The token of the transaction. One of field id or token is required."
- )
- + ADDED_IN_314,
+ "The token of the transaction. One of field id or token is required, "
+ "if `transactionItem` is not already assigned to the "
+ "`orderGrantedRefund`. If `transactionItem` is already assigned to the "
+ "grantedRefund the field will be ignored."
+ ),
required=False,
)
granted_refund_id = graphene.ID(
@@ -63,40 +70,87 @@ class TransactionRequestRefundForGrantedRefund(BaseMutation):
def clean_input(
cls, info, transaction_id: str, token: UUID, granted_refund_id: str
) -> tuple[payment_models.TransactionItem, order_models.OrderGrantedRefund]:
- transaction_item = get_transaction_item(transaction_id, token)
granted_refund = cls.get_node_or_error(
info,
granted_refund_id,
field="granted_refund_id",
only_type="OrderGrantedRefund",
qs=order_models.OrderGrantedRefund.objects.select_related(
- "order__channel"
+ "order__channel", "transaction_item"
).all(),
)
granted_refund = cast(order_models.OrderGrantedRefund, granted_refund)
- if transaction_item.order_id != granted_refund.order_id:
- error_code = TransactionRequestRefundForGrantedRefundErrorCode.INVALID.value
- raise ValidationError(
- {
- "granted_refund_id": ValidationError(
- "The granted refund belongs to different order than "
- "transaction.",
- code=error_code,
- ),
- "id": ValidationError(
- "The transaction belongs to different order than "
- "granted refund.",
- code=error_code,
- ),
- }
+
+ if granted_refund.transaction_item_id:
+ transaction_item = cast(
+ payment_models.TransactionItem, granted_refund.transaction_item
)
+ error_class = TransactionRequestRefundForGrantedRefundErrorCode
+ if granted_refund.status == OrderGrantedRefundStatus.PENDING:
+ error_code = error_class.REFUND_IS_PENDING.value
+ raise ValidationError(
+ {
+ "granted_refund_id": ValidationError(
+ "The refund request is already in progress.",
+ code=error_code,
+ )
+ }
+ )
+ if granted_refund.status == OrderGrantedRefundStatus.SUCCESS:
+ error_code = error_class.REFUND_ALREADY_PROCESSED.value
+ raise ValidationError(
+ {
+ "granted_refund_id": ValidationError(
+ "The granted refund is already processed.",
+ code=error_code,
+ )
+ }
+ )
+ if transaction_item.charged_value < granted_refund.amount_value:
+ error_code = error_class.AMOUNT_GREATER_THAN_AVAILABLE.value
+ raise ValidationError(
+ {
+ "granted_refund_id": ValidationError(
+ f"The granted refund amount {granted_refund.amount_value} "
+ f"is greater than available charged amount on "
+ f"transactionItem ({transaction_item.charged_value})."
+ f"Update the order granted refund amount to process the "
+ f"grant refund.",
+ code=error_code,
+ )
+ }
+ )
+ else:
+ validate_one_of_args_is_in_mutation("id", transaction_id, "token", token)
+ transaction_item = get_transaction_item(transaction_id, token)
+ if transaction_item.order_id != granted_refund.order_id:
+ error_code = (
+ TransactionRequestRefundForGrantedRefundErrorCode.INVALID.value
+ )
+ raise ValidationError(
+ {
+ "granted_refund_id": ValidationError(
+ "The granted refund belongs to different order than "
+ "transaction.",
+ code=error_code,
+ ),
+ "id": ValidationError(
+ "The transaction belongs to different order than "
+ "granted refund.",
+ code=error_code,
+ ),
+ }
+ )
+ if not granted_refund.transaction_item_id:
+ granted_refund.transaction_item_id = transaction_item.pk
+ granted_refund.save(update_fields=["transaction_item_id"])
+
return transaction_item, granted_refund
@classmethod
def perform_mutation( # type: ignore[override]
cls, root, info: ResolveInfo, /, granted_refund_id, token=None, id=None
):
- validate_one_of_args_is_in_mutation("id", id, "token", token)
transaction_item, granted_refund = cls.clean_input(
info, id, token, granted_refund_id
)
@@ -110,11 +164,22 @@ class TransactionRequestRefundForGrantedRefund(BaseMutation):
manager = get_plugin_manager_promise(info.context).get()
action_value = granted_refund.amount_value or transaction_item.charged_value
action_value = min(action_value, transaction_item.charged_value)
+
+ assigned_granted_refund = None
+ if granted_refund.transaction_item_id == transaction_item.pk:
+ # For granted refund which doesn't have transaction item assigned
+ # there is a possibility to call the multiple refund with different
+ # transaction items. In that case we only match granted refund with
+ # transaction event when the same transaction item is assigned to the
+ # granted refund.
+ assigned_granted_refund = granted_refund
+
request_event = transaction_item.events.create(
amount_value=action_value,
currency=transaction_item.currency,
type=TransactionEventType.REFUND_REQUEST,
idempotency_key=str(uuid.uuid4()),
+ related_granted_refund=assigned_granted_refund,
)
try:
@@ -132,4 +197,8 @@ class TransactionRequestRefundForGrantedRefund(BaseMutation):
error_enum = TransactionRequestActionErrorCode
code = error_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
raise ValidationError(str(e), code=code)
+ finally:
+ if assigned_granted_refund:
+ calculate_order_granted_refund_status(assigned_granted_refund)
+
return cls(transaction=transaction_item)
diff --git a/saleor/graphql/payment/mutations/transaction/utils.py b/saleor/graphql/payment/mutations/transaction/utils.py
index 6be73f2caa..eee758cc73 100644
--- a/saleor/graphql/payment/mutations/transaction/utils.py
+++ b/saleor/graphql/payment/mutations/transaction/utils.py
@@ -16,7 +16,9 @@ if TYPE_CHECKING:
pass
-def get_transaction_item(id, token) -> payment_models.TransactionItem:
+def get_transaction_item(
+ id, token, error_field_name="id", qs=None
+) -> payment_models.TransactionItem:
"""Get transaction based on token or global ID.
The transactions created before 3.13 were using the `id` field as a graphql ID.
@@ -33,11 +35,14 @@ def get_transaction_item(id, token) -> payment_models.TransactionItem:
query_params = {"id": db_id, "use_old_id": True}
else:
query_params = {"token": db_id}
- instance = payment_models.TransactionItem.objects.filter(**query_params).first()
+ if qs is None:
+ qs = payment_models.TransactionItem.objects
+
+ instance = qs.filter(**query_params).first()
if not instance:
raise ValidationError(
{
- "id": ValidationError(
+ error_field_name: ValidationError(
f"Couldn't resolve to a node: {id}",
code=TransactionUpdateErrorCode.NOT_FOUND.value,
)
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index cd26d26e77..5b614a395a 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -12,6 +12,7 @@ from freezegun import freeze_time
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....order import OrderGrantedRefundStatus
from .....payment import TransactionEventType
from .....payment.models import TransactionEvent
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
@@ -2086,3 +2087,79 @@ def test_transaction_event_report_assign_transaction_psp_reference_if_missing(
== expected_transaction_psp_reference
)
assert transaction.psp_reference == expected_transaction_psp_reference
+
+
+ ("event_type", "expected_status"),
+ [
+ (TransactionEventTypeEnum.REFUND_SUCCESS, OrderGrantedRefundStatus.SUCCESS),
+ (TransactionEventTypeEnum.REFUND_FAILURE, OrderGrantedRefundStatus.FAILURE),
+ (TransactionEventTypeEnum.REFUND_REVERSE, OrderGrantedRefundStatus.NONE),
+ ],
+)
+def test_transaction_event_report_updates_granted_refund_status_when_needed(
+ event_type,
+ expected_status,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ order,
+):
+ # given
+ amount = Decimal("11.00")
+ transaction = transaction_item_generator(
+ app=app_api_client.app, charged_value=Decimal("10"), order_id=order.pk
+ )
+ granted_refund = order.granted_refunds.create(
+ amount_value=amount, currency=order.currency, transaction_item=transaction
+ )
+ psp_reference = "111-abc"
+
+ transaction.events.create(
+ psp_reference=psp_reference,
+ amount_value=amount,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ include_in_calculations=True,
+ related_granted_refund=granted_refund,
+ )
+
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": event_type.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "availableActions": [],
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ availableActions: $availableActions
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ granted_refund.refresh_from_db()
+ assert granted_refund.status == expected_status
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
index 9b9d4c263d..556cfdcfee 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
@@ -2,7 +2,9 @@ from decimal import Decimal
from unittest.mock import patch
import graphene
+import pytest
+from .....order import OrderGrantedRefundStatus
from .....payment import TransactionAction, TransactionEventType
from .....payment.interface import TransactionActionData
from .....payment.models import TransactionEvent
@@ -310,8 +312,12 @@ def test_triggers_refund_request_for_app(
variables,
)
+ # then
get_graphql_content(response)
+ granted_refund.refresh_from_db()
+ assert granted_refund.transaction_item_id == transaction_item.pk
+
request_event = TransactionEvent.objects.filter(
type=TransactionEventType.REFUND_REQUEST,
).first()
@@ -374,8 +380,12 @@ def test_triggers_refund_request_for_app_via_token(
variables,
)
+ # then
get_graphql_content(response)
+ granted_refund.refresh_from_db()
+ assert granted_refund.transaction_item_id == transaction_item.pk
+
request_event = TransactionEvent.objects.filter(
type=TransactionEventType.REFUND_REQUEST,
).first()
@@ -441,6 +451,79 @@ def test_triggers_refund_request_for_staff_user(
variables,
)
+ # then
+ get_graphql_content(response)
+
+ granted_refund.refresh_from_db()
+ assert granted_refund.transaction_item_id == transaction_item.pk
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+ assert request_event
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction_item,
+ action_type=TransactionAction.REFUND,
+ action_value=expected_refund_amount,
+ event=request_event,
+ transaction_app_owner=app,
+ granted_refund=granted_refund,
+ ),
+ order_with_lines.channel.slug,
+ )
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction_item,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_refund_amount,
+ )
+
+
[email protected]("expected_refund_amount", [Decimal("10.00"), Decimal("20.00")])
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_trigger_refund_request_with_assigned_transaction_item(
+ mocked_payment_action_request,
+ mocked_is_active,
+ expected_refund_amount,
+ staff_api_client,
+ order_with_lines,
+ permission_manage_payments,
+ transaction_item_generator,
+ app,
+ permission_group_no_perms_all_channels,
+):
+ # given
+ permission_group_no_perms_all_channels.user_set.add(staff_api_client.user)
+ staff_api_client.user.user_permissions.add(permission_manage_payments)
+
+ webhook = app.webhooks.create(
+ name="Request", is_active=True, target_url="http://localhost:8000/endpoint/"
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ charged_value=Decimal("20.00"),
+ app=app,
+ )
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=expected_refund_amount, transaction_item=transaction_item
+ )
+
+ variables = {
+ "grantedRefundID": to_global_id_or_none(granted_refund),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,
+ variables,
+ )
+
+ # then
get_graphql_content(response)
request_event = TransactionEvent.objects.filter(
@@ -465,3 +548,210 @@ def test_triggers_refund_request_for_staff_user(
type=TransactionEventType.REFUND_REQUEST,
amount_value=expected_refund_amount,
)
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_trigger_refund_request_with_assigned_transaction_item_and_not_enough_charged(
+ mocked_payment_action_request,
+ mocked_is_active,
+ staff_api_client,
+ order_with_lines,
+ permission_manage_payments,
+ transaction_item_generator,
+ app,
+ permission_group_no_perms_all_channels,
+):
+ # given
+ permission_group_no_perms_all_channels.user_set.add(staff_api_client.user)
+ staff_api_client.user.user_permissions.add(permission_manage_payments)
+
+ webhook = app.webhooks.create(
+ name="Request", is_active=True, target_url="http://localhost:8000/endpoint/"
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ available_charged_value = Decimal("20.00")
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ charged_value=available_charged_value,
+ app=app,
+ )
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=available_charged_value + Decimal("1"),
+ transaction_item=transaction_item,
+ )
+
+ variables = {
+ "grantedRefundID": to_global_id_or_none(granted_refund),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,
+ variables,
+ )
+
+ # then
+ response = get_graphql_content(response)
+ data = response["data"]["transactionRequestRefundForGrantedRefund"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "grantedRefundId"
+ assert (
+ error["code"]
+ == TransactionRequestRefundForGrantedRefundErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.name
+ )
+
+ assert not mocked_is_active.called
+ assert not mocked_payment_action_request.called
+
+
+ ("granted_refund_status", "expected_error_code"),
+ [
+ (OrderGrantedRefundStatus.PENDING, "REFUND_IS_PENDING"),
+ (OrderGrantedRefundStatus.SUCCESS, "REFUND_ALREADY_PROCESSED"),
+ ],
+)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_trigger_refund_blocked_based_on_status_of_granted_refund(
+ mocked_payment_action_request,
+ mocked_is_active,
+ granted_refund_status,
+ expected_error_code,
+ staff_api_client,
+ order_with_lines,
+ permission_manage_payments,
+ transaction_item_generator,
+ app,
+ permission_group_no_perms_all_channels,
+):
+ # given
+ permission_group_no_perms_all_channels.user_set.add(staff_api_client.user)
+ staff_api_client.user.user_permissions.add(permission_manage_payments)
+
+ webhook = app.webhooks.create(
+ name="Request", is_active=True, target_url="http://localhost:8000/endpoint/"
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ available_charged_value = Decimal("20.00")
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ charged_value=available_charged_value,
+ app=app,
+ )
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=available_charged_value - Decimal("1"),
+ transaction_item=transaction_item,
+ status=granted_refund_status,
+ )
+
+ variables = {
+ "grantedRefundID": to_global_id_or_none(granted_refund),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,
+ variables,
+ )
+
+ # then
+ response = get_graphql_content(response)
+ data = response["data"]["transactionRequestRefundForGrantedRefund"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "grantedRefundId"
+ assert (
+ error["code"]
+ == getattr(
+ TransactionRequestRefundForGrantedRefundErrorCode, expected_error_code
+ ).name
+ )
+
+ assert not mocked_is_active.called
+ assert not mocked_payment_action_request.called
+
+
+ "granted_refund_status",
+ [
+ OrderGrantedRefundStatus.NONE,
+ OrderGrantedRefundStatus.FAILURE,
+ ],
+)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_trigger_refund_possible_based_on_status_of_granted_refund(
+ mocked_payment_action_request,
+ mocked_is_active,
+ granted_refund_status,
+ staff_api_client,
+ order_with_lines,
+ permission_manage_payments,
+ transaction_item_generator,
+ app,
+ permission_group_no_perms_all_channels,
+):
+ # given
+ permission_group_no_perms_all_channels.user_set.add(staff_api_client.user)
+ staff_api_client.user.user_permissions.add(permission_manage_payments)
+
+ webhook = app.webhooks.create(
+ name="Request", is_active=True, target_url="http://localhost:8000/endpoint/"
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ charged_value=Decimal("20.00"),
+ app=app,
+ )
+ refund_amount = Decimal("10.00")
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=refund_amount,
+ transaction_item=transaction_item,
+ status=granted_refund_status,
+ )
+
+ variables = {
+ "grantedRefundID": to_global_id_or_none(granted_refund),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,
+ variables,
+ )
+
+ # then
+ get_graphql_content(response)
+
+ granted_refund.refresh_from_db()
+ assert granted_refund.status == OrderGrantedRefundStatus.PENDING
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+ assert request_event
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction_item,
+ action_type=TransactionAction.REFUND,
+ action_value=refund_amount,
+ event=request_event,
+ transaction_app_owner=app,
+ granted_refund=granted_refund,
+ ),
+ order_with_lines.channel.slug,
+ )
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction_item,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=refund_amount,
+ )
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 633ca30825..1590534ca4 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -13079,6 +13079,27 @@ type OrderGrantedRefund @doc(category: "Orders") {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
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
}
"""
@@ -13101,6 +13122,21 @@ type OrderGrantedRefundLine {
reason: String
}
+"""
+Represents the status of a granted refund.
+
+ NONE - the refund on related transactionItem is not processed
+ PENDING - the refund on related transactionItem is pending
+ FULL - the refund on related transactionItem is fully processed
+ FAIL - the refund on related transactionItem failed
+"""
+enum OrderGrantedRefundStatusEnum @doc(category: "Orders") {
+ NONE
+ PENDING
+ SUCCESS
+ FAILURE
+}
+
"""Represents transaction's event."""
type TransactionEvent implements Node @doc(category: "Payments") {
"""The ID of the object."""
@@ -16864,13 +16900,13 @@ type Mutation {
"""The ID of the granted refund."""
grantedRefundId: ID!
- """The ID of the transaction. One of field id or token is required."""
+ """
+ The ID of the transaction. One of field id or token is required, if `transactionItem` is not already assigned to the `orderGrantedRefund`. If `transactionItem` is already assigned to the grantedRefund the field will be ignored.
+ """
id: ID
"""
- The token of the transaction. One of field id or token is required.
-
- Added in Saleor 3.14.
+ The token of the transaction. One of field id or token is required, if `transactionItem` is not already assigned to the `orderGrantedRefund`. If `transactionItem` is already assigned to the grantedRefund the field will be ignored.
"""
token: UUID
): TransactionRequestRefundForGrantedRefund @doc(category: "Payments")
@@ -24734,7 +24770,10 @@ enum TransactionRequestRefundForGrantedRefundErrorCode @doc(category: "Payments"
INVALID
GRAPHQL_ERROR
NOT_FOUND
+ AMOUNT_GREATER_THAN_AVAILABLE
MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK
+ REFUND_ALREADY_PROCESSED
+ REFUND_IS_PENDING
}
"""
@@ -25994,6 +26033,7 @@ enum OrderGrantRefundCreateErrorCode @doc(category: "Orders") {
GRAPHQL_ERROR
NOT_FOUND
SHIPPING_COSTS_ALREADY_GRANTED
+ AMOUNT_GREATER_THAN_AVAILABLE
REQUIRED
INVALID
}
@@ -26047,6 +26087,15 @@ input OrderGrantRefundCreateInput @doc(category: "Orders") {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
grantRefundForShipping: Boolean
+
+ """
+ The ID of the transaction item related to the granted refund. If `amount` provided in the input, the transaction.chargedAmount needs to be equal or greater than provided `amount`.If `amount` is not provided in the input and calculated automatically by Saleor, the `min(calculatedAmount, transaction.chargedAmount)` will be used.Field will be required starting from Saleor 3.21.
+
+ Added in Saleor 3.20.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ transactionId: ID
}
input OrderGrantRefundCreateLineInput @doc(category: "Orders") {
@@ -26115,6 +26164,7 @@ enum OrderGrantRefundUpdateErrorCode @doc(category: "Orders") {
NOT_FOUND
REQUIRED
INVALID
+ AMOUNT_GREATER_THAN_AVAILABLE
SHIPPING_COSTS_ALREADY_GRANTED
}
@@ -26176,6 +26226,15 @@ input OrderGrantRefundUpdateInput @doc(category: "Orders") {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
grantRefundForShipping: Boolean
+
+ """
+ The ID of the transaction item related to the granted refund. If `amount` provided in the input, the transaction.chargedAmount needs to be equal or greater than provided `amount`.If `amount` is not provided in the input and calculated automatically by Saleor, the `min(calculatedAmount, transaction.chargedAmount)` will be used.Field will be required starting from Saleor 3.21.
+
+ Added in Saleor 3.20.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ transactionId: ID
}
input OrderGrantRefundUpdateLineAddInput @doc(category: "Orders") {
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 3e17d734bc..0257d7522a 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -320,3 +320,25 @@ class StockUpdatePolicy:
(UPDATE, "Only do update, if there is enough stocks."),
(FORCE, "Force update, if there is not enough stocks."),
]
+
+
+class OrderGrantedRefundStatus:
+ """Represents the status of a granted refund.
+
+ NONE - the refund on related transactionItem is not processed
+ PENDING - the refund on related transactionItem is pending
+ FULL - the refund on related transactionItem is fully processed
+ FAIL - the refund on related transactionItem failed
+ """
+
+ NONE = "none"
+ PENDING = "pending"
+ SUCCESS = "success"
+ FAILURE = "failure"
+
+ CHOICES = [
+ (NONE, "The refund on related transactionItem is not processed"),
+ (PENDING, "The refund on related transactionItem is pending"),
+ (SUCCESS, "The refund on related transactionItem is successfully processed"),
+ (FAILURE, "The refund on related transactionItem failed"),
+ ]
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 0fd975a4b7..f5bb4a73b5 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -44,6 +44,7 @@ class OrderGrantRefundCreateErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
NOT_FOUND = "not_found"
SHIPPING_COSTS_ALREADY_GRANTED = "shipping_costs_already_granted"
+ AMOUNT_GREATER_THAN_AVAILABLE = "amount_greater_than_available"
REQUIRED = "required"
INVALID = "invalid"
@@ -53,6 +54,7 @@ class OrderGrantRefundUpdateErrorCode(Enum):
NOT_FOUND = "not_found"
REQUIRED = "required"
INVALID = "invalid"
+ AMOUNT_GREATER_THAN_AVAILABLE = "amount_greater_than_available"
SHIPPING_COSTS_ALREADY_GRANTED = "shipping_costs_already_granted"
diff --git a/saleor/order/migrations/0185_ordergrantedrefund_transaction_item.py b/saleor/order/migrations/0185_ordergrantedrefund_transaction_item.py
new file mode 100644
index 0000000000..60930ca4eb
--- /dev/null
+++ b/saleor/order/migrations/0185_ordergrantedrefund_transaction_item.py
@@ -0,0 +1,47 @@
+# Generated by Django 3.2.23 on 2024-03-06 10:55
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0056_merge_20231213_0755"),
+ ("order", "0184_merge_0182_merge_20240325_1338_0183_order_tax_error"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="ordergrantedrefund",
+ name="transaction_item",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="granted_refund",
+ to="payment.transactionitem",
+ ),
+ ),
+ migrations.AddField(
+ model_name="ordergrantedrefund",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("none", "The refund on related transactionItem is not processed"),
+ ("pending", "The refund on related transactionItem is pending"),
+ (
+ "success",
+ "The refund on related transactionItem is successfully "
+ "processed",
+ ),
+ ("failure", "The refund on related transactionItem failed"),
+ ],
+ default="none",
+ max_length=128,
+ ),
+ ),
+ migrations.RunSQL(
+ "ALTER TABLE order_ordergrantedrefund ALTER COLUMN status SET DEFAULT 'none';",
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 469dc01659..bbff37a07f 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -35,6 +35,7 @@ from . import (
OrderAuthorizeStatus,
OrderChargeStatus,
OrderEvents,
+ OrderGrantedRefundStatus,
OrderOrigin,
OrderStatus,
)
@@ -876,6 +877,20 @@ class OrderGrantedRefund(models.Model):
)
shipping_costs_included = models.BooleanField(default=False)
+ transaction_item = models.ForeignKey(
+ "payment.TransactionItem",
+ related_name="granted_refund",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ )
+
+ status = models.CharField(
+ choices=OrderGrantedRefundStatus.CHOICES,
+ default=OrderGrantedRefundStatus.NONE,
+ max_length=128,
+ )
+
class Meta:
ordering = ("created_at", "id")
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index 8dd9dec91b..bbd384d6b4 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -9,15 +9,17 @@ from ...discount.interface import VariantPromotionRuleInfo
from ...giftcard import GiftCardEvents
from ...giftcard.models import GiftCardEvent
from ...graphql.order.utils import OrderLineData
+from ...payment import TransactionEventType
from ...plugins.manager import get_plugins_manager
from ...product.models import VariantChannelListingPromotionRule
-from .. import OrderStatus
+from .. import OrderGrantedRefundStatus, OrderStatus
from ..events import OrderEvents
from ..fetch import OrderLineInfo
from ..models import Order, OrderEvent
from ..utils import (
add_gift_cards_to_order,
add_variant_to_order,
+ calculate_order_granted_refund_status,
change_order_line_quantity,
create_order_line_discounts,
get_order_country,
@@ -662,3 +664,44 @@ def test_create_order_line_discounts(
assert discount_2.name == f"{promotion.name}: {rule_2.name}"
assert discount_2.translated_name == f"{promotion_translation_fr.name}"
assert discount_2.promotion_rule == rule_2
+
+
+ ("expected_granted_status", "event_type"),
+ [
+ (OrderGrantedRefundStatus.NONE, TransactionEventType.CHARGE_SUCCESS),
+ (OrderGrantedRefundStatus.PENDING, TransactionEventType.REFUND_REQUEST),
+ (OrderGrantedRefundStatus.SUCCESS, TransactionEventType.REFUND_SUCCESS),
+ (OrderGrantedRefundStatus.FAILURE, TransactionEventType.REFUND_FAILURE),
+ (OrderGrantedRefundStatus.NONE, TransactionEventType.REFUND_REVERSE),
+ ],
+)
+def test_calculate_order_granted_refund_status(
+ expected_granted_status, event_type, order, transaction_item_generator
+):
+ # given
+ transaction_item = transaction_item_generator(
+ order_id=order.pk,
+ charged_value=Decimal("100.00"),
+ refunded_value=Decimal("5.00"),
+ )
+
+ granted_refund = order.granted_refunds.create(
+ amount_value=Decimal("10.00"),
+ currency=order.currency,
+ transaction_item=transaction_item,
+ )
+
+ transaction_item.events.create(
+ amount_value=Decimal("10.00"),
+ currency=order.currency,
+ type=event_type,
+ related_granted_refund=granted_refund,
+ )
+
+ # when
+ calculate_order_granted_refund_status(granted_refund)
+
+ # then
+ granted_refund.refresh_from_db()
+ assert granted_refund.status == expected_granted_status
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index f159dc5b1e..e70b3f1f1f 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -35,6 +35,7 @@ from ..discount.utils import (
from ..giftcard import events as gift_card_events
from ..giftcard.models import GiftCard
from ..giftcard.search import mark_gift_cards_search_index_as_dirty
+from ..payment import TransactionEventType
from ..payment.model_helpers import get_total_authorized
from ..product.utils.digital_products import get_default_digital_content_settings
from ..shipping.interface import ShippingMethodData
@@ -56,6 +57,7 @@ from . import (
FulfillmentStatus,
OrderAuthorizeStatus,
OrderChargeStatus,
+ OrderGrantedRefundStatus,
OrderStatus,
events,
)
@@ -1156,3 +1158,42 @@ def update_order_display_gross_prices(order: "Order"):
order.display_gross_prices = get_display_gross_prices(
tax_configuration, country_tax_configuration
)
+
+
+def calculate_order_granted_refund_status(
+ granted_refund: OrderGrantedRefund,
+ with_save: bool = True,
+):
+ """Update the status for the granted refund.
+
+ The status is calculated based on last transaction event related to refund action.
+ """
+
+ last_event = (
+ granted_refund.transaction_events.filter(
+ transaction_id=granted_refund.transaction_item_id,
+ type__in=[
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_REVERSE,
+ TransactionEventType.REFUND_FAILURE,
+ ],
+ )
+ .order_by("created_at")
+ .last()
+ )
+
+ current_granted_refund_status = granted_refund.status
+ if not last_event:
+ return
+ if last_event.type == TransactionEventType.REFUND_SUCCESS:
+ granted_refund.status = OrderGrantedRefundStatus.SUCCESS
+ elif last_event.type == TransactionEventType.REFUND_REQUEST:
+ granted_refund.status = OrderGrantedRefundStatus.PENDING
+ elif last_event.type == TransactionEventType.REFUND_FAILURE:
+ granted_refund.status = OrderGrantedRefundStatus.FAILURE
+ else:
+ granted_refund.status = OrderGrantedRefundStatus.NONE
+
+ if with_save and current_granted_refund_status != granted_refund.status:
+ granted_refund.save(update_fields=["status"])
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 421f2d8470..064804fb51 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -237,6 +237,12 @@ class TransactionEventType:
(CANCEL_REQUEST, "Represents cancel request"),
(INFO, "Represents an info event"),
]
+ REFUND_RELATED_EVENT_TYPES = [
+ REFUND_SUCCESS,
+ REFUND_FAILURE,
+ REFUND_REVERSE,
+ REFUND_REQUEST,
+ ]
class TokenizedPaymentFlow:
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index 853c911c90..f0883ecc8a 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -52,9 +52,12 @@ class TransactionRequestRefundForGrantedRefundErrorCode(Enum):
INVALID = "invalid"
GRAPHQL_ERROR = "graphql_error"
NOT_FOUND = "not_found"
+ AMOUNT_GREATER_THAN_AVAILABLE = "amount_greater_than_available"
MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK = (
"missing_transaction_action_request_webhook"
)
+ REFUND_ALREADY_PROCESSED = "refund_already_processed"
+ REFUND_IS_PENDING = "refund_is_pending"
class TransactionEventReportErrorCode(Enum):
diff --git a/saleor/payment/migrations/0057_transactionevent_related_granted_refund.py b/saleor/payment/migrations/0057_transactionevent_related_granted_refund.py
new file mode 100644
index 0000000000..1c057f5130
--- /dev/null
+++ b/saleor/payment/migrations/0057_transactionevent_related_granted_refund.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.23 on 2024-03-07 11:26
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0185_ordergrantedrefund_transaction_item"),
+ ("payment", "0056_merge_20231213_0755"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="transactionevent",
+ name="related_granted_refund",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="transaction_events",
+ to="order.ordergrantedrefund",
+ ),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 83f174eb40..cb9f377884 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -203,6 +203,14 @@ class TransactionEvent(models.Model):
include_in_calculations = models.BooleanField(default=False)
+ related_granted_refund = models.ForeignKey(
+ "order.OrderGrantedRefund",
+ related_name="transaction_events",
+ blank=True,
+ null=True,
+ on_delete=models.SET_NULL,
+ )
+
class Meta:
ordering = ("pk",)
constraints = [
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 641eea33c5..f5245c9c8a 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -8,7 +8,7 @@ from django.utils import timezone
from freezegun import freeze_time
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ...order import OrderAuthorizeStatus, OrderChargeStatus
+from ...order import OrderAuthorizeStatus, OrderChargeStatus, OrderGrantedRefundStatus
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
from .. import TransactionEventType
@@ -1268,6 +1268,105 @@ def test_create_event_from_request_and_webhook_success_event_calculate_refundabl
assert checkout.automatically_refundable is True
+ ("event_type", "expected_status"),
+ [
+ (TransactionEventType.REFUND_SUCCESS, OrderGrantedRefundStatus.SUCCESS),
+ (TransactionEventType.REFUND_FAILURE, OrderGrantedRefundStatus.FAILURE),
+ ],
+)
+def test_create_event_from_request_and_webhook_success_updated_granted_refund_status(
+ event_type,
+ expected_status,
+ transaction_item_generator,
+ order,
+ app,
+):
+ # given
+ transaction = transaction_item_generator(
+ order_id=order.pk, charged_value=Decimal(100)
+ )
+
+ granted_refund = order.granted_refunds.create(
+ amount_value=Decimal(100),
+ currency="USD",
+ transaction_item_id=transaction.id,
+ status=OrderGrantedRefundStatus.NONE,
+ )
+ with freeze_time("2022-11-18T12:25:58"):
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ related_granted_refund=granted_refund,
+ )
+
+ event_amount = 12.00
+ event_type = event_type
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ response_data = {
+ "pspReference": "123",
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ "actions": ["CHARGE", "CHARGE", "CANCEL"],
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ granted_refund.refresh_from_db()
+ assert granted_refund.status == expected_status
+
+
+def test_create_event_from_request_and_webhook_success_granted_refund_status_only_psp(
+ transaction_item_generator,
+ order,
+ app,
+):
+ # given
+ transaction = transaction_item_generator(
+ order_id=order.pk, charged_value=Decimal(100)
+ )
+
+ granted_refund = order.granted_refunds.create(
+ amount_value=Decimal(100),
+ currency="USD",
+ transaction_item_id=transaction.id,
+ status=OrderGrantedRefundStatus.NONE,
+ )
+ with freeze_time("2022-11-18T12:25:58"):
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ related_granted_refund=granted_refund,
+ )
+
+ response_data = {
+ "pspReference": "123",
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ granted_refund.refresh_from_db()
+ assert granted_refund.status == OrderGrantedRefundStatus.PENDING
+
+
def test_create_event_from_request_and_webhook_pending_event_calculate_refundable(
transaction_item_generator,
checkout,
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 621342ea74..f4bade3712 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -29,9 +29,13 @@ from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
from ..graphql.core.utils import str_to_enum
from ..order.fetch import fetch_order_info
-from ..order.models import Order
+from ..order.models import Order, OrderGrantedRefund
from ..order.search import update_order_search_vector
-from ..order.utils import update_order_authorize_data, updates_amounts_for_order
+from ..order.utils import (
+ calculate_order_granted_refund_status,
+ update_order_authorize_data,
+ updates_amounts_for_order,
+)
from ..plugins.manager import PluginsManager, get_plugins_manager
from . import (
ChargeStatus,
@@ -1023,6 +1027,7 @@ def create_failed_transaction_event(
message=cause,
include_in_calculations=False,
psp_reference=event.psp_reference,
+ related_granted_refund_id=event.related_granted_refund_id,
)
@@ -1108,6 +1113,7 @@ def _create_event_from_response(
app: App,
transaction_id: int,
currency: str,
+ related_granted_refund_id: Optional[int] = None,
) -> tuple[Optional[TransactionEvent], Optional[error_msg]]:
app_identifier = None
if app and app.identifier:
@@ -1124,6 +1130,7 @@ def _create_event_from_response(
app_identifier=app_identifier,
app=app,
include_in_calculations=True,
+ related_granted_refund_id=related_granted_refund_id,
)
with transaction.atomic():
event, error_msg = deduplicate_event(event, app)
@@ -1298,6 +1305,12 @@ def create_transaction_event_for_transaction_session(
return event
+def update_order_granted_status_if_needed(request_event: TransactionEvent):
+ if request_event.related_granted_refund_id:
+ granted_refund = cast(OrderGrantedRefund, request_event.related_granted_refund)
+ calculate_order_granted_refund_status(granted_refund)
+
+
def create_transaction_event_from_request_and_webhook_response(
request_event: TransactionEvent,
app: App,
@@ -1310,7 +1323,11 @@ def create_transaction_event_from_request_and_webhook_response(
transaction_item = request_event.transaction
if not transaction_request_response:
recalculate_refundable_for_checkout(transaction_item, request_event)
- return create_failed_transaction_event(request_event, cause=error_msg or "")
+ failure_event = create_failed_transaction_event(
+ request_event, cause=error_msg or ""
+ )
+ update_order_granted_status_if_needed(request_event)
+ return failure_event
psp_reference = transaction_request_response.psp_reference
request_event.psp_reference = psp_reference
@@ -1323,10 +1340,15 @@ def create_transaction_event_from_request_and_webhook_response(
app=app,
transaction_id=request_event.transaction_id,
currency=request_event.currency,
+ related_granted_refund_id=request_event.related_granted_refund_id,
)
if error_msg:
recalculate_refundable_for_checkout(transaction_item, request_event)
- return create_failed_transaction_event(request_event, cause=error_msg)
+ failure_event = create_failed_transaction_event(
+ request_event, cause=error_msg
+ )
+ update_order_granted_status_if_needed(request_event)
+ return failure_event
transaction_item = request_event.transaction
previous_authorized_value = transaction_item.authorized_value
@@ -1370,6 +1392,12 @@ def create_transaction_event_from_request_and_webhook_response(
previous_charged_value=previous_charged_value,
previous_refunded_value=previous_refunded_value,
)
+ if request_event.related_granted_refund_id:
+ granted_refund = cast(
+ OrderGrantedRefund, request_event.related_granted_refund
+ )
+ calculate_order_granted_refund_status(granted_refund)
+
elif transaction_item.checkout_id:
manager = get_plugins_manager(allow_replica=True)
recalculate_refundable_for_checkout(transaction_item, request_event, event)