Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Include lines in transaction's refund requests (#13014)
Maciej Korycinski4689ca0d8098
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 969855a29a..0931c88c73 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@All notable, unreleased changes to this project will be documented in this file. For the released changes, please visit the [Releases](https://github.com/mirumee/saleor/releases) page.+# 3.15.0 [Unreleased]### Breaking changes@@ -22,6 +23,7 @@ All notable, unreleased changes to this project will be documented in this file.3. Channel's default country### GraphQL API+- Add `lines` to `OrderGrantedRefund` - #13014 by @korycins- Add `orderNoteAdd` and `orderNoteUpdate` mutations and deprecate `orderAddNote` mutation - #12434 by @pawelzar- Deprecate `Order.trackingClientId` field - #13146 by @SzymJdiff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.pyindex 9c2001523a..380e5050d6 100644--- a/saleor/graphql/core/enums.py+++ b/saleor/graphql/core/enums.py@@ -240,6 +240,10 @@ TransactionRequestActionErrorCode = graphene.Enum.from_enum()TransactionRequestActionErrorCode.doc_category = DOC_CATEGORY_PAYMENTS+TransactionRequestRefundForGrantedRefundErrorCode = graphene.Enum.from_enum(+ payment_error_codes.TransactionRequestRefundForGrantedRefundErrorCode+)+TransactionRequestRefundForGrantedRefundErrorCode.doc_category = DOC_CATEGORY_PAYMENTSTransactionEventReportErrorCode = graphene.Enum.from_enum(payment_error_codes.TransactionEventReportErrorCode)diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex fd9d4c5721..925448a8a0 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -78,6 +78,7 @@ from ..enums import (TransactionInitializeErrorCode,TransactionProcessErrorCode,TransactionRequestActionErrorCode,+ TransactionRequestRefundForGrantedRefundErrorCode,TransactionUpdateErrorCode,TranslationErrorCode,UploadErrorCode,@@ -597,6 +598,15 @@ class TransactionRequestActionError(Error):doc_category = DOC_CATEGORY_PAYMENTS+class TransactionRequestRefundForGrantedRefundError(Error):+ code = TransactionRequestRefundForGrantedRefundErrorCode(+ description="The error code.", required=True+ )++ class Meta:+ doc_category = DOC_CATEGORY_PAYMENTS++class TransactionEventReportError(Error):code = TransactionEventReportErrorCode(description="The error code.", required=True)diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.pyindex c977ebf1c2..e4f8050fcc 100644--- a/saleor/graphql/order/dataloaders.py+++ b/saleor/graphql/order/dataloaders.py@@ -9,6 +9,7 @@ from ...order.models import (Order,OrderEvent,OrderGrantedRefund,+ OrderGrantedRefundLine,OrderLine,)from ...payment.models import TransactionItem@@ -141,6 +142,22 @@ class OrderGrantedRefundsByOrderIdLoader(DataLoader):return [refunds_map.get(order_id, []) for order_id in keys]+class OrderGrantedRefundLinesByOrderGrantedRefundIdLoader(DataLoader):+ context_key = "order_granted_refund_lines_by_granted_refund_id"++ def batch_load(self, keys):+ refund_lines = OrderGrantedRefundLine.objects.using(+ self.database_connection_name+ ).filter(granted_refund_id__in=keys)+ refund_lines_map = defaultdict(list)++ for refund_line in refund_lines.iterator():+ refund_lines_map[refund_line.granted_refund_id].append(refund_line)+ return [+ refund_lines_map.get(granted_refund_id, []) for granted_refund_id in keys+ ]++class AllocationsByOrderLineIdLoader(DataLoader):context_key = "allocations_by_orderline_id"diff --git a/saleor/graphql/order/enums.py b/saleor/graphql/order/enums.pyindex 2671114663..732597297f 100644--- a/saleor/graphql/order/enums.py+++ b/saleor/graphql/order/enums.py@@ -64,6 +64,14 @@ OrderChargeStatusEnum.doc_category = DOC_CATEGORY_ORDERSOrderGrantRefundCreateErrorCode = graphene.Enum.from_enum(error_codes.OrderGrantRefundCreateErrorCode)+OrderGrantRefundCreateLineErrorCode = graphene.Enum.from_enum(+ error_codes.OrderGrantRefundCreateLineErrorCode+)++OrderGrantRefundUpdateLineErrorCode = graphene.Enum.from_enum(+ error_codes.OrderGrantRefundUpdateLineErrorCode+)+OrderGrantRefundCreateErrorCode.doc_category = DOC_CATEGORY_ORDERSOrderGrantRefundUpdateErrorCode = graphene.Enum.from_enum(diff --git a/saleor/graphql/order/mutations/order_grant_refund_create.py b/saleor/graphql/order/mutations/order_grant_refund_create.pyindex 2dd3c3a182..6572144ee4 100644--- a/saleor/graphql/order/mutations/order_grant_refund_create.py+++ b/saleor/graphql/order/mutations/order_grant_refund_create.py@@ -1,27 +1,85 @@+import decimal+from typing import Any, Optional, Union+import graphene+from django.core.exceptions import ValidationError+from django.db import transaction+from ....order import modelsfrom ....permission.enums import OrderPermissionsfrom ...core import ResolveInfo-from ...core.descriptions import ADDED_IN_313, PREVIEW_FEATURE+from ...core.descriptions import ADDED_IN_313, ADDED_IN_315, PREVIEW_FEATUREfrom ...core.doc_category import DOC_CATEGORY_ORDERSfrom ...core.mutations import BaseMutationfrom ...core.scalars import Decimalfrom ...core.types import BaseInputObjectType-from ...core.types.common import Error-from ..enums import OrderGrantRefundCreateErrorCode+from ...core.types.common import Error, NonNullList+from ..enums import OrderGrantRefundCreateErrorCode, OrderGrantRefundCreateLineErrorCodefrom ..types import Order, OrderGrantedRefund+from .order_grant_refund_utils import (+ assign_order_lines,+ get_input_lines_data,+ handle_lines_with_quantity_already_refunded,+ shipping_costs_already_granted,+)+++class OrderGrantRefundCreateLineError(Error):+ code = OrderGrantRefundCreateLineErrorCode(+ description="The error code.", required=True+ )+ line_id = graphene.ID(+ description="The ID of the line related to the error.", required=True+ )class OrderGrantRefundCreateError(Error):code = OrderGrantRefundCreateErrorCode(description="The error code.", required=True)+ lines = NonNullList(+ OrderGrantRefundCreateLineError,+ description="List of lines which cause the error."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ required=False,+ )++ class Meta:+ doc_category = DOC_CATEGORY_ORDERS+++class OrderGrantRefundCreateLineInput(BaseInputObjectType):+ id = graphene.ID(description="The ID of the order line.", required=True)+ quantity = graphene.Int(+ description="The quantity of line items to be marked to refund.", required=True+ )+ reason = graphene.String(description="Reason of the granted refund for the line.")class Meta:doc_category = DOC_CATEGORY_ORDERSclass OrderGrantRefundCreateInput(BaseInputObjectType):- amount = Decimal(required=True, description="Amount of the granted refund.")+ amount = Decimal(+ description=(+ "Amount of the granted refund. If not provided, the amount will be "+ "calculated automatically based on provided `lines` and "+ "`grantRefundForShipping`."+ )+ )reason = graphene.String(description="Reason of the granted refund.")+ lines = NonNullList(+ OrderGrantRefundCreateLineInput,+ description="Lines to assign to granted refund."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ required=False,+ )+ grant_refund_for_shipping = graphene.Boolean(+ description="Determine if granted refund should include shipping costs."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ required=False,+ )class Meta:doc_category = DOC_CATEGORY_ORDERS@@ -50,18 +108,145 @@ class OrderGrantRefundCreate(BaseMutation):error_type_class = OrderGrantRefundCreateErrordoc_category = DOC_CATEGORY_ORDERS+ @classmethod+ def clean_input_lines(+ cls,+ order: models.Order,+ lines: list[dict[str, Union[str, int]]],+ ) -> tuple[list[models.OrderGrantedRefundLine], Optional[list[dict[str, str]]]]:+ errors: list[dict[str, str]] = []+ input_lines_data = get_input_lines_data(+ lines, errors, OrderGrantRefundCreateLineErrorCode.GRAPHQL_ERROR.value+ )+ assign_order_lines(+ order,+ input_lines_data,+ errors,+ OrderGrantRefundCreateLineErrorCode.NOT_FOUND.value,+ )+ handle_lines_with_quantity_already_refunded(+ order,+ input_lines_data,+ errors,+ OrderGrantRefundCreateLineErrorCode.QUANTITY_GREATER_THAN_AVAILABLE.value,+ )++ if errors:+ return [], errors++ return list(input_lines_data.values()), None++ @classmethod+ def calculate_amount(+ cls,+ order: models.Order,+ cleaned_input_lines: list[models.OrderGrantedRefundLine],+ grant_refund_for_shipping: bool,+ ) -> decimal.Decimal:+ amount = decimal.Decimal(0)+ for granted_refund_line in cleaned_input_lines:+ amount += (+ granted_refund_line.order_line.unit_price_gross_amount+ * granted_refund_line.quantity+ )+ if grant_refund_for_shipping:+ amount += order.shipping_price_gross_amount+ return amount++ @classmethod+ def validate_input(cls, input: dict[str, Any]):+ amount = input.get("amount")+ input_lines = input.get("lines", [])+ grant_refund_for_shipping = input.get("grant_refund_for_shipping", False)++ if amount is None and not input_lines and not grant_refund_for_shipping:+ error_msg = (+ "You must provide at least one of `amount`, `lines`, "+ "`grantRefundForShipping`."+ )+ error_code = OrderGrantRefundCreateErrorCode.REQUIRED.value+ raise ValidationError(+ {+ "amount": ValidationError(error_msg, code=error_code),+ "lines": ValidationError(error_msg, code=error_code),+ "grant_refund_for_shipping": ValidationError(+ error_msg, code=error_code+ ),+ }+ )++ @classmethod+ def clean_input(+ cls,+ order: models.Order,+ input: dict[str, Any],+ ):+ amount = input.get("amount")+ reason = input.get("reason", "")+ input_lines = input.get("lines", [])+ grant_refund_for_shipping = input.get("grant_refund_for_shipping", None)++ cls.validate_input(input)++ cleaned_input_lines: list[models.OrderGrantedRefundLine] = []+ if input_lines:+ cleaned_input_lines, errors = cls.clean_input_lines(order, input_lines)+ if errors:+ raise ValidationError(+ {+ "lines": ValidationError(+ "Provided input for lines is invalid.",+ code=OrderGrantRefundCreateErrorCode.INVALID.value,+ params={"lines": errors},+ ),+ }+ )+ if grant_refund_for_shipping and shipping_costs_already_granted(order):+ error_code = OrderGrantRefundCreateErrorCode.SHIPPING_COSTS_ALREADY_GRANTED+ raise ValidationError(+ {+ "grant_refund_for_shipping": ValidationError(+ "Shipping costs have already been granted.",+ code=error_code.value,+ )+ }+ )++ if amount is None:+ amount = cls.calculate_amount(+ order, cleaned_input_lines, grant_refund_for_shipping+ )++ return {+ "amount": amount,+ "reason": reason,+ "lines": cleaned_input_lines,+ "grant_refund_for_shipping": grant_refund_for_shipping,+ }+@classmethoddef perform_mutation( # type: ignore[override]cls, _root, info: ResolveInfo, /, *, id, input):order = cls.get_node_or_error(info, id, only_type=Order)- amount = input["amount"]- reason = input.get("reason", "")- granted_refund = order.granted_refunds.create(- amount_value=amount,- currency=order.currency,- reason=reason,- user=info.context.user,- app=info.context.app,- )+ cleaned_input = cls.clean_input(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"]++ with transaction.atomic():+ granted_refund = order.granted_refunds.create(+ amount_value=amount,+ currency=order.currency,+ reason=reason,+ user=info.context.user,+ app=info.context.app,+ shipping_costs_included=grant_refund_for_shipping or False,+ )+ if cleaned_input_lines:+ for line in cleaned_input_lines:+ line.granted_refund = granted_refund+ models.OrderGrantedRefundLine.objects.bulk_create(cleaned_input_lines)+return cls(order=order, granted_refund=granted_refund)diff --git a/saleor/graphql/order/mutations/order_grant_refund_update.py b/saleor/graphql/order/mutations/order_grant_refund_update.pyindex 4e9678dec4..e86b40243b 100644--- a/saleor/graphql/order/mutations/order_grant_refund_update.py+++ b/saleor/graphql/order/mutations/order_grant_refund_update.py@@ -1,34 +1,107 @@+from typing import Any, Union+import graphenefrom django.core.exceptions import ValidationError+from django.db import transaction+from graphql import GraphQLErrorfrom ....order import modelsfrom ....permission.enums import OrderPermissions-from ...core.descriptions import ADDED_IN_313, PREVIEW_FEATURE+from ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_313, ADDED_IN_315, PREVIEW_FEATUREfrom ...core.doc_category import DOC_CATEGORY_ORDERS-from ...core.mutations import ModelMutation+from ...core.mutations import BaseMutationfrom ...core.scalars import Decimalfrom ...core.types import BaseInputObjectType-from ...core.types.common import Error-from ..enums import OrderGrantRefundUpdateErrorCode+from ...core.types.common import Error, NonNullList+from ...core.utils import from_global_id_or_error+from ..enums import OrderGrantRefundUpdateErrorCode, OrderGrantRefundUpdateLineErrorCodefrom ..types import Order, OrderGrantedRefund+from .order_grant_refund_utils import (+ assign_order_lines,+ get_input_lines_data,+ handle_lines_with_quantity_already_refunded,+ shipping_costs_already_granted,+)+++class OrderGrantRefundUpdateLineError(Error):+ code = OrderGrantRefundUpdateLineErrorCode(+ description="The error code.", required=True+ )+ line_id = graphene.ID(+ description="The ID of the line related to the error.", required=True+ )class OrderGrantRefundUpdateError(Error):code = OrderGrantRefundUpdateErrorCode(description="The error code.", required=True)+ add_lines = NonNullList(+ OrderGrantRefundUpdateLineError,+ description="List of lines to add which cause the error."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ required=False,+ )+ remove_lines = NonNullList(+ OrderGrantRefundUpdateLineError,+ description="List of lines to remove which cause the error."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ required=False,+ )++ class Meta:+ doc_category = DOC_CATEGORY_ORDERS+++class OrderGrantRefundUpdateLineAddInput(BaseInputObjectType):+ id = graphene.ID(description="The ID of the order line.", required=True)+ quantity = graphene.Int(+ description="The quantity of line items to be marked to refund.", required=True+ )+ reason = graphene.String(description="Reason of the granted refund for the line.")+class Meta:doc_category = DOC_CATEGORY_ORDERSclass OrderGrantRefundUpdateInput(BaseInputObjectType):- amount = Decimal(description="Amount of the granted refund.")+ amount = Decimal(+ description=(+ "Amount of the granted refund. if not provided and `addLines` or "+ "`removeLines` or `grantRefundForShipping` is provided, amount will be "+ "calculated automatically."+ )+ )reason = graphene.String(description="Reason of the granted refund.")+ add_lines = NonNullList(+ OrderGrantRefundUpdateLineAddInput,+ description="Lines to assign to granted refund."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ required=False,+ )+ remove_lines = NonNullList(+ graphene.ID,+ description="Lines to remove from granted refund."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ required=False,+ )+ grant_refund_for_shipping = graphene.Boolean(+ description="Determine if granted refund should include shipping costs."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ required=False,+ )class Meta:doc_category = DOC_CATEGORY_ORDERS-class OrderGrantRefundUpdate(ModelMutation):+class OrderGrantRefundUpdate(BaseMutation):order = graphene.Field(Order, description="Order which has assigned updated grant refund.")@@ -47,16 +120,23 @@ class OrderGrantRefundUpdate(ModelMutation):description = "Updates granted refund." + ADDED_IN_313 + PREVIEW_FEATUREpermissions = (OrderPermissions.MANAGE_ORDERS,)error_type_class = OrderGrantRefundUpdateError- model = models.OrderGrantedRefund- object_type = OrderGrantedRefunddoc_category = DOC_CATEGORY_ORDERS@classmethod- def validate_input(cls, amount, reason):- if not amount and not reason:- error_msg = (- "At least amount or reason need to be provided to process update."- )+ def validate_input(cls, input: dict[str, Any]):+ 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)+ if (+ not amount+ and not reason+ and not input_lines+ and not grant_refund_for_shipping+ and not remove_lines+ ):+ error_msg = "At least one field needs to be provided to process update."raise ValidationError({"input": ValidationError(@@ -66,14 +146,191 @@ class OrderGrantRefundUpdate(ModelMutation):)@classmethod- def success_response(cls, instance):- return cls(order=instance.order, granted_refund=instance)+ def clean_remove_lines(+ cls,+ granted_refund: models.OrderGrantedRefund,+ lines_to_remove: list[str],+ errors: list[dict[str, Any]],+ ):+ lines_pk_to_remove = set()+ for line_id in lines_to_remove:+ try:+ _, pk = from_global_id_or_error(+ line_id, only_type="OrderGrantedRefundLine", raise_error=True+ )+ lines_pk_to_remove.add(int(pk))+ except GraphQLError as e:+ errors.append(+ {+ "line_id": line_id,+ "code": OrderGrantRefundUpdateLineErrorCode.GRAPHQL_ERROR.value,+ "message": str(e),+ }+ )+ line_ids_from_granted_refund = granted_refund.lines.filter(+ id__in=lines_pk_to_remove+ ).values_list("id", flat=True)+ invalid_ids = lines_pk_to_remove.difference(set(line_ids_from_granted_refund))+ if invalid_ids:+ for invalid_id in invalid_ids:+ errors.append(+ {+ "line_id": graphene.Node.to_global_id(+ "OrderGrantedRefundLine", invalid_id+ ),+ "message": "Could not resolve to a line.",+ "code": OrderGrantRefundUpdateLineErrorCode.NOT_FOUND.value,+ }+ )++ return lines_pk_to_remove@classmethod- def clean_input(cls, info, instance, data, input_cls=None):- cleaned_input = super().clean_input(info, instance, data, input_cls=input_cls)- amount = cleaned_input.pop("amount", None)- cls.validate_input(amount, data.get("reason"))- if amount is not None:- cleaned_input["amount_value"] = amount- return cleaned_input+ def clean_add_lines(+ cls,+ order: models.Order,+ lines: list[dict[str, Union[str, int]]],+ errors: list[dict[str, Any]],+ line_ids_exclude: list[int],+ ) -> list[models.OrderGrantedRefundLine]:+ input_lines_data = get_input_lines_data(+ lines, errors, OrderGrantRefundUpdateLineErrorCode.GRAPHQL_ERROR.value+ )+ assign_order_lines(+ order,+ input_lines_data,+ errors,+ OrderGrantRefundUpdateLineErrorCode.NOT_FOUND.value,+ )+ handle_lines_with_quantity_already_refunded(+ order,+ input_lines_data,+ errors,+ OrderGrantRefundUpdateLineErrorCode.QUANTITY_GREATER_THAN_AVAILABLE.value,+ granted_refund_lines_to_exclude=line_ids_exclude,+ )++ return list(input_lines_data.values())++ @classmethod+ def clean_input(+ cls,+ 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)+ order = granted_refund.order+ amount = input.get("amount")+ reason = input.get("reason", None)+ add_lines = input.get("add_lines", [])+ remove_lines = input.get("remove_lines", [])+ grant_refund_for_shipping = input.get("grant_refund_for_shipping", None)++ line_ids_to_remove = []+ if remove_lines:+ line_ids_to_remove = cls.clean_remove_lines(+ granted_refund, remove_lines, remove_errors+ )++ if remove_errors:+ errors["remove_lines"] = ValidationError(+ "Provided input for lines is invalid.",+ code=OrderGrantRefundUpdateErrorCode.INVALID.value,+ params={"remove_lines": remove_errors},+ )++ lines_to_add = []+ if add_lines:+ lines_to_add = cls.clean_add_lines(+ order, add_lines, add_errors, line_ids_to_remove+ )+ for line in lines_to_add:+ line.granted_refund = granted_refund++ if add_errors:+ errors["add_lines"] = ValidationError(+ "Provided input for lines is invalid.",+ code=OrderGrantRefundUpdateErrorCode.INVALID.value,+ params={"add_lines": add_errors},+ )++ if grant_refund_for_shipping and shipping_costs_already_granted(order):+ error_code = OrderGrantRefundUpdateErrorCode.SHIPPING_COSTS_ALREADY_GRANTED+ errors["grant_refund_for_shipping"] = ValidationError(+ "Shipping costs have already been granted.",+ code=error_code.value,+ )++ if errors:+ raise ValidationError(errors)++ return {+ "amount": amount,+ "reason": reason,+ "add_lines": lines_to_add,+ "remove_lines": line_ids_to_remove,+ "grant_refund_for_shipping": grant_refund_for_shipping,+ }++ @classmethod+ def process_update_for_granted_refund(+ cls,+ order: models.Order,+ granted_refund: models.OrderGrantedRefund,+ cleaned_input: dict,+ ):+ lines_to_remove = cleaned_input.get("remove_lines")+ lines_to_add = cleaned_input.get("add_lines")+ grant_refund_for_shipping = cleaned_input.get("grant_refund_for_shipping")+ if grant_refund_for_shipping is not None:+ granted_refund.shipping_costs_included = grant_refund_for_shipping++ with transaction.atomic():+ if lines_to_remove:+ granted_refund.lines.filter(id__in=lines_to_remove).delete()+ if lines_to_add:+ granted_refund.lines.bulk_create(lines_to_add)++ amount = cleaned_input.get("amount")+ if amount is not None:+ granted_refund.amount_value = amount+ elif amount is None and (+ lines_to_add or lines_to_remove or grant_refund_for_shipping is not None+ ):+ lines = granted_refund.lines.select_related("order_line")+ amount = sum(+ [+ line.order_line.unit_price_gross_amount * line.quantity+ for line in lines+ ]+ )+ if granted_refund.shipping_costs_included:+ amount += order.shipping_price_gross_amount+ granted_refund.amount_value = amount++ reason = cleaned_input.get("reason")+ if reason is not None:+ granted_refund.reason = reason++ granted_refund.save(+ update_fields=[+ "amount_value",+ "reason",+ "shipping_costs_included",+ "updated_at",+ ]+ )++ @classmethod+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, id, input+ ):+ granted_refund = cls.get_node_or_error(info, id, only_type=OrderGrantedRefund)+ order = granted_refund.order++ cleaned_input = cls.clean_input(granted_refund, input)+ cls.process_update_for_granted_refund(order, granted_refund, cleaned_input)+ 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.pynew file mode 100644index 0000000000..c9799433b6--- /dev/null+++ b/saleor/graphql/order/mutations/order_grant_refund_utils.py@@ -0,0 +1,118 @@+import uuid+from collections import defaultdict+from typing import Any, Optional, Union, cast++import graphene+from graphql import GraphQLError++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):+ return True+ return False+++def handle_lines_with_quantity_already_refunded(+ order: models.Order,+ input_lines_data: dict[uuid.UUID, models.OrderGrantedRefundLine],+ errors: list[dict[str, Any]],+ error_code: str,+ granted_refund_lines_to_exclude: Optional[list[int]] = None,+):+ all_granted_refund_ids = order.granted_refunds.all().values_list("id", flat=True)+ all_granted_refund_lines = models.OrderGrantedRefundLine.objects.filter(+ granted_refund_id__in=all_granted_refund_ids+ )+ if granted_refund_lines_to_exclude:+ all_granted_refund_lines.exclude(pk__in=granted_refund_lines_to_exclude)++ lines_with_quantity_already_refunded: dict[uuid.UUID, int] = defaultdict(int)+ for line in all_granted_refund_lines:+ lines_with_quantity_already_refunded[line.order_line_id] += line.quantity++ for granted_refund_line in input_lines_data.values():+ if not granted_refund_line.order_line:+ continue++ quantity_already_refunded = lines_with_quantity_already_refunded[+ granted_refund_line.order_line.pk+ ]++ if (+ granted_refund_line.quantity + quantity_already_refunded+ > granted_refund_line.order_line.quantity+ ):+ available_quantity = (+ granted_refund_line.order_line.quantity - quantity_already_refunded+ )+ errors.append(+ {+ "line_id": graphene.Node.to_global_id(+ "OrderLine", granted_refund_line.order_line.pk+ ),+ "field": "quantity",+ "message": (+ "Cannot grant refund for more than the available quantity "+ f"of the line ({available_quantity})."+ ),+ "code": error_code,+ }+ )+++def get_input_lines_data(+ lines: list[dict[str, Union[str, int]]],+ errors: list[dict[str, str]],+ error_code: str,+) -> dict[uuid.UUID, models.OrderGrantedRefundLine]:+ granted_refund_lines = {}+ for line in lines:+ order_line_id = cast(str, line["id"])+ try:+ _, pk = from_global_id_or_error(+ order_line_id, only_type="OrderLine", raise_error=True+ )+ uuid_pk = uuid.UUID(pk)+ reason = cast(Optional[str], line.get("reason"))+ granted_refund_lines[uuid_pk] = models.OrderGrantedRefundLine(+ order_line_id=uuid_pk,+ quantity=int(line["quantity"]),+ reason=reason,+ )+ except (GraphQLError, ValueError) as e:+ errors.append(+ {+ "line_id": order_line_id,+ "field": "id",+ "code": error_code,+ "message": str(e),+ }+ )+ return granted_refund_lines+++def assign_order_lines(+ order: models.Order,+ input_lines_data: dict[uuid.UUID, models.OrderGrantedRefundLine],+ errors: list[dict[str, str]],+ error_code: str,+):+ input_line_ids = list(input_lines_data.keys())+ lines = order.lines.filter(id__in=input_line_ids)+ lines_dict = {line.pk: line for line in lines}+ if len(lines_dict.keys()) != len(input_line_ids):+ invalid_ids = set(input_line_ids).difference(set(lines_dict.keys()))+ for invalid_id in invalid_ids:+ errors.append(+ {+ "line_id": graphene.Node.to_global_id("OrderLine", invalid_id),+ "field": "id",+ "message": "Could not resolve to a line.",+ "code": error_code,+ }+ )+ for line_pk, order_line in lines_dict.items():+ input_lines_data[line_pk].order_line = order_linediff --git a/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.pyindex ad57366e71..cb29a56d40 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@@ -1,8 +1,15 @@from decimal import Decimal+import graphene++from saleor.core.prices import quantize_price+from ....core.utils import to_global_id_or_nonefrom ....tests.utils import assert_no_permission, get_graphql_content-from ...enums import OrderGrantRefundCreateErrorCode+from ...enums import (+ OrderGrantRefundCreateErrorCode,+ OrderGrantRefundCreateLineErrorCode,+)ORDER_GRANT_REFUND_CREATE = """mutation OrderGrantRefundCreate(@@ -23,6 +30,15 @@ mutation OrderGrantRefundCreate(app{id}+ shippingCostsIncluded+ lines{+ id+ orderLine{+ id+ }+ quantity+ reason+ }}order{id@@ -40,11 +56,26 @@ mutation OrderGrantRefundCreate(user{id}+ shippingCostsIncluded+ lines{+ id+ orderLine{+ id+ }+ quantity+ reason+ }}}errors{fieldcode+ lines{+ field+ code+ lineId+ message+ }}}}@@ -189,3 +220,467 @@ def test_grant_refund_incorrect_order_id(staff_api_client, permission_manage_ordassert len(errors) == 1assert errors[0]["field"] == "id"assert errors[0]["code"] == OrderGrantRefundCreateErrorCode.GRAPHQL_ERROR.name+++def test_grant_refund_with_only_include_grant_refund_for_shipping(+ staff_api_client, permission_manage_orders, order_with_lines+):+ # given+ order_id = to_global_id_or_none(order_with_lines)+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": order_id,+ "input": {"grantRefundForShipping": True},+ }++ # when+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundCreate"]+ errors = data["errors"]+ assert not errors++ assert order_id == data["order"]["id"]+ assert len(data["order"]["grantedRefunds"]) == 1+ granted_refund_from_db = order_with_lines.granted_refunds.first()+ order_granted_refund = data["order"]["grantedRefunds"][0]+ assert (+ granted_refund_from_db.shipping_costs_included+ == order_granted_refund["shippingCostsIncluded"]+ is True+ )+ assert data["grantedRefund"]["shippingCostsIncluded"] is True+ assert (+ granted_refund_from_db.amount_value+ == order_with_lines.shipping_price_gross_amount+ )+++def test_grant_refund_with_only_lines(+ staff_api_client, permission_manage_orders, order_with_lines+):+ # given+ order = order_with_lines+ order_id = to_global_id_or_none(order)+ first_line = order.lines.first()+ staff_api_client.user.user_permissions.add(permission_manage_orders)++ expected_reason = "Reason"+ variables = {+ "id": order_id,+ "input": {+ "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++ assert order_id == data["order"]["id"]+ assert len(data["order"]["grantedRefunds"]) == 1++ granted_refund_from_db = order.granted_refunds.first()+ 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 granted_refund_from_db.amount_value == first_line.unit_price_gross_amount * 1+ 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_include_grant_refund_for_shipping_and_lines(+ staff_api_client, permission_manage_orders, order_with_lines+):+ # given+ order = order_with_lines+ order_id = to_global_id_or_none(order)+ first_line = order.lines.first()+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": order_id,+ "input": {+ "grantRefundForShipping": True,+ "lines": [{"id": to_global_id_or_none(first_line), "quantity": 1}],+ },+ }++ # when+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundCreate"]+ errors = data["errors"]+ assert not errors++ assert order_id == data["order"]["id"]+ assert len(data["order"]["grantedRefunds"]) == 1+ granted_refund_from_db = order.granted_refunds.first()+ order_granted_refund = data["order"]["grantedRefunds"][0]+ assert (+ granted_refund_from_db.shipping_costs_included+ == order_granted_refund["shippingCostsIncluded"]+ is True+ )+ assert data["grantedRefund"]["shippingCostsIncluded"] is True+ 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 granted_refund_from_db.amount_value == (+ first_line.unit_price_gross_amount * 1 + order.shipping_price_gross_amount+ )+ 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+++def test_grant_refund_with_provided_lines_shipping_and_amount(+ staff_api_client, permission_manage_orders, order_with_lines+):+ # given+ order = order_with_lines+ order_id = to_global_id_or_none(order)+ first_line = order.lines.first()+ expected_amount = Decimal("10.0")+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": order_id,+ "input": {+ "grantRefundForShipping": True,+ "lines": [{"id": to_global_id_or_none(first_line), "quantity": 1}],+ "amount": expected_amount,+ },+ }++ # when+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundCreate"]+ errors = data["errors"]+ assert not errors++ assert order_id == data["order"]["id"]+ assert len(data["order"]["grantedRefunds"]) == 1+ granted_refund_from_db = order.granted_refunds.first()+ order_granted_refund = data["order"]["grantedRefunds"][0]+ assert (+ granted_refund_from_db.shipping_costs_included+ == order_granted_refund["shippingCostsIncluded"]+ is True+ )+ assert data["grantedRefund"]["shippingCostsIncluded"] is True+ 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 granted_refund_from_db.amount_value == expected_amount+ 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+++def test_grant_refund_without_lines_and_amount_and_grant_for_shipping(+ staff_api_client, permission_manage_orders, order_with_lines+):+ # given+ order = order_with_lines+ order_id = to_global_id_or_none(order)+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": order_id,+ "input": {+ "reason": "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) == 3+ assert set([error["field"] for error in errors]) == {+ "amount",+ "lines",+ "grantRefundForShipping",+ }+ assert set([error["code"] for error in errors]) == {"REQUIRED"}+++def test_grant_refund_with_incorrect_line_id(+ staff_api_client, permission_manage_orders, order_with_lines+):+ # given+ order = order_with_lines+ order_id = to_global_id_or_none(order)+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": order_id,+ "input": {+ "lines": [+ {"id": graphene.Node.to_global_id("OrderLine", 1), "quantity": 1}+ ],+ },+ }++ # when+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundCreate"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "lines"+ assert error["code"] == OrderGrantRefundCreateErrorCode.INVALID.name+ assert len(error["lines"]) == 1+ line = error["lines"][0]+ assert line["lineId"] == graphene.Node.to_global_id("OrderLine", 1)+ assert line["field"] == "id"+ assert line["code"] == OrderGrantRefundCreateLineErrorCode.GRAPHQL_ERROR.name+++def test_grant_refund_with_line_that_belongs_to_another_order(+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+ order_with_lines_for_cc,+):+ # given+ order = order_with_lines+ another_order = order_with_lines_for_cc+ another_order_id = to_global_id_or_none(another_order)+ first_line = order.lines.first()+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": another_order_id,+ "input": {+ "lines": [{"id": to_global_id_or_none(first_line), "quantity": 1}],+ },+ }++ # when+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundCreate"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "lines"+ assert error["code"] == OrderGrantRefundCreateErrorCode.INVALID.name+ assert len(error["lines"]) == 1+ line = error["lines"][0]+ assert line["lineId"] == to_global_id_or_none(first_line)+ assert line["field"] == "id"+ assert line["code"] == OrderGrantRefundCreateLineErrorCode.NOT_FOUND.name+++def test_grant_refund_with_bigger_quantity_than_available(+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+):+ # given+ order = order_with_lines+ order_id = to_global_id_or_none(order)+ first_line = order.lines.first()+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": order_id,+ "input": {+ "lines": [{"id": to_global_id_or_none(first_line), "quantity": 100}],+ },+ }++ # when+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundCreate"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "lines"+ assert error["code"] == OrderGrantRefundCreateErrorCode.INVALID.name+ assert len(error["lines"]) == 1+ line = error["lines"][0]+ assert line["lineId"] == to_global_id_or_none(first_line)+ assert line["field"] == "quantity"+ assert (+ line["code"]+ == OrderGrantRefundCreateLineErrorCode.QUANTITY_GREATER_THAN_AVAILABLE.name+ )+++def test_grant_refund_with_refund_for_shipping_already_processed(+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+):+ # given+ order = order_with_lines+ order_id = to_global_id_or_none(order)+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": order_id,+ "input": {+ "grantRefundForShipping": True,+ },+ }+ order.granted_refunds.create(shipping_costs_included=True)++ # when+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundCreate"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "grantRefundForShipping"+ assert (+ error["code"]+ == OrderGrantRefundCreateErrorCode.SHIPPING_COSTS_ALREADY_GRANTED.name+ )+++def test_grant_refund_with_lines_and_existing_other_grant_refund(+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+):+ # given+ order = order_with_lines+ order_id = to_global_id_or_none(order)+ first_line = order.lines.first()+ first_line.quantity = 2+ first_line.save(update_fields=["quantity"])++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": order_id,+ "input": {+ "lines": [{"id": to_global_id_or_none(first_line), "quantity": 1}],+ },+ }+ granted_refund = order.granted_refunds.create(shipping_costs_included=False)+ granted_refund.lines.create(order_line=first_line, quantity=1)++ # when+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundCreate"]+ errors = data["errors"]+ assert not errors++ assert order_id == data["order"]["id"]+ assert len(data["order"]["grantedRefunds"]) == 2++ granted_refund_from_db = order.granted_refunds.last()+ order_granted_refund = data["order"]["grantedRefunds"][1]+ 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 granted_refund_from_db.amount_value == first_line.unit_price_gross_amount * 1+ assert quantize_price(+ granted_refund_from_db.amount_value, order.currency+ ) == quantize_price(+ Decimal(order_granted_refund["amount"]["amount"]), order.currency+ )+++def test_grant_refund_with_lines_and_existing_other_grant_and_refund_exceeding_quantity(+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+):+ # given+ order = order_with_lines+ order_id = to_global_id_or_none(order)+ first_line = order.lines.first()+ first_line.quantity = 1+ first_line.save(update_fields=["quantity"])++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ variables = {+ "id": order_id,+ "input": {+ "lines": [{"id": to_global_id_or_none(first_line), "quantity": 1}],+ },+ }+ granted_refund = order.granted_refunds.create(shipping_costs_included=False)+ granted_refund.lines.create(order_line=first_line, quantity=1)++ # when+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundCreate"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "lines"+ assert error["code"] == OrderGrantRefundCreateErrorCode.INVALID.name+ assert len(error["lines"]) == 1+ line = error["lines"][0]+ assert line["lineId"] == to_global_id_or_none(first_line)+ assert line["field"] == "quantity"+ assert (+ line["code"]+ == OrderGrantRefundCreateLineErrorCode.QUANTITY_GREATER_THAN_AVAILABLE.name+ )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.pyindex 68ce720208..27e4aa2f64 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,12 +1,17 @@from decimal import Decimal+from saleor.core.prices import quantize_price+from ....core.utils import to_global_id_or_nonefrom ....tests.utils import (assert_no_permission,get_graphql_content,get_graphql_content_from_response,)-from ...enums import OrderGrantRefundUpdateErrorCode+from ...enums import (+ OrderGrantRefundUpdateErrorCode,+ OrderGrantRefundUpdateLineErrorCode,+)ORDER_GRANT_REFUND_UPDATE = """mutation OrderGrantRefundUpdate(@@ -27,6 +32,15 @@ mutation OrderGrantRefundUpdate(app {id}+ shippingCostsIncluded+ lines{+ id+ orderLine{+ id+ }+ quantity+ reason+ }}order {id@@ -44,11 +58,33 @@ mutation OrderGrantRefundUpdate(user{id}+ shippingCostsIncluded+ lines{+ id+ orderLine{+ id+ }+ quantity+ reason+ }}}errors {fieldcode+ message+ addLines{+ field+ code+ lineId+ message+ }+ removeLines{+ field+ code+ lineId+ message+ }}}}@@ -422,3 +458,701 @@ def test_grant_refund_update_by_app_missing_input(assert len(errors) == 1assert errors[0]["code"] == OrderGrantRefundUpdateErrorCode.REQUIRED.nameassert errors[0]["field"] == "input"+++def test_grant_refund_update_include_grant_refund_for_shipping(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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,+ )+ granted_refund_id = to_global_id_or_none(granted_refund)+ app_api_client.app.permissions.set([permission_manage_orders])++ variables = {+ "id": granted_refund_id,+ "input": {"grantRefundForShipping": True},+ }++ # when+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderGrantRefundUpdate"]+ assert not data["errors"]++ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]+ assert granted_refund_assigned_to_order["id"] == data["grantedRefund"]["id"]+ granted_refund.refresh_from_db()+ assert (+ granted_refund.shipping_costs_included+ == granted_refund_assigned_to_order["shippingCostsIncluded"]+ is True+ )+ assert granted_refund_assigned_to_order["shippingCostsIncluded"] is True+ assert granted_refund.amount_value == order_with_lines.shipping_price_gross_amount+ assert quantize_price(+ granted_refund.amount_value, order_with_lines.currency+ ) == quantize_price(+ Decimal(granted_refund_assigned_to_order["amount"]["amount"]),+ order_with_lines.currency,+ )+++def test_grant_refund_update_with_only_add_lines(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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"++ variables = {+ "id": granted_refund_id,+ "input": {+ "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+ == order_line.unit_price_gross_amount * expected_quantity+ )+ assert quantize_price(+ granted_refund.amount_value, order_with_lines.currency+ ) == quantize_price(+ Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency+ )+++def test_grant_refund_update_with_only_remove_lines(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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)+ app_api_client.app.permissions.set([permission_manage_orders])++ variables = {+ "id": granted_refund_id,+ "input": {"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 len(granted_refund_data["lines"]) == 0+ assert len(granted_refund.lines.all()) == 0++ assert granted_refund.amount_value == 0+ assert quantize_price(+ granted_refund.amount_value, order_with_lines.currency+ ) == quantize_price(+ Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency+ )+++def test_grant_refund_update_with_add_and_remove_lines(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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,+ )+ last_order_line = order_with_lines.lines.last()+ granted_refund_line_to_remove = granted_refund.lines.create(+ order_line=last_order_line, quantity=1+ )++ 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++ variables = {+ "id": granted_refund_id,+ "input": {+ "addLines": [+ {"id": to_global_id_or_none(order_line), "quantity": expected_quantity}+ ],+ "removeLines": [to_global_id_or_none(granted_refund_line_to_remove)],+ },+ }++ # 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 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.amount_value+ == order_line.unit_price_gross_amount * expected_quantity+ )+ assert quantize_price(+ granted_refund.amount_value, order_with_lines.currency+ ) == quantize_price(+ Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency+ )+++def test_grant_refund_update_with_add_and_remove_lines_and_shipping_included(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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,+ )+ last_order_line = order_with_lines.lines.last()+ granted_refund_line_to_remove = granted_refund.lines.create(+ order_line=last_order_line, quantity=1+ )++ 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++ variables = {+ "id": granted_refund_id,+ "input": {+ "addLines": [+ {"id": to_global_id_or_none(order_line), "quantity": expected_quantity}+ ],+ "removeLines": [to_global_id_or_none(granted_refund_line_to_remove)],+ "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 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 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.amount_value+ == order_line.unit_price_gross_amount * expected_quantity+ + order_with_lines.shipping_price_gross_amount+ )+ assert quantize_price(+ granted_refund.amount_value, order_with_lines.currency+ ) == quantize_price(+ Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency+ )+++def test_grant_refund_update_with_add_and_remove_lines_and_shipping_included_and_amount(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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,+ )+ last_order_line = order_with_lines.lines.last()+ granted_refund_line_to_remove = granted_refund.lines.create(+ order_line=last_order_line, quantity=1+ )++ 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_amount = Decimal("20.000")++ variables = {+ "id": granted_refund_id,+ "input": {+ "amount": expected_amount,+ "addLines": [+ {"id": to_global_id_or_none(order_line), "quantity": expected_quantity}+ ],+ "removeLines": [to_global_id_or_none(granted_refund_line_to_remove)],+ "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 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 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.amount_value == expected_amount+ assert quantize_price(+ granted_refund.amount_value, order_with_lines.currency+ ) == quantize_price(+ Decimal(granted_refund_data["amount"]["amount"]), order_with_lines.currency+ )+++def test_grant_refund_update_with_incorrect_add_line_id(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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,+ )+ granted_refund_id = to_global_id_or_none(granted_refund)+ app_api_client.app.permissions.set([permission_manage_orders])++ expected_quantity = 1++ variables = {+ "id": granted_refund_id,+ "input": {"addLines": [{"id": "incorrect-id", "quantity": expected_quantity}]},+ }++ # 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"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "addLines"+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name+ assert len(error["addLines"]) == 1+ line = error["addLines"][0]+ assert line["lineId"] == "incorrect-id"+ assert line["field"] == "id"+ assert line["code"] == OrderGrantRefundUpdateLineErrorCode.GRAPHQL_ERROR.name+ assert len(granted_refund.lines.all()) == 0+++def test_grant_refund_update_with_incorrect_remove_line_id(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ current_reason = "Granted refund reason."+ current_amount = Decimal("10.00")+ order_line = order_with_lines.lines.first()+ 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_line = granted_refund.lines.create(order_line=order_line, quantity=1)++ granted_refund_id = to_global_id_or_none(granted_refund)+ app_api_client.app.permissions.set([permission_manage_orders])++ variables = {+ "id": granted_refund_id,+ "input": {"removeLines": ["incorrect-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"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "removeLines"+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name+ assert len(error["removeLines"]) == 1+ line = error["removeLines"][0]+ assert line["lineId"] == "incorrect-id"+ assert line["field"] is None+ assert line["code"] == OrderGrantRefundUpdateLineErrorCode.GRAPHQL_ERROR.name+ assert len(granted_refund.lines.all()) == 1+ assert granted_refund.lines.all()[0] == granted_refund_line+++def test_grant_refund_update_with_add_line_belongs_to_another_order(+ app_api_client,+ staff_user,+ permission_manage_orders,+ order_with_lines,+ order_with_lines_for_cc,+):+ # given+ 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_from_another_order = order_with_lines_for_cc.lines.first()+ granted_refund_id = to_global_id_or_none(granted_refund)+ order_line_from_another_order_id = to_global_id_or_none(+ order_line_from_another_order+ )+ app_api_client.app.permissions.set([permission_manage_orders])++ expected_quantity = 1++ variables = {+ "id": granted_refund_id,+ "input": {+ "addLines": [+ {"id": order_line_from_another_order_id, "quantity": expected_quantity}+ ]+ },+ }++ # 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"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "addLines"+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name+ assert len(error["addLines"]) == 1+ line = error["addLines"][0]+ assert line["lineId"] == order_line_from_another_order_id+ assert line["field"] == "id"+ assert line["code"] == OrderGrantRefundUpdateLineErrorCode.NOT_FOUND.name+ assert len(granted_refund.lines.all()) == 0+++def test_grant_refund_update_with_remove_line_belong_to_another_granted_refund(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ current_reason = "Granted refund reason."+ current_amount = Decimal("10.00")+ order_line = order_with_lines.lines.first()+ 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_line = granted_refund.lines.create(order_line=order_line, quantity=1)++ second_granted_refund = order_with_lines.granted_refunds.create(+ amount_value=current_amount,+ currency=order_with_lines.currency,+ reason=current_reason,+ user=staff_user,+ )++ second_granted_refund_id = to_global_id_or_none(second_granted_refund)+ granted_refund_line_id = to_global_id_or_none(granted_refund_line)++ app_api_client.app.permissions.set([permission_manage_orders])++ variables = {+ "id": second_granted_refund_id,+ "input": {"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"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "removeLines"+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name+ assert len(error["removeLines"]) == 1+ line = error["removeLines"][0]+ assert line["lineId"] == granted_refund_line_id+ assert line["field"] is None+ assert line["code"] == OrderGrantRefundUpdateLineErrorCode.NOT_FOUND.name+++def test_grant_refund_update_with_add_line_quantity_bigger_than_order_line_quantity(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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)+ order_line_id = to_global_id_or_none(order_line)+ app_api_client.app.permissions.set([permission_manage_orders])++ expected_quantity = 100++ variables = {+ "id": granted_refund_id,+ "input": {"addLines": [{"id": order_line_id, "quantity": expected_quantity}]},+ }++ # 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"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "addLines"+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name+ assert len(error["addLines"]) == 1+ line = error["addLines"][0]+ assert line["lineId"] == order_line_id+ assert line["field"] == "quantity"+ assert (+ line["code"]+ == OrderGrantRefundUpdateLineErrorCode.QUANTITY_GREATER_THAN_AVAILABLE.name+ )+ assert len(granted_refund.lines.all()) == 0+++def test_grant_refund_update_with_add_line_quantity_bigger_than_available_quantity(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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()+ second_granted_refund = order_with_lines.granted_refunds.create(+ amount_value=current_amount,+ currency=order_with_lines.currency,+ reason=current_reason,+ user=staff_user,+ )+ second_granted_refund.lines.create(+ order_line=order_line, quantity=order_line.quantity+ )+ granted_refund_id = to_global_id_or_none(granted_refund)+ order_line_id = to_global_id_or_none(order_line)+ app_api_client.app.permissions.set([permission_manage_orders])++ expected_quantity = 1++ variables = {+ "id": granted_refund_id,+ "input": {"addLines": [{"id": order_line_id, "quantity": expected_quantity}]},+ }++ # 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"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "addLines"+ assert error["code"] == OrderGrantRefundUpdateErrorCode.INVALID.name+ assert len(error["addLines"]) == 1+ line = error["addLines"][0]+ assert line["lineId"] == order_line_id+ assert line["field"] == "quantity"+ assert (+ line["code"]+ == OrderGrantRefundUpdateLineErrorCode.QUANTITY_GREATER_THAN_AVAILABLE.name+ )+ assert len(granted_refund.lines.all()) == 0+++def test_grant_refund_update_with_shipping_cost_already_included(+ app_api_client, staff_user, permission_manage_orders, order_with_lines+):+ # given+ 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()+ order_with_lines.granted_refunds.create(+ amount_value=current_amount,+ currency=order_with_lines.currency,+ reason=current_reason,+ user=staff_user,+ shipping_costs_included=True,+ )+ granted_refund_id = to_global_id_or_none(granted_refund)+ order_line_id = to_global_id_or_none(order_line)+ app_api_client.app.permissions.set([permission_manage_orders])++ expected_quantity = 1++ variables = {+ "id": granted_refund_id,+ "input": {+ "addLines": [{"id": order_line_id, "quantity": expected_quantity}],+ "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"]+ errors = data["errors"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "grantRefundForShipping"+ assert (+ error["code"]+ == OrderGrantRefundUpdateErrorCode.SHIPPING_COSTS_ALREADY_GRANTED.name+ )+ assert len(granted_refund.lines.all()) == 0diff --git a/saleor/graphql/order/tests/queries/test_order_granted_refunds.py b/saleor/graphql/order/tests/queries/test_order_granted_refunds.pyindex 70714b8c92..0e5e01f650 100644--- a/saleor/graphql/order/tests/queries/test_order_granted_refunds.py+++ b/saleor/graphql/order/tests/queries/test_order_granted_refunds.py@@ -30,6 +30,14 @@ query OrdersQuery {app{id}+ shippingCostsIncluded+ lines{+ id+ orderLine{+ id+ }+ quantity+ }}}}@@ -38,7 +46,7 @@ query OrdersQuery {"""-def test_order_granted_refunds_query_by_user(+def test_order_granted_refunds_query_without_lines_by_user(staff_user,app,staff_api_client,@@ -89,6 +97,8 @@ def test_order_granted_refunds_query_by_user("reason": first_granted_refund.reason,"user": {"id": to_global_id_or_none(first_granted_refund.user)},"app": None,+ "shippingCostsIncluded": False,+ "lines": [],},{"id": to_global_id_or_none(second_granted_refund),@@ -101,11 +111,13 @@ def test_order_granted_refunds_query_by_user("reason": second_granted_refund.reason,"app": {"id": to_global_id_or_none(second_granted_refund.app)},"user": None,+ "shippingCostsIncluded": False,+ "lines": [],},]-def test_order_granted_refunds_query_by_app(+def test_order_granted_refunds_query_without_lines_by_app(staff_user,app,app_api_client,@@ -138,35 +150,8 @@ def test_order_granted_refunds_query_by_app([permission_manage_orders, permission_manage_shipping, permission_manage_users])- query = """- query OrdersQuery {- orders(first: 1) {- edges {- node {- number- grantedRefunds{- id- createdAt- updatedAt- amount{- amount- currency- }- reason- user{- id- }- app{- id- }- }- }- }- }- }- """# when- response = app_api_client.post_graphql(query)+ response = app_api_client.post_graphql(ORDERS_QUERY)content = get_graphql_content(response)# then@@ -185,6 +170,8 @@ def test_order_granted_refunds_query_by_app("reason": first_granted_refund.reason,"user": {"id": to_global_id_or_none(first_granted_refund.user)},"app": None,+ "shippingCostsIncluded": False,+ "lines": [],},{"id": to_global_id_or_none(second_granted_refund),@@ -197,6 +184,140 @@ def test_order_granted_refunds_query_by_app("reason": second_granted_refund.reason,"app": {"id": to_global_id_or_none(second_granted_refund.app)},"user": None,+ "shippingCostsIncluded": False,+ "lines": [],+ },+ ]+++def test_order_granted_refunds_query_by_user(+ staff_user,+ app,+ staff_api_client,+ permission_group_manage_orders,+ permission_manage_shipping,+ fulfilled_order,+ shipping_zone,+):+ # given+ order = fulfilled_order+ net = Money(amount=Decimal("10"), currency="USD")+ gross = Money(amount=net.amount * Decimal(1.23), currency="USD").quantize()+ shipping_price = TaxedMoney(net=net, gross=gross)+ order.shipping_price = shipping_price+ shipping_tax_rate = Decimal("0.23")+ order.shipping_tax_rate = shipping_tax_rate+ order.save()+ granted_refund = order.granted_refunds.create(+ amount_value=Decimal("10.0"),+ currency="USD",+ reason="Test reason",+ user=staff_user,+ shipping_costs_included=True,+ )+ order_line = order.lines.first()+ granted_refund_line = granted_refund.lines.create(order_line=order_line, quantity=1)++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ staff_api_client.user.user_permissions.add(permission_manage_shipping)++ # when+ response = staff_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 == [+ {+ "id": to_global_id_or_none(granted_refund),+ "createdAt": granted_refund.created_at.isoformat(),+ "updatedAt": granted_refund.updated_at.isoformat(),+ "amount": {+ "amount": float(granted_refund.amount.amount),+ "currency": granted_refund.currency,+ },+ "reason": granted_refund.reason,+ "user": {"id": to_global_id_or_none(granted_refund.user)},+ "app": None,+ "shippingCostsIncluded": True,+ "lines": [+ {+ "id": to_global_id_or_none(granted_refund_line),+ "quantity": granted_refund_line.quantity,+ "orderLine": {+ "id": to_global_id_or_none(order_line),+ },+ }+ ],+ },+ ]+++def test_order_granted_refunds_query_by_app(+ staff_user,+ app,+ app_api_client,+ permission_manage_orders,+ permission_manage_shipping,+ permission_manage_users,+ fulfilled_order,+ shipping_zone,+):+ # given+ order = fulfilled_order+ net = Money(amount=Decimal("10"), currency="USD")+ gross = Money(amount=net.amount * Decimal(1.23), currency="USD").quantize()+ shipping_price = TaxedMoney(net=net, gross=gross)+ order.shipping_price = shipping_price+ shipping_tax_rate = Decimal("0.23")+ order.shipping_tax_rate = shipping_tax_rate+ order.save()+ granted_refund = order.granted_refunds.create(+ amount_value=Decimal("10.0"),+ currency="USD",+ reason="Test reason",+ app=app,+ shipping_costs_included=True,+ )+ order_line = order.lines.first()+ granted_refund_line = granted_refund.lines.create(order_line=order_line, quantity=1)++ 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 == [+ {+ "id": to_global_id_or_none(granted_refund),+ "createdAt": granted_refund.created_at.isoformat(),+ "updatedAt": granted_refund.updated_at.isoformat(),+ "amount": {+ "amount": float(granted_refund.amount.amount),+ "currency": granted_refund.currency,+ },+ "reason": granted_refund.reason,+ "user": None,+ "app": {"id": to_global_id_or_none(granted_refund.app)},+ "shippingCostsIncluded": True,+ "lines": [+ {+ "id": to_global_id_or_none(granted_refund_line),+ "quantity": granted_refund_line.quantity,+ "orderLine": {+ "id": to_global_id_or_none(order_line),+ },+ }+ ],},]diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 9235e18338..28a10e6b2c 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -145,6 +145,7 @@ from .dataloaders import (OrderByNumberLoader,OrderEventsByIdLoader,OrderEventsByOrderIdLoader,+ OrderGrantedRefundLinesByOrderGrantedRefundIdLoader,OrderGrantedRefundsByOrderIdLoader,OrderLineByIdLoader,OrderLinesByOrderIdLoader,@@ -196,7 +197,26 @@ def get_payment_status_for_order(order):return status-class OrderGrantedRefund(ModelObjectType):+class OrderGrantedRefundLine(ModelObjectType[models.OrderGrantedRefundLine]):+ id = graphene.GlobalID(required=True)+ quantity = graphene.Int(description="Number of items to refund.", required=True)+ order_line = graphene.Field(+ "saleor.graphql.order.types.OrderLine",+ description="Line of the order associated with this granted refund.",+ required=True,+ )+ reason = graphene.String(description="Reason for refunding the line.")++ class Meta:+ description = "Represents granted refund line." + ADDED_IN_315 + PREVIEW_FEATURE+ model = models.OrderGrantedRefundLine++ @staticmethod+ def resolve_order_line(root: models.OrderGrantedRefundLine, info):+ return OrderLineByIdLoader(info.context).load(root.order_line_id)+++class OrderGrantedRefund(ModelObjectType[models.OrderGrantedRefund]):id = graphene.GlobalID(required=True)created_at = graphene.DateTime(required=True, description="Time of creation.")updated_at = graphene.DateTime(required=True, description="Time of last update.")@@ -212,6 +232,21 @@ class OrderGrantedRefund(ModelObjectType):),)app = graphene.Field(App, description=("App that performed the action."))+ shipping_costs_included = graphene.Boolean(+ required=True,+ description=(+ "If true, the refunded amount includes the shipping price."+ "If false, the refunded amount does not include the shipping price."+ + ADDED_IN_315+ + PREVIEW_FEATURE+ ),+ )+ lines = NonNullList(+ OrderGrantedRefundLine,+ description="Lines assigned to the granted refund."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ )class Meta:description = "The details of granted refund." + ADDED_IN_313 + PREVIEW_FEATURE@@ -242,6 +277,12 @@ class OrderGrantedRefund(ModelObjectType):return AppByIdLoader(info.context).load(root.app_id)return None+ @staticmethod+ def resolve_lines(root: models.OrderGrantedRefund, info):+ return OrderGrantedRefundLinesByOrderGrantedRefundIdLoader(info.context).load(+ root.id+ )+class OrderDiscount(BaseObjectType):value_type = graphene.Field(diff --git a/saleor/graphql/payment/mutations/__init__.py b/saleor/graphql/payment/mutations/__init__.pyindex 5d729c1762..a35af7ad13 100644--- a/saleor/graphql/payment/mutations/__init__.py+++ b/saleor/graphql/payment/mutations/__init__.py@@ -13,6 +13,7 @@ from .transaction import (TransactionInitialize,TransactionProcess,TransactionRequestAction,+ TransactionRequestRefundForGrantedRefund,TransactionUpdate,)@@ -30,4 +31,5 @@ __all__ = ["TransactionProcess","TransactionRequestAction","TransactionUpdate",+ "TransactionRequestRefundForGrantedRefund",]diff --git a/saleor/graphql/payment/mutations/transaction/__init__.py b/saleor/graphql/payment/mutations/transaction/__init__.pyindex 81f72c1f05..25469b1a08 100644--- a/saleor/graphql/payment/mutations/transaction/__init__.py+++ b/saleor/graphql/payment/mutations/transaction/__init__.py@@ -3,6 +3,9 @@ from .transaction_event_report import TransactionEventReportfrom .transaction_initialize import TransactionInitializefrom .transaction_process import TransactionProcessfrom .transaction_request_action import TransactionRequestAction+from .transaction_request_refund_for_granted_refund import (+ TransactionRequestRefundForGrantedRefund,+)from .transaction_update import TransactionUpdate__all__ = [@@ -12,4 +15,5 @@ __all__ = ["TransactionProcess","TransactionRequestAction","TransactionUpdate",+ "TransactionRequestRefundForGrantedRefund",]diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py b/saleor/graphql/payment/mutations/transaction/transaction_request_action.pyindex f96d918774..a5609bd971 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py@@ -23,7 +23,6 @@ from ....core.mutations import BaseMutationfrom ....core.scalars import PositiveDecimalfrom ....core.types import common as common_typesfrom ....plugins.dataloaders import get_plugin_manager_promise-from ....utils import get_user_or_app_from_contextfrom ...enums import TransactionActionEnumfrom ...types import TransactionItemfrom .utils import get_transaction_item@@ -60,17 +59,6 @@ class TransactionRequestAction(BaseMutation):error_type_class = common_types.TransactionRequestActionErrorpermissions = (PaymentPermissions.HANDLE_PAYMENTS,)- @classmethod- def check_permissions(cls, context, permissions=None, **data):- required_permissions = permissions or cls._meta.permissions- requestor = get_user_or_app_from_context(context)- for required_permission in required_permissions:- # We want to allow to call this mutation for requestor with one of following- # permission: manage_orders, handle_payments- if requestor and requestor.has_perm(required_permission):- return True- return False-@classmethoddef handle_transaction_action(cls,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.pynew file mode 100644index 0000000000..c5ca81c941--- /dev/null+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py@@ -0,0 +1,119 @@+from typing import TYPE_CHECKING, cast++import graphene+from django.core.exceptions import ValidationError++from .....order import models as order_models+from .....payment import PaymentError, TransactionEventType+from .....payment import models as payment_models+from .....payment.error_codes import TransactionRequestActionErrorCode+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_315, PREVIEW_FEATURE+from ....core.doc_category import DOC_CATEGORY_PAYMENTS+from ....core.enums import TransactionRequestRefundForGrantedRefundErrorCode+from ....core.mutations import BaseMutation+from ....core.types import common as common_types+from ....plugins.dataloaders import get_plugin_manager_promise+from ...types import TransactionItem+from .utils import get_transaction_item++if TYPE_CHECKING:+ pass+++class TransactionRequestRefundForGrantedRefund(BaseMutation):+ transaction = graphene.Field(TransactionItem)++ class Arguments:+ id = graphene.ID(+ description="The ID of the transaction.",+ required=True,+ )+ granted_refund_id = graphene.ID(+ required=True,+ description="The ID of the granted refund.",+ )++ class Meta:+ description = (+ "Request a refund for payment transaction based on granted refund."+ + ADDED_IN_315+ + PREVIEW_FEATURE+ )+ doc_category = DOC_CATEGORY_PAYMENTS+ error_type_class = common_types.TransactionRequestRefundForGrantedRefundError+ permissions = (PaymentPermissions.HANDLE_PAYMENTS,)++ @classmethod+ def clean_input(+ cls, info, transaction_id: str, granted_refund_id: str+ ) -> tuple[payment_models.TransactionItem, order_models.OrderGrantedRefund]:+ transaction_item = get_transaction_item(transaction_id)+ 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"+ ).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,+ ),+ }+ )+ return transaction_item, granted_refund++ @classmethod+ def perform_mutation( # type: ignore[override]+ cls, root, info: ResolveInfo, /, id, granted_refund_id+ ):+ transaction_item, granted_refund = cls.clean_input(info, id, granted_refund_id)+ order = granted_refund.order++ channel = order.channel+ cls.check_channel_permissions(info, [channel.id])+ channel_slug = channel.slug++ app = get_app_promise(info.context).get()+ 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)+ request_event = transaction_item.events.create(+ amount_value=action_value,+ currency=transaction_item.currency,+ type=TransactionEventType.REFUND_REQUEST,+ )++ try:+ request_refund_action(+ transaction=transaction_item,+ manager=manager,+ refund_value=action_value,+ request_event=request_event,+ channel_slug=channel_slug,+ user=info.context.user,+ app=app,+ granted_refund=granted_refund,+ )+ except PaymentError as e:+ error_enum = TransactionRequestActionErrorCode+ code = error_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value+ raise ValidationError(str(e), code=code)+ return cls(transaction=transaction_item)diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.pyindex 77748db08c..25f9b0fc31 100644--- a/saleor/graphql/payment/schema.py+++ b/saleor/graphql/payment/schema.py@@ -20,6 +20,7 @@ from .mutations import (TransactionInitialize,TransactionProcess,TransactionRequestAction,+ TransactionRequestRefundForGrantedRefund,TransactionUpdate,)from .resolvers import resolve_payment_by_id, resolve_payments, resolve_transaction@@ -88,6 +89,9 @@ class PaymentMutations(graphene.ObjectType):transaction_create = TransactionCreate.Field()transaction_update = TransactionUpdate.Field()transaction_request_action = TransactionRequestAction.Field()+ transaction_request_refund_for_granted_refund = (+ TransactionRequestRefundForGrantedRefund.Field()+ )transaction_event_report = TransactionEventReport.Field()payment_gateway_initialize = PaymentGatewayInitialize.Field()diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.pyindex 574a47c668..6d79ec3718 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py@@ -579,7 +579,7 @@ def test_transaction_action_request_uses_handle_payment_permission(def test_transaction_request_action_missing_permission(- app_api_client, order_with_lines+ app_api_client, order_with_lines, permission_manage_orders):# given@@ -599,7 +599,9 @@ def test_transaction_request_action_missing_permission(# whenresponse = app_api_client.post_graphql(- MUTATION_TRANSACTION_REQUEST_ACTION, variables, permissions=[]+ MUTATION_TRANSACTION_REQUEST_ACTION,+ variables,+ permissions=[permission_manage_orders],)# thendiff --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.pynew file mode 100644index 0000000000..7fb400b3f0--- /dev/null+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py@@ -0,0 +1,380 @@+from decimal import Decimal++import graphene+from mock import patch++from .....payment import TransactionAction, TransactionEventType+from .....payment.interface import TransactionActionData+from .....payment.models import TransactionEvent+from .....webhook.event_types import WebhookEventSyncType+from ....core.enums import TransactionRequestRefundForGrantedRefundErrorCode+from ....core.utils import to_global_id_or_none+from ....tests.utils import assert_no_permission, get_graphql_content++TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND = """+mutation TransactionRequestRefundForGrantedRefund($id: ID!, $grantedRefundID: ID!) {+ transactionRequestRefundForGrantedRefund(id: $id, grantedRefundId: $grantedRefundID) {+ transaction {+ id+ events {+ type+ amount {+ amount+ }+ }+ }+ errors {+ field+ message+ code+ }+ }+}+"""+++def test_missing_permission_for_app(+ app_api_client,+ order_with_lines,+ permission_manage_orders,+ transaction_item_generator,+):+ # given+ granted_refund = order_with_lines.granted_refunds.create(+ amount_value=Decimal("10.00")+ )+ transaction_item = transaction_item_generator(+ order_id=order_with_lines.pk, charged_value=order_with_lines.total_gross.amount+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "grantedRefundID": to_global_id_or_none(granted_refund),+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,+ variables,+ permissions=[permission_manage_orders],+ )++ # then+ assert_no_permission(response)+++def test_missing_permission_for_user(+ staff_api_client,+ order_with_lines,+ transaction_item_generator,+ permission_group_no_perms_all_channels,+):+ # given+ permission_group_no_perms_all_channels.user_set.add(staff_api_client.user)+ granted_refund = order_with_lines.granted_refunds.create(+ amount_value=Decimal("10.00")+ )+ transaction_item = transaction_item_generator(+ order_id=order_with_lines.pk, charged_value=order_with_lines.total_gross.amount+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "grantedRefundID": to_global_id_or_none(granted_refund),+ }++ # when+ response = staff_api_client.post_graphql(+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,+ variables,+ )++ # then+ assert_no_permission(response)+++def test_transaction_doesnt_exist(+ app_api_client,+ order_with_lines,+ permission_manage_payments,+):+ # given+ granted_refund = order_with_lines.granted_refunds.create(+ amount_value=Decimal("10.00")+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", "1"),+ "grantedRefundID": to_global_id_or_none(granted_refund),+ }+ # when+ response = app_api_client.post_graphql(+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,+ variables,+ permissions=[permission_manage_payments],+ )++ # then+ error_class = TransactionRequestRefundForGrantedRefundErrorCode+ content = get_graphql_content(response)+ data = content["data"]["transactionRequestRefundForGrantedRefund"]+ assert data["errors"][0]["field"] == "id"+ assert data["errors"][0]["code"] == error_class.NOT_FOUND.name+++def test_granted_refund_doesnt_exist(+ app_api_client,+ order_with_lines,+ permission_manage_payments,+ transaction_item_generator,+):+ # given+ transaction_item = transaction_item_generator(+ order_id=order_with_lines.pk, charged_value=order_with_lines.total_gross.amount+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "grantedRefundID": graphene.Node.to_global_id("OrderGrantedRefund", 1),+ }+ # when+ response = app_api_client.post_graphql(+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,+ variables,+ permissions=[permission_manage_payments],+ )++ # then+ error_class = TransactionRequestRefundForGrantedRefundErrorCode+ content = get_graphql_content(response)++ data = content["data"]["transactionRequestRefundForGrantedRefund"]+ assert data["errors"][0]["field"] == "grantedRefundId"+ assert data["errors"][0]["code"] == error_class.NOT_FOUND.name+++def test_transaction_belongs_to_different_order_than_granted_refund_order(+ app_api_client,+ order_with_lines,+ permission_manage_payments,+ transaction_item_generator,+ order_with_lines_for_cc,+):+ # given+ transaction_item = transaction_item_generator(+ order_id=order_with_lines.pk, charged_value=order_with_lines.total_gross.amount+ )++ granted_refund = order_with_lines_for_cc.granted_refunds.create(+ amount_value=Decimal("10.00")+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "grantedRefundID": to_global_id_or_none(granted_refund),+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,+ variables,+ permissions=[permission_manage_payments],+ )++ # then+ content = get_graphql_content(response)++ error_class = TransactionRequestRefundForGrantedRefundErrorCode+ data = content["data"]["transactionRequestRefundForGrantedRefund"]+ assert len(data["errors"]) == 2+ assert any([err["field"] == "grantedRefundId" for err in data["errors"]])+ assert any([err["field"] == "id" for err in data["errors"]])+ assert all([err["code"] == error_class.INVALID.name for err in data["errors"]])+++@patch("saleor.payment.gateway.get_webhooks_for_event")+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")+def test_missing_assigned_webhook_event(+ mocked_is_active,+ mocked_get_webhooks,+ app_api_client,+ order_with_lines,+ permission_manage_payments,+ transaction_item_generator,+ app,+):+ # given+ transaction_item = transaction_item_generator(+ order_id=order_with_lines.pk,+ charged_value=order_with_lines.total_gross.amount,+ app=app,+ )++ granted_refund = order_with_lines.granted_refunds.create(+ amount_value=Decimal("10.00")+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "grantedRefundID": to_global_id_or_none(granted_refund),+ }++ mocked_get_webhooks.return_value = []+ mocked_is_active.return_value = False++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,+ variables,+ permissions=[permission_manage_payments],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["transactionRequestRefundForGrantedRefund"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["message"] == (+ "No app or plugin is configured to handle payment action requests."+ )+ error_class = TransactionRequestRefundForGrantedRefundErrorCode+ assert data["errors"][0]["code"] == (+ error_class.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.name+ )++ assert mocked_is_active.called+ assert mocked_get_webhooks.called+ mocked_get_webhooks.assert_called_once_with(+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,+ apps_ids=[app.id],+ )+++@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")+def test_triggers_refund_request_for_app(+ mocked_payment_action_request,+ mocked_is_active,+ app_api_client,+ order_with_lines,+ permission_manage_payments,+ transaction_item_generator,+ app,+):+ # given+ app.permissions.set([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=order_with_lines.total_gross.amount,+ app=app,+ )+ expected_refund_amount = Decimal("10.00")+ granted_refund = order_with_lines.granted_refunds.create(+ amount_value=expected_refund_amount+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "grantedRefundID": to_global_id_or_none(granted_refund),+ }++ # when+ response = app_api_client.post_graphql(+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,+ variables,+ )++ get_graphql_content(response)++ 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,+ )+++@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")+def test_triggers_refund_request_for_staff_user(+ 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)+ transaction_item = transaction_item_generator(+ order_id=order_with_lines.pk,+ charged_value=order_with_lines.total_gross.amount,+ app=app,+ )+ expected_refund_amount = Decimal("10.00")+ granted_refund = order_with_lines.granted_refunds.create(+ amount_value=expected_refund_amount+ )++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),+ "grantedRefundID": to_global_id_or_none(granted_refund),+ }++ # when+ response = staff_api_client.post_graphql(+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,+ variables,+ )++ get_graphql_content(response)++ 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,+ )diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 0cf88a495d..ab2f191604 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -11717,6 +11717,44 @@ type OrderGrantedRefund @doc(category: "Orders") {"""App that performed the action."""app: App++ """+ If true, the refunded amount includes the shipping price.If false, the refunded amount does not include the shipping price.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ shippingCostsIncluded: Boolean!++ """+ Lines assigned to the granted refund.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ lines: [OrderGrantedRefundLine!]+}++"""+Represents granted refund line.++Added in Saleor 3.15.++Note: this API is currently in Feature Preview and can be subject to changes at later point.+"""+type OrderGrantedRefundLine {+ id: ID!++ """Number of items to refund."""+ quantity: Int!++ """Line of the order associated with this granted refund."""+ orderLine: OrderLine!++ """Reason for refunding the line."""+ reason: String}"""Represents transaction's event."""@@ -14815,6 +14853,23 @@ type Mutation {id: ID!): TransactionRequestAction @doc(category: "Payments")+ """+ Request a refund for payment transaction based on granted refund.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.++ Requires one of the following permissions: HANDLE_PAYMENTS.+ """+ transactionRequestRefundForGrantedRefund(+ """The ID of the granted refund."""+ grantedRefundId: ID!++ """The ID of the transaction."""+ id: ID!+ ): TransactionRequestRefundForGrantedRefund @doc(category: "Payments")+"""Report the event for the transaction.@@ -21733,6 +21788,41 @@ enum TransactionRequestActionErrorCode @doc(category: "Payments") {MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK}+"""+Request a refund for payment transaction based on granted refund.++Added in Saleor 3.15.++Note: this API is currently in Feature Preview and can be subject to changes at later point.++Requires one of the following permissions: HANDLE_PAYMENTS.+"""+type TransactionRequestRefundForGrantedRefund @doc(category: "Payments") {+ transaction: TransactionItem+ errors: [TransactionRequestRefundForGrantedRefundError!]!+}++type TransactionRequestRefundForGrantedRefundError @doc(category: "Payments") {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: TransactionRequestRefundForGrantedRefundErrorCode!+}++"""An enumeration."""+enum TransactionRequestRefundForGrantedRefundErrorCode @doc(category: "Payments") {+ INVALID+ GRAPHQL_ERROR+ NOT_FOUND+ MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK+}+"""Report the event for the transaction.@@ -22726,20 +22816,86 @@ type OrderGrantRefundCreateError @doc(category: "Orders") {"""The error code."""code: OrderGrantRefundCreateErrorCode!++ """+ List of lines which cause the error.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ lines: [OrderGrantRefundCreateLineError!]}"""An enumeration."""enum OrderGrantRefundCreateErrorCode @doc(category: "Orders") {GRAPHQL_ERRORNOT_FOUND+ SHIPPING_COSTS_ALREADY_GRANTED+ REQUIRED+ INVALID+}++type OrderGrantRefundCreateLineError {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: OrderGrantRefundCreateLineErrorCode!++ """The ID of the line related to the error."""+ lineId: ID!+}++"""An enumeration."""+enum OrderGrantRefundCreateLineErrorCode {+ GRAPHQL_ERROR+ NOT_FOUND+ QUANTITY_GREATER_THAN_AVAILABLE}input OrderGrantRefundCreateInput @doc(category: "Orders") {- """Amount of the granted refund."""- amount: Decimal!+ """+ Amount of the granted refund. If not provided, the amount will be calculated automatically based on provided `lines` and `grantRefundForShipping`.+ """+ amount: Decimal"""Reason of the granted refund."""reason: String++ """+ Lines to assign to granted refund.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ lines: [OrderGrantRefundCreateLineInput!]++ """+ Determine if granted refund should include shipping costs.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ grantRefundForShipping: Boolean+}++input OrderGrantRefundCreateLineInput @doc(category: "Orders") {+ """The ID of the order line."""+ id: ID!++ """The quantity of line items to be marked to refund."""+ quantity: Int!++ """Reason of the granted refund for the line."""+ reason: String}"""@@ -22758,7 +22914,6 @@ type OrderGrantRefundUpdate @doc(category: "Orders") {"""Created granted refund."""grantedRefund: OrderGrantedRefunderrors: [OrderGrantRefundUpdateError!]!- orderGrantedRefund: OrderGrantedRefund}type OrderGrantRefundUpdateError @doc(category: "Orders") {@@ -22772,6 +22927,24 @@ type OrderGrantRefundUpdateError @doc(category: "Orders") {"""The error code."""code: OrderGrantRefundUpdateErrorCode!++ """+ List of lines to add which cause the error.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ addLines: [OrderGrantRefundUpdateLineError!]++ """+ List of lines to remove which cause the error.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ removeLines: [OrderGrantRefundUpdateLineError!]}"""An enumeration."""@@ -22779,14 +22952,79 @@ enum OrderGrantRefundUpdateErrorCode @doc(category: "Orders") {GRAPHQL_ERRORNOT_FOUNDREQUIRED+ INVALID+ SHIPPING_COSTS_ALREADY_GRANTED+}++type OrderGrantRefundUpdateLineError {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: OrderGrantRefundUpdateLineErrorCode!++ """The ID of the line related to the error."""+ lineId: ID!+}++"""An enumeration."""+enum OrderGrantRefundUpdateLineErrorCode {+ GRAPHQL_ERROR+ NOT_FOUND+ QUANTITY_GREATER_THAN_AVAILABLE}input OrderGrantRefundUpdateInput @doc(category: "Orders") {- """Amount of the granted refund."""+ """+ Amount of the granted refund. if not provided and `addLines` or `removeLines` or `grantRefundForShipping` is provided, amount will be calculated automatically.+ """amount: Decimal"""Reason of the granted refund."""reason: String++ """+ Lines to assign to granted refund.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ addLines: [OrderGrantRefundUpdateLineAddInput!]++ """+ Lines to remove from granted refund.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ removeLines: [ID!]++ """+ Determine if granted refund should include shipping costs.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ grantRefundForShipping: Boolean+}++input OrderGrantRefundUpdateLineAddInput @doc(category: "Orders") {+ """The ID of the order line."""+ id: ID!++ """The quantity of line items to be marked to refund."""+ quantity: Int!++ """Reason of the granted refund for the line."""+ reason: String}"""@@ -30518,6 +30756,15 @@ type TransactionRefundRequested implements Event @doc(category: "Payments") {"""Requested action data."""action: TransactionAction!++ """+ Granted refund related to refund request.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ grantedRefund: OrderGrantedRefund}"""diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 6f2a1e190a..545c7811b6 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -57,7 +57,7 @@ from ..core.scalars import JSON, PositiveDecimalfrom ..core.types import NonNullList, SubscriptionObjectTypefrom ..core.types.order_or_checkout import OrderOrCheckoutfrom ..order.dataloaders import OrderByIdLoader-from ..order.types import Order+from ..order.types import Order, OrderGrantedRefundfrom ..payment.enums import TransactionActionEnumfrom ..payment.types import TransactionItemfrom ..plugins.dataloaders import plugin_manager_promise_callback@@ -1559,6 +1559,13 @@ class TransactionChargeRequested(TransactionActionBase, SubscriptionObjectType):class TransactionRefundRequested(TransactionActionBase, SubscriptionObjectType):+ granted_refund = graphene.Field(+ OrderGrantedRefund,+ description="Granted refund related to refund request."+ + ADDED_IN_315+ + PREVIEW_FEATURE,+ )+class Meta:interfaces = (Event,)root_type = None@@ -1570,6 +1577,12 @@ class TransactionRefundRequested(TransactionActionBase, SubscriptionObjectType):)doc_category = DOC_CATEGORY_PAYMENTS+ @staticmethod+ def resolve_granted_refund(root, _info: ResolveInfo):+ _, transaction_action_data = root+ transaction_action_data: TransactionActionData+ return transaction_action_data.granted_refund+class TransactionCancelationRequested(TransactionActionBase, SubscriptionObjectType):class Meta:diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.pyindex 2b841dfe6d..da5ccfb392 100644--- a/saleor/order/error_codes.py+++ b/saleor/order/error_codes.py@@ -39,12 +39,29 @@ class OrderErrorCode(Enum):class OrderGrantRefundCreateErrorCode(Enum):GRAPHQL_ERROR = "graphql_error"NOT_FOUND = "not_found"+ SHIPPING_COSTS_ALREADY_GRANTED = "shipping_costs_already_granted"+ REQUIRED = "required"+ INVALID = "invalid"class OrderGrantRefundUpdateErrorCode(Enum):GRAPHQL_ERROR = "graphql_error"NOT_FOUND = "not_found"REQUIRED = "required"+ INVALID = "invalid"+ SHIPPING_COSTS_ALREADY_GRANTED = "shipping_costs_already_granted"+++class OrderGrantRefundCreateLineErrorCode(Enum):+ GRAPHQL_ERROR = "graphql_error"+ NOT_FOUND = "not_found"+ QUANTITY_GREATER_THAN_AVAILABLE = "quantity_greater_than_available"+++class OrderGrantRefundUpdateLineErrorCode(Enum):+ GRAPHQL_ERROR = "graphql_error"+ NOT_FOUND = "not_found"+ QUANTITY_GREATER_THAN_AVAILABLE = "quantity_greater_than_available"class OrderBulkCreateErrorCode(Enum):diff --git a/saleor/order/migrations/0171_auto_20230518_0854.py b/saleor/order/migrations/0171_auto_20230518_0854.pynew file mode 100644index 0000000000..ed1671891a--- /dev/null+++ b/saleor/order/migrations/0171_auto_20230518_0854.py@@ -0,0 +1,58 @@+# Generated by Django 3.2.19 on 2023-05-18 08:54++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0170_auto_20230529_1314"),+ ]++ operations = [+ migrations.AddField(+ model_name="ordergrantedrefund",+ name="shipping_costs_included",+ field=models.BooleanField(default=False),+ ),+ migrations.RunSQL(+ "ALTER TABLE order_ordergrantedrefund ALTER COLUMN shipping_costs_included "+ "SET DEFAULT false;",+ migrations.RunSQL.noop,+ ),+ migrations.CreateModel(+ name="OrderGrantedRefundLine",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("quantity", models.PositiveIntegerField()),+ (+ "granted_refund",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="lines",+ to="order.ordergrantedrefund",+ ),+ ),+ (+ "order_line",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="granted_refund_lines",+ to="order.orderline",+ ),+ ),+ (+ "reason",+ models.TextField(blank=True, null=True, default=""),+ ),+ ],+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex a3c898ee9b..7ce8f130c3 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -847,6 +847,22 @@ class OrderGrantedRefund(models.Model):order = models.ForeignKey(Order, related_name="granted_refunds", on_delete=models.CASCADE)+ shipping_costs_included = models.BooleanField(default=False)class Meta:ordering = ("created_at", "id")+++class OrderGrantedRefundLine(models.Model):+ """Model used to store granted refund line for the order."""++ order_line = models.ForeignKey(+ OrderLine, related_name="granted_refund_lines", on_delete=models.CASCADE+ )+ quantity = models.PositiveIntegerField()++ granted_refund = models.ForeignKey(+ OrderGrantedRefund, related_name="lines", on_delete=models.CASCADE+ )++ reason = models.TextField(blank=True, null=True, default="")diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.pyindex 5d10fc825a..bcd2a04d5e 100644--- a/saleor/payment/error_codes.py+++ b/saleor/payment/error_codes.py@@ -48,6 +48,15 @@ class TransactionRequestActionErrorCode(Enum):)+class TransactionRequestRefundForGrantedRefundErrorCode(Enum):+ INVALID = "invalid"+ GRAPHQL_ERROR = "graphql_error"+ NOT_FOUND = "not_found"+ MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK = (+ "missing_transaction_action_request_webhook"+ )++class TransactionEventReportErrorCode(Enum):INVALID = "invalid"GRAPHQL_ERROR = "graphql_error"diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.pyindex e1a827d45d..2e92ff2efd 100644--- a/saleor/payment/gateway.py+++ b/saleor/payment/gateway.py@@ -11,6 +11,7 @@ from ..order.events import (event_transaction_charge_requested,event_transaction_refund_requested,)+from ..order.models import OrderGrantedRefundfrom ..payment.interface import (CustomerSource,PaymentGateway,@@ -124,6 +125,7 @@ def request_refund_action(channel_slug: str,user: Optional[User],app: Optional[App],+ granted_refund: Optional[OrderGrantedRefund] = None,):if refund_value is None:refund_value = transaction.charged_value@@ -133,6 +135,7 @@ def request_refund_action(action_type=TransactionAction.REFUND,action_value=refund_value,request_event=request_event,+ granted_refund=granted_refund,)_request_payment_action(transaction_action_data=transaction_action_data,@@ -192,6 +195,7 @@ def _create_transaction_data(action_type: "str",action_value: Optional[Decimal],request_event: TransactionEvent,+ granted_refund: Optional[OrderGrantedRefund] = None,):app_owner = Noneif transaction.app_id:@@ -205,6 +209,7 @@ def _create_transaction_data(action_value=action_value,event=request_event,transaction_app_owner=app_owner,+ granted_refund=granted_refund,)diff --git a/saleor/payment/interface.py b/saleor/payment/interface.pyindex 4e17e8335b..37ea4635df 100644--- a/saleor/payment/interface.py+++ b/saleor/payment/interface.py@@ -12,7 +12,7 @@ from ..payment.models import TransactionEvent, TransactionItemif TYPE_CHECKING:from ..app.models import Appfrom ..checkout.models import Checkout- from ..order.models import Order+ from ..order.models import Order, OrderGrantedRefundJSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]JSONType = Union[Dict[str, JSONValue], List[JSONValue]]@@ -25,6 +25,7 @@ class TransactionActionData:event: "TransactionEvent"transaction_app_owner: Optional["App"]action_value: Optional[Decimal] = None+ granted_refund: Optional["OrderGrantedRefund"] = None@dataclassdiff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.pyindex 961aa5ecea..f271a36995 100644--- a/saleor/payment/tests/test_gateway.py+++ b/saleor/payment/tests/test_gateway.py@@ -720,6 +720,71 @@ def test_request_refund_action_on_order(assert event.user == staff_user+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")+def test_request_refund_action_with_granted_refund(+ mocked_transaction_request, mocked_is_active, order_with_lines, staff_user+):+ # given+ order_line = order_with_lines.lines.first()+ granted_refund = order_with_lines.granted_refunds.create(+ amount_value=order_line.unit_price_gross_amount+ )+ granted_refund.lines.create(+ quantity=1,+ order_line=order_line,+ )++ transaction = TransactionItem.objects.create(+ status="Captured",+ name="Credit card",+ psp_reference="PSP ref",+ available_actions=["refund"],+ currency="USD",+ order_id=order_with_lines.pk,+ charged_value=Decimal("10"),+ )+ action_value = order_line.unit_price_gross_amount+ requested_event = transaction.events.create(+ amount_value=action_value,+ currency=transaction.currency,+ type=TransactionEventType.REFUND_REQUEST,+ )+ mocked_is_active.side_effect = [False, True]++ # when+ request_refund_action(+ transaction=transaction,+ manager=get_plugins_manager(),+ refund_value=action_value,+ channel_slug=order_with_lines.channel.slug,+ user=staff_user,+ app=None,+ request_event=requested_event,+ granted_refund=granted_refund,+ )++ # then+ assert mocked_is_active.called+ mocked_transaction_request.assert_called_once_with(+ TransactionActionData(+ transaction=transaction,+ action_type=TransactionAction.REFUND,+ action_value=action_value,+ event=requested_event,+ transaction_app_owner=None,+ granted_refund=granted_refund,+ ),+ order_with_lines.channel.slug,+ )++ event = order_with_lines.events.first()+ assert event.type == OrderEvents.TRANSACTION_REFUND_REQUESTED+ assert Decimal(event.parameters["amount"]) == action_value+ assert event.parameters["reference"] == transaction.psp_reference+ assert event.user == staff_user++@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")def test_request_refund_action_by_app(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.pyindex 4b647e5e54..a91ce91368 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py@@ -31,6 +31,41 @@ subscription {}""")+TRANSACTION_REFUND_REQUESTED_WITH_GRANTED_REFUND_SUBSCRIPTION = (+ fragments.TRANSACTION_ITEM_DETAILS+ + """+subscription {+ event {+ ... on TransactionRefundRequested {+ transaction {+ ...TransactionFragment+ }+ grantedRefund{+ id+ amount{+ amount+ }+ lines{+ id+ quantity+ orderLine{+ unitPrice{+ gross{+ amount+ }+ }+ }+ }+ }+ action {+ actionType+ amount+ }+ }+ }+}+"""+)@freeze_time("2020-03-18 12:00:00")@@ -104,3 +139,105 @@ def test_transaction_refund_request(order, webhook_app, permission_manage_paymen"amount": quantize_price(action_value, "USD"),},}+++@freeze_time("2020-03-18 12:00:00")+def test_transaction_refund_request_with_granted_refund(+ order_with_lines, webhook_app, permission_manage_payments+):+ # given+ charged_value = Decimal("10")+ webhook_app.permissions.add(permission_manage_payments)+ transaction = TransactionItem.objects.create(+ status="Captured",+ name="Credit card",+ psp_reference="PSP ref",+ available_actions=["refund"],+ currency="USD",+ order_id=order_with_lines.pk,+ charged_value=charged_value,+ )++ order_line = order_with_lines.lines.first()+ expected_amount = order_line.unit_price_gross_amount++ granted_refund = order_with_lines.granted_refunds.create(+ amount_value=expected_amount+ )+ granted_refund_line = granted_refund.lines.create(+ quantity=1,+ order_line=order_line,+ )++ action_value = expected_amount+ request_event = transaction.events.create(+ amount_value=action_value,+ currency=transaction.currency,+ type=TransactionEventType.REFUND_REQUEST,+ )++ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ target_url="http://www.example.com/any",+ subscription_query=(+ TRANSACTION_REFUND_REQUESTED_WITH_GRANTED_REFUND_SUBSCRIPTION+ ),+ )+ event_type = WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED+ webhook.events.create(event_type=event_type)++ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)+ transaction_data = TransactionActionData(+ transaction=transaction,+ action_type=TransactionAction.REFUND,+ action_value=action_value,+ event=request_event,+ transaction_app_owner=None,+ granted_refund=granted_refund,+ )+ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, transaction_data, [webhook]+ )++ # then+ assert json.loads(deliveries[0].payload.payload) == {+ "transaction": {+ "id": transaction_id,+ "createdAt": "2020-03-18T12:00:00+00:00",+ "actions": ["REFUND"],+ "authorizedAmount": {"currency": "USD", "amount": 0.0},+ "refundedAmount": {"currency": "USD", "amount": 0.0},+ "voidedAmount": {"currency": "USD", "amount": 0.0},+ "chargedAmount": {+ "currency": "USD",+ "amount": quantize_price(charged_value, "USD"),+ },+ "events": [+ {"id": graphene.Node.to_global_id("TransactionEvent", request_event.id)}+ ],+ "status": "Captured",+ "type": "Credit card",+ "reference": "PSP ref",+ "pspReference": "PSP ref",+ "order": {"id": graphene.Node.to_global_id("Order", order_with_lines.id)},+ },+ "grantedRefund": {+ "amount": {"amount": 12.3},+ "id": graphene.Node.to_global_id("OrderGrantedRefund", granted_refund.id),+ "lines": [+ {+ "id": graphene.Node.to_global_id(+ "OrderGrantedRefundLine", granted_refund_line.id+ ),+ "orderLine": {"unitPrice": {"gross": {"amount": 12.3}}},+ "quantity": 1,+ }+ ],+ },+ "action": {+ "actionType": "REFUND",+ "amount": 12.3,+ },+ }diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 6f8ea53973..10837b4890 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -652,10 +652,15 @@ class WebhookEventSyncType:PAYMENT_VOID,]+ # Events that are used only in the mutation logic can be excluded from the+ # circular query check.ALLOWED_IN_CIRCULAR_QUERY = [PAYMENT_GATEWAY_INITIALIZE_SESSION,TRANSACTION_INITIALIZE_SESSION,TRANSACTION_PROCESS_SESSION,+ TRANSACTION_CHARGE_REQUESTED,+ TRANSACTION_REFUND_REQUESTED,+ TRANSACTION_CANCELATION_REQUESTED,]PERMISSIONS = {