Skip to content

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

Fix refund data

Mateusz Grzybdb823caba8d0
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index bb50a63754..37e537ce6f 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -1445,6 +1445,7 @@ def _process_refund(
manager: "PluginsManager",
):
lines_to_refund: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]] = dict()
+ manual_amount_to_refund = amount
if amount is None:
amount = _calculate_refund_amount(
order_lines_to_refund, fulfillment_lines_to_refund, lines_to_refund
@@ -1465,6 +1466,7 @@ def _process_refund(
order,
order_lines_to_refund,
fulfillment_lines_to_refund,
+ manual_amount_to_refund,
refund_shipping_costs,
),
)
diff --git a/saleor/payment/gateways/np_atobarai/__init__.py b/saleor/payment/gateways/np_atobarai/__init__.py
index a78742c92a..2490692705 100644
--- a/saleor/payment/gateways/np_atobarai/__init__.py
+++ b/saleor/payment/gateways/np_atobarai/__init__.py
@@ -122,10 +122,10 @@ def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayRespon
f"Order does not exist for payment with id {payment_id}."
)
- refund_data = payment_information.refund_data
-
result = api.change_transaction(
- config, payment, payment_information, refund_data
+ config,
+ payment,
+ payment_information,
)
if result.status == PaymentStatus.FOR_REREGISTRATION:
@@ -138,7 +138,6 @@ def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayRespon
payment_information,
shipping_company_code,
tracking_number,
- refund_data,
)
else:
diff --git a/saleor/payment/gateways/np_atobarai/api.py b/saleor/payment/gateways/np_atobarai/api.py
index ad0313a606..89b0689fb3 100644
--- a/saleor/payment/gateways/np_atobarai/api.py
+++ b/saleor/payment/gateways/np_atobarai/api.py
@@ -2,13 +2,12 @@ import logging
from typing import List, Optional, Tuple
from ....order.models import Fulfillment
-from ...interface import PaymentData, RefundData
+from ...interface import PaymentData
from ...models import Payment
from .api_helpers import (
cancel,
format_price,
- get_goods_with_discount,
- get_refunded_goods,
+ get_goods_with_refunds,
handle_unrecoverable_state,
np_request,
register,
@@ -95,17 +94,13 @@ def change_transaction(
config: ApiConfig,
payment: Payment,
payment_information: PaymentData,
- refund_data: Optional[RefundData],
) -> PaymentResult:
"""Change transaction.
If the fulfillment was reported prior to changing given transaction,
then no change is applied and payment status is set to FOR_REREGISTRATION.
"""
- if refund_data:
- goods = get_refunded_goods(config, refund_data, payment_information)
- else:
- goods = get_goods_with_discount(config, payment_information)
+ goods = get_goods_with_refunds(config, payment_information)
data = {
"transactions": [
@@ -157,7 +152,6 @@ def reregister_transaction_for_partial_return(
payment_information: PaymentData,
shipping_company_code: Optional[str],
tracking_number: Optional[str],
- refund_data: Optional[RefundData],
) -> PaymentResult:
"""Change transaction.
@@ -181,10 +175,7 @@ def reregister_transaction_for_partial_return(
)
return errors_payment_result(error_messages)
- if refund_data:
- goods = get_refunded_goods(config, refund_data, payment_information)
- else:
- goods = get_goods_with_discount(config, payment_information)
+ goods = get_goods_with_refunds(config, payment_information)
billed_amount = format_price(
payment.captured_amount - payment_information.amount,
diff --git a/saleor/payment/gateways/np_atobarai/api_helpers.py b/saleor/payment/gateways/np_atobarai/api_helpers.py
index 49d781b5c2..7f5b20533f 100644
--- a/saleor/payment/gateways/np_atobarai/api_helpers.py
+++ b/saleor/payment/gateways/np_atobarai/api_helpers.py
@@ -165,29 +165,49 @@ def _get_voucher_and_shipping_goods(
return goods_lines
-def get_refunded_goods(
+def get_goods_with_refunds(
config: "ApiConfig",
- refund_data: RefundData,
payment_information: PaymentData,
) -> List[dict]:
- """Convert payment lines and refund lines into NP Atobarai goods lines.
+ goods_lines = []
+ refund_data = payment_information.refund_data or RefundData(
+ lines={}, shipping=False, manual_amount=Decimal("0.00")
+ )
- Used for refunds with specific lines refunded.
- Returns remaining lines after refunds,
- not lines removed by refunds.
- """
- return [
- {
- "goods_name": _get_goods_name(line, config),
- "goods_price": format_price(line.amount, payment_information.currency),
- "quantity": quantity,
- }
- for line in payment_information.lines_data.lines
- if (quantity := refund_data.lines.get(line.variant_id, line.quantity))
- ] + _get_voucher_and_shipping_goods(
- config, payment_information, refund_data.shipping
+ for line in payment_information.lines_data.lines:
+ quantity = line.quantity
+ refunded_quantity = refund_data.lines.get(line.variant_id)
+ if refunded_quantity:
+ quantity -= refunded_quantity
+
+ goods_lines.append(
+ {
+ "goods_name": _get_goods_name(line, config),
+ "goods_price": format_price(line.amount, payment_information.currency),
+ "quantity": quantity,
+ }
+ )
+
+ discount_amount = refund_data.manual_amount
+ if discount_amount:
+ goods_lines.append(
+ {
+ "goods_name": "Discount",
+ "goods_price": format_price(
+ -discount_amount, payment_information.currency
+ ),
+ "quantity": 1,
+ }
+ )
+
+ goods_lines.extend(
+ _get_voucher_and_shipping_goods(
+ config, payment_information, refund_data.shipping
+ )
)
+ return goods_lines
+
def get_goods(config: "ApiConfig", payment_information: PaymentData) -> List[dict]:
return [
@@ -200,27 +220,6 @@ def get_goods(config: "ApiConfig", payment_information: PaymentData) -> List[dic
] + _get_voucher_and_shipping_goods(config, payment_information)
-def get_goods_with_discount(
- config: "ApiConfig",
- payment_information: PaymentData,
-) -> List[dict]:
- """Convert payment lines into NP Atobarai goods lines.
-
- Used for refunds without specific lines refunded.
- """
- product_lines = get_goods(config, payment_information)
- return product_lines + [
- {
- "goods_name": "Discount",
- "goods_price": format_price(
- -payment_information.amount,
- payment_information.currency,
- ),
- "quantity": 1,
- }
- ]
-
-
def cancel(config: "ApiConfig", transaction_id: str) -> NPResponse:
data = {"transactions": [{"np_transaction_id": transaction_id}]}
return np_request(config, "patch", "/transactions/cancel", json=data)
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_api.py b/saleor/payment/gateways/np_atobarai/tests/test_api.py
index 089e6a4374..a77894edc2 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_api.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api.py
@@ -9,7 +9,7 @@ from graphene import Node
from .... import PaymentError
from ....interface import RefundData
from .. import PaymentStatus, api, const
-from ..api_helpers import format_price, get_goods_with_discount, get_refunded_goods
+from ..api_helpers import format_price, get_goods_with_refunds
from ..api_types import NPResponse, PaymentResult
from ..errors import (
NO_PSP_REFERENCE,
@@ -494,7 +494,6 @@ def test_change_transaction_success(
mocked_request, config, payment_dummy, np_payment_data
):
# given
- refund_data = None
response = Mock(
spec=requests.Response,
status_code=200,
@@ -512,9 +511,7 @@ def test_change_transaction_success(
mocked_request.return_value = response
# when
- payment_response = api.change_transaction(
- config, payment_dummy, np_payment_data, refund_data
- )
+ payment_response = api.change_transaction(config, payment_dummy, np_payment_data)
# then
assert payment_response.status == PaymentStatus.SUCCESS
@@ -526,7 +523,6 @@ def test_change_transaction_pending(
mocked_request, mocked_cancel, config, payment_dummy, np_payment_data
):
# given
- refund_data = None
transaction_id = "123"
response = Mock(
spec=requests.Response,
@@ -549,9 +545,7 @@ def test_change_transaction_pending(
mocked_request.return_value = response
# when
- payment_response = api.change_transaction(
- config, payment_dummy, np_payment_data, refund_data
- )
+ payment_response = api.change_transaction(config, payment_dummy, np_payment_data)
# then
mocked_cancel.assert_called_once_with(config, transaction_id)
@@ -563,7 +557,6 @@ def test_change_transaction_post_fulfillment(
mocked_request, config, payment_dummy, np_payment_data
):
# given
- refund_data = None
response = Mock(
spec=requests.Response,
status_code=200,
@@ -572,9 +565,7 @@ def test_change_transaction_post_fulfillment(
mocked_request.return_value = response
# when
- payment_response = api.change_transaction(
- config, payment_dummy, np_payment_data, refund_data
- )
+ payment_response = api.change_transaction(config, payment_dummy, np_payment_data)
# then
assert payment_response.status == PaymentStatus.FOR_REREGISTRATION
@@ -585,7 +576,6 @@ def test_change_transaction_failed(
mocked_request, config, payment_dummy, np_payment_data
):
# given
- refund_data = None
response = Mock(
spec=requests.Response,
status_code=200,
@@ -594,44 +584,30 @@ def test_change_transaction_failed(
mocked_request.return_value = response
# when
- payment_response = api.change_transaction(
- config, payment_dummy, np_payment_data, refund_data
- )
+ payment_response = api.change_transaction(config, payment_dummy, np_payment_data)
# then
assert payment_response.status == PaymentStatus.FAILED
assert payment_response.errors
[email protected]("lines", [{}, {i: i for i in range(1, 4)}])
[email protected]("shipping", [False, True])
[email protected]("manual_amount", [Decimal("0.00"), Decimal("12.34")])
@patch("saleor.payment.gateways.np_atobarai.api.np_request")
def test_change_transaction_refunded_goods(
- mocked_request, config, payment_dummy, np_payment_data
+ mocked_request,
+ config,
+ payment_dummy,
+ np_payment_data,
+ lines,
+ shipping,
+ manual_amount,
):
# given
- refund_data = RefundData(lines={i: i for i in range(1, 4)}, shipping=False)
- mocked_request.return_value = NPResponse(
- result={
- "authori_result": "00",
- "np_transaction_id": "123123123",
- },
- error_codes=[],
+ np_payment_data.refund_data = RefundData(
+ lines=lines, shipping=shipping, manual_amount=manual_amount
)
-
- # when
- api.change_transaction(config, payment_dummy, np_payment_data, refund_data)
-
- # then
- data = mocked_request.call_args[1]["json"]
- goods = data["transactions"][0]["goods"]
- assert goods == get_refunded_goods(config, refund_data, np_payment_data)
-
-
-@patch("saleor.payment.gateways.np_atobarai.api.np_request")
-def test_change_transaction_goods_with_discount(
- mocked_request, config, payment_dummy, np_payment_data
-):
- # given
- refund_data = None
mocked_request.return_value = NPResponse(
result={
"authori_result": "00",
@@ -641,12 +617,12 @@ def test_change_transaction_goods_with_discount(
)
# when
- api.change_transaction(config, payment_dummy, np_payment_data, refund_data)
+ api.change_transaction(config, payment_dummy, np_payment_data)
# then
data = mocked_request.call_args[1]["json"]
goods = data["transactions"][0]["goods"]
- assert goods == get_goods_with_discount(config, np_payment_data)
+ assert goods == get_goods_with_refunds(config, np_payment_data)
@patch("saleor.payment.gateways.np_atobarai.api.report")
@@ -661,7 +637,6 @@ def test_reregister_transaction_success(
np_payment_data,
):
# given
- refund_data = None
tracking_number = "123"
shipping_company_code = "50000"
payment_dummy.psp_reference = "123"
@@ -682,7 +657,6 @@ def test_reregister_transaction_success(
np_payment_data,
shipping_company_code,
tracking_number,
- refund_data,
)
# then
@@ -690,7 +664,7 @@ def test_reregister_transaction_success(
billed_amount = format_price(
payment_dummy.captured_amount - np_payment_data.amount, np_payment_data.currency
)
- goods = get_goods_with_discount(config, np_payment_data)
+ goods = get_goods_with_refunds(config, np_payment_data)
mocked_register.assert_called_once_with(
config, np_payment_data, billed_amount, goods
)
@@ -704,7 +678,7 @@ def test_reregister_transaction_success(
def test_reregister_transaction_no_psp_reference(payment_dummy, np_payment_data):
# when
payment_response = api.reregister_transaction_for_partial_return(
- Mock(), payment_dummy, np_payment_data, Mock(), Mock(), Mock()
+ Mock(), payment_dummy, np_payment_data, Mock(), Mock()
)
# then
@@ -723,7 +697,7 @@ def test_reregister_transaction_cancel_error(
# when
payment_response = api.reregister_transaction_for_partial_return(
- config, payment_dummy, np_payment_data, Mock(), Mock(), Mock()
+ config, payment_dummy, np_payment_data, Mock(), Mock()
)
# then
@@ -743,7 +717,6 @@ def test_reregister_transaction_report_error(
np_payment_data,
):
# given
- refund_data = None
tracking_number = "123"
shipping_company_code = "50000"
payment_dummy.psp_reference = "123"
@@ -765,7 +738,6 @@ def test_reregister_transaction_report_error(
np_payment_data,
shipping_company_code,
tracking_number,
- refund_data,
)
# then
@@ -795,7 +767,6 @@ def test_reregister_transaction_general_error(
np_payment_data,
Mock(),
Mock(),
- Mock(),
)
# then
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py b/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py
index fb1e22ab93..da473ddf7d 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py
@@ -1,4 +1,5 @@
from dataclasses import fields
+from decimal import Decimal
from unittest.mock import DEFAULT, Mock, patch, sentinel
import pytest
@@ -7,7 +8,7 @@ from posuto import Posuto
from ....interface import AddressData, RefundData
from ....utils import price_to_minor_unit
from .. import api_helpers, errors
-from ..api_helpers import get_goods, get_refunded_goods
+from ..api_helpers import get_goods, get_goods_with_refunds
def test_register_no_billing_address(config, np_payment_data):
@@ -192,6 +193,22 @@ def test_get_goods(
]
+ "manual_refund, discount_goods",
+ [
+ (Decimal("0.00"), []),
+ (
+ Decimal("12.34"),
+ [
+ {
+ "goods_name": "Discount",
+ "goods_price": -1234,
+ "quantity": 1,
+ }
+ ],
+ ),
+ ],
+)
@pytest.mark.parametrize(
"refund_shipping, shipping_goods",
[
@@ -209,20 +226,29 @@ def test_get_goods(
],
)
@pytest.mark.parametrize("sku_as_name", [True, False])
-def test_get_refunded_goods(
+ "refund_lines, quantities",
+ [({0: 1, 1: 2, 2: 3}, {0: 4, 1: 3, 2: 2}), ({}, {i: 5 for i in range(3)})],
+)
+def test_get_goods_with_refunds(
config,
np_payment_data,
sku_as_name,
refund_shipping,
shipping_goods,
+ manual_refund,
+ discount_goods,
+ refund_lines,
+ quantities,
):
# given
config.sku_as_name = sku_as_name
- refund_data_lines = {1: 23, 2: 0, 3: 13}
- refund_data = RefundData(lines=refund_data_lines, shipping=refund_shipping)
+ np_payment_data.refund_data = RefundData(
+ lines=refund_lines, shipping=refund_shipping, manual_amount=manual_refund
+ )
# when
- goods = get_refunded_goods(config, refund_data, np_payment_data)
+ goods = get_goods_with_refunds(config, np_payment_data)
# then
assert (
@@ -233,11 +259,11 @@ def test_get_refunded_goods(
"goods_price": int(
price_to_minor_unit(line.amount, np_payment_data.currency)
),
- "quantity": quantity,
+ "quantity": quantities[line.variant_id],
}
for line in np_payment_data.lines_data.lines
- if (quantity := refund_data_lines.get(line.variant_id, line.quantity))
]
+ + discount_goods
+ [
{
"goods_name": "Voucher",
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 987eebe0be..dfdfe2e7dd 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -86,6 +86,7 @@ class PaymentLinesData:
@dataclass
class RefundData:
shipping: bool
+ manual_amount: Decimal
lines: Dict[int, int]
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index daaff9bb95..3e6804f87d 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -1,6 +1,6 @@
from decimal import Decimal
from itertools import chain, zip_longest
-from typing import List
+from typing import List, Optional
from unittest.mock import Mock, patch
import pytest
@@ -13,8 +13,10 @@ from ...order.models import Order
from ...plugins.manager import get_plugins_manager
from ..interface import PaymentLineData, PaymentLinesData
from ..utils import (
+ _create_refund_lines,
+ _create_refund_manual_amount,
+ _create_refund_shipping,
create_payment_lines_information,
- create_refund_data,
get_channel_slug_from_payment,
try_void_or_refund_inactive_payment,
)
@@ -26,8 +28,12 @@ def create_refund_fulfillment_helper(payment_dummy):
order: Order,
order_lines: List[OrderLineInfo] = None,
fulfillment_lines: List[FulfillmentLineData] = None,
+ manual_refund_amount: Optional[Decimal] = None,
refund_shipping_costs: bool = False,
):
+ if manual_refund_amount:
+ payment_dummy.captured_amount = manual_refund_amount
+ payment_dummy.save(update_fields=["captured_amount"])
with patch("saleor.order.actions.gateway.refund"):
return create_refund_fulfillment(
user=None,
@@ -37,14 +43,14 @@ def create_refund_fulfillment_helper(payment_dummy):
order_lines_to_refund=order_lines or [],
fulfillment_lines_to_refund=fulfillment_lines or [],
manager=get_plugins_manager(),
+ amount=manual_refund_amount,
refund_shipping_costs=refund_shipping_costs,
)
return factory
[email protected]("refund_shipping_costs", [True, False])
-def test_create_refund_data_order_lines(order_with_lines, refund_shipping_costs):
+def test_create_refund_lines_order_lines(order_with_lines):
# given
order_lines = order_with_lines.lines.all()
order_refund_lines = [
@@ -54,23 +60,17 @@ def test_create_refund_data_order_lines(order_with_lines, refund_shipping_costs)
fulfillment_refund_lines = []
# when
- refund_data = create_refund_data(
+ lines = _create_refund_lines(
order_with_lines,
order_refund_lines,
fulfillment_refund_lines,
- refund_shipping_costs,
)
# then
- assert refund_data.lines == {
- line.variant_id: line.quantity - refund_line.quantity
- for line, refund_line in zip(order_lines, order_refund_lines)
- }
- assert refund_data.shipping == refund_shipping_costs
+ assert lines == {line.line.variant_id: line.quantity for line in order_refund_lines}
[email protected]("refund_shipping_costs", [True, False])
-def test_create_refund_data_fulfillment_lines(fulfilled_order, refund_shipping_costs):
+def test_create_refund_lines_fulfillment_lines(fulfilled_order):
# given
fulfillment_lines = fulfilled_order.fulfillments.first().lines.all()
order_refund_lines = []
@@ -86,58 +86,26 @@ def test_create_refund_data_fulfillment_lines(fulfilled_order, refund_shipping_c
]
# when
- refund_data = create_refund_data(
+ lines = _create_refund_lines(
fulfilled_order,
order_refund_lines,
fulfillment_refund_lines,
- refund_shipping_costs,
)
# then
- assert refund_data.lines == {
- line.order_line.variant_id: line.quantity - refund_line.quantity
- for line, refund_line in zip(fulfillment_lines, fulfillment_refund_lines)
+ assert lines == {
+ line.line.order_line.variant_id: line.quantity
+ for line in fulfillment_refund_lines
}
- assert refund_data.shipping == refund_shipping_costs
-
-
[email protected]("refund_shipping_costs", [True, False])
-def test_create_refund_data_shipping_only(order, refund_shipping_costs):
- # given
- order_refund_lines = []
- fulfillment_refund_lines = []
-
- # when
- refund_data = create_refund_data(
- order, order_refund_lines, fulfillment_refund_lines, refund_shipping_costs
- )
-
- # then
- assert not refund_data.lines
- assert refund_data.shipping == refund_shipping_costs
@patch("saleor.order.actions.gateway.refund")
- [
- "previous_refund_shipping_costs",
- "current_refund_shipping_costs",
- "refund_shipping_costs",
- ],
- [
- (True, True, True),
- (True, False, True),
- (False, True, True),
- (False, False, False),
- ],
-)
[email protected]("previous_refund_shipping_costs", [True, False])
def test_create_refund_data_previously_refunded_order_lines(
_mocked_refund,
order_with_lines,
create_refund_fulfillment_helper,
previous_refund_shipping_costs,
- current_refund_shipping_costs,
- refund_shipping_costs,
):
# given
order_lines = order_with_lines.lines.all()
@@ -156,11 +124,10 @@ def test_create_refund_data_previously_refunded_order_lines(
fulfillment_refund_lines = []
# when
- refund_data = create_refund_data(
+ lines = _create_refund_lines(
order_with_lines,
current_order_refund_lines,
fulfillment_refund_lines,
- current_refund_shipping_costs,
)
# then
@@ -172,34 +139,16 @@ def test_create_refund_data_previously_refunded_order_lines(
fillvalue=Mock(spec=OrderLineInfo, quantity=0),
)
]
- assert refund_data.lines == {
- line.variant_id: line.quantity - refund_line.quantity
- for line, refund_line in zip(order_lines, order_refund_lines)
- }
- assert refund_data.shipping == refund_shipping_costs
+ assert lines == {line.line.variant_id: line.quantity for line in order_refund_lines}
@patch("saleor.order.actions.gateway.refund")
- [
- "previous_refund_shipping_costs",
- "current_refund_shipping_costs",
- "refund_shipping_costs",
- ],
- [
- (True, True, True),
- (True, False, True),
- (False, True, True),
- (False, False, False),
- ],
-)
[email protected]("previous_refund_shipping_costs", [True, False])
def test_create_refund_data_previously_refunded_fulfillment_lines(
_mocked_refund,
fulfilled_order,
create_refund_fulfillment_helper,
previous_refund_shipping_costs,
- current_refund_shipping_costs,
- refund_shipping_costs,
):
# given
fulfillment_lines = list(
@@ -226,11 +175,10 @@ def test_create_refund_data_previously_refunded_fulfillment_lines(
]
# when
- refund_data = create_refund_data(
+ lines = _create_refund_lines(
fulfilled_order,
order_refund_lines,
current_fulfillment_refund_lines,
- current_refund_shipping_costs,
)
# then
@@ -242,13 +190,61 @@ def test_create_refund_data_previously_refunded_fulfillment_lines(
fillvalue=Mock(spec=FulfillmentLineData, quantity=0),
)
]
- assert refund_data.lines == {
- line.variant_id: line.quantity - refund_line.quantity
- for line, refund_line in zip(
- fulfilled_order.lines.all(), fulfillment_refund_lines
- )
+ assert lines == {
+ line.line.order_line.variant_id: line.quantity
+ for line in fulfillment_refund_lines
}
- assert refund_data.shipping == refund_shipping_costs
+
+
+ "current_manual_refund_amount, expected_manual_amount",
+ [
+ (None, Decimal("0.00")),
+ (Decimal("0.00"), Decimal("0.00")),
+ (Decimal("12.34"), Decimal("12.34")),
+ ],
+)
+def test_create_refund_manual_amount(
+ order,
+ current_manual_refund_amount,
+ expected_manual_amount,
+):
+ assert (
+ _create_refund_manual_amount(order, current_manual_refund_amount)
+ == expected_manual_amount
+ )
+
+
+ "previous_manual_refund_amount", [None, Decimal("0.00"), Decimal("12.34")]
+)
+ "current_manual_refund_amount", [None, Decimal("0.00"), Decimal("23.45")]
+)
+def test_create_refund_manual_amount_previously_refunded(
+ order,
+ create_refund_fulfillment_helper,
+ previous_manual_refund_amount,
+ current_manual_refund_amount,
+):
+ # given
+ create_refund_fulfillment_helper(
+ order, manual_refund_amount=previous_manual_refund_amount
+ )
+
+ # when
+ manual_amount = _create_refund_manual_amount(order, current_manual_refund_amount)
+
+ # then
+ expected_manual_amount = (previous_manual_refund_amount or Decimal("0.00")) + (
+ current_manual_refund_amount or Decimal("0.00")
+ )
+ assert manual_amount == expected_manual_amount
+
+
[email protected]("refund_shipping", [True, False])
+def test_create_refund_shipping(order, refund_shipping):
+ assert _create_refund_shipping(order, refund_shipping) is refund_shipping
@patch("saleor.order.actions.gateway.refund")
@@ -265,7 +261,7 @@ def test_create_refund_data_previously_refunded_fulfillment_lines(
(False, False, False),
],
)
-def test_create_refund_data_previously_refunded_shipping_only(
+def test_create_refund_shipping_previously_refunded(
_mocked_refund,
order,
create_refund_fulfillment_helper,
@@ -277,20 +273,15 @@ def test_create_refund_data_previously_refunded_shipping_only(
create_refund_fulfillment_helper(
order, refund_shipping_costs=previous_refund_shipping_costs
)
- order_refund_lines = []
- fulfillment_refund_lines = []
# when
- refund_data = create_refund_data(
+ refund = _create_refund_shipping(
order,
- order_refund_lines,
- fulfillment_refund_lines,
current_refund_shipping_costs,
)
# then
- assert not refund_data.lines
- assert refund_data.shipping == refund_shipping_costs
+ assert refund is refund_shipping_costs
def test_create_payment_lines_information_order(payment_dummy):
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 5babe1859c..7650dc40d9 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -8,7 +8,7 @@ from typing import Dict, List, Optional, cast
import graphene
from babel.numbers import get_currency_precision
from django.core.serializers.json import DjangoJSONEncoder
-from django.db.models import Q
+from django.db.models import Q, Sum
from ..account.models import User
from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -219,15 +219,15 @@ def create_payment_information(
)
-def _join_refund_lines(
+def _create_refund_lines(
order: Order,
order_lines_to_refund: List[OrderLineInfo],
fulfillment_lines_to_refund: List[FulfillmentLineData],
) -> Dict[int, int]:
- """Return mapping from variant id to quantity of refunded products.
+ """Return all refunded product variants for specified order.
- Takes into account previously refunded lines and lines from current
- refund mutation.
+ Takes into account previous refunds and current refund mutation parameters.
+ :return: Dictionary of variant ids and refunded quantities.
"""
previous_fulfillment_lines = FulfillmentLine.objects.prefetch_related(
"order_line"
@@ -241,21 +241,19 @@ def _join_refund_lines(
)
previous_refund_lines = (
- (p_variant_id, line.quantity)
- for line in previous_fulfillment_lines
- if (p_variant_id := line.order_line.variant_id)
+ (p_variant_id, line1.quantity)
+ for line1 in previous_fulfillment_lines
+ if (p_variant_id := line1.order_line.variant_id)
)
-
current_order_refund_lines = (
- (variant.id, line.quantity)
- for line in order_lines_to_refund
- if (variant := line.variant)
+ (variant.id, line1.quantity)
+ for line1 in order_lines_to_refund
+ if (variant := line1.variant)
)
-
current_fulfillment_refund_lines = (
- (f_variant_id, line.quantity)
- for line in fulfillment_lines_to_refund
- if (f_variant_id := line.line.order_line.variant_id)
+ (f_variant_id, line1.quantity)
+ for line1 in fulfillment_lines_to_refund
+ if (f_variant_id := line1.line.order_line.variant_id)
)
refund_lines = chain(
@@ -263,39 +261,64 @@ def _join_refund_lines(
current_order_refund_lines,
current_fulfillment_refund_lines,
)
-
summed_refund_lines: Dict[int, int] = defaultdict(int)
for variant_id, quantity in refund_lines:
summed_refund_lines[variant_id] += quantity
- return summed_refund_lines
+ return dict(summed_refund_lines)
-def create_refund_data(
+def _create_refund_manual_amount(
order: Order,
- order_lines_to_refund: List[OrderLineInfo],
- fulfillment_lines_to_refund: List[FulfillmentLineData],
- refund_shipping_costs: bool,
-) -> RefundData:
- """Create RefundData given previous refunds and current refund mutation."""
- order_lines = {line.variant_id: line.quantity for line in order.lines.all()}
+ manual_amount_to_refund: Optional[Decimal],
+) -> Decimal:
+ """Return sum of all manual refunds for specified order.
- joined_refund_lines = _join_refund_lines(
- order, order_lines_to_refund, fulfillment_lines_to_refund
- )
+ Takes into account previous refunds and current refund mutation parameters.
+ """
+ previous_manual_amount_to_refund = order.fulfillments.filter(
+ lines__order_line__variant_id__isnull=True, shipping_refund_amount__isnull=True
+ ).aggregate(discount=Sum("total_refund_amount"))["discount"]
- lines = {
- variant_id: order_lines[variant_id] - joined_refund_lines[variant_id]
- for variant_id in joined_refund_lines
- }
+ if previous_manual_amount_to_refund is None:
+ previous_manual_amount_to_refund = Decimal("0.00")
+ if manual_amount_to_refund is None:
+ manual_amount_to_refund = Decimal("0.00")
+ return previous_manual_amount_to_refund + manual_amount_to_refund
+
+
+def _create_refund_shipping(
+ order: Order,
+ refund_shipping_costs: bool,
+) -> bool:
+ """Determine whether shipping is refunded for specified order.
+
+ Takes into account previous refunds and current refund mutation parameters.
+ """
shipping_previously_refunded = order.fulfillments.exclude(
shipping_refund_amount__isnull=True
).exists()
+ return shipping_previously_refunded or refund_shipping_costs
+
+
+def create_refund_data(
+ order: Order,
+ order_lines_to_refund: List[OrderLineInfo],
+ fulfillment_lines_to_refund: List[FulfillmentLineData],
+ manual_amount_to_refund: Optional[Decimal],
+ refund_shipping_costs: bool,
+) -> RefundData:
+ """Create RefundData given previous refunds and current refund mutation."""
+
return RefundData(
- shipping=shipping_previously_refunded or refund_shipping_costs, lines=lines
+ shipping=_create_refund_shipping(order, refund_shipping_costs),
+ manual_amount=_create_refund_manual_amount(order, manual_amount_to_refund),
+ lines=_create_refund_lines(
+ order, order_lines_to_refund, fulfillment_lines_to_refund
+ ),
)