Skip to content

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

Move refund logic to NP

Mateusz Grzyb85a0fda59197
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 37e537ce6f..eab24c039c 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -21,8 +21,9 @@ from ..payment import (
TransactionKind,
gateway,
)
+from ..payment.interface import RefundData
from ..payment.models import Payment, Transaction
-from ..payment.utils import create_payment, create_refund_data
+from ..payment.utils import create_payment
from ..warehouse.management import (
deallocate_stock,
deallocate_stock_for_order,
@@ -1445,7 +1446,6 @@ 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
@@ -1462,12 +1462,10 @@ def _process_refund(
manager,
amount=amount,
channel_slug=order.channel.slug,
- refund_data=create_refund_data(
- order,
- order_lines_to_refund,
- fulfillment_lines_to_refund,
- manual_amount_to_refund,
- refund_shipping_costs,
+ refund_data=RefundData(
+ order_lines_to_refund=order_lines_to_refund,
+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,
+ refund_shipping_costs=refund_shipping_costs,
),
)
except PaymentError:
diff --git a/saleor/payment/gateways/np_atobarai/api.py b/saleor/payment/gateways/np_atobarai/api.py
index 89b0689fb3..e81e2405b0 100644
--- a/saleor/payment/gateways/np_atobarai/api.py
+++ b/saleor/payment/gateways/np_atobarai/api.py
@@ -100,7 +100,7 @@ def 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.
"""
- goods = get_goods_with_refunds(config, payment_information)
+ goods = get_goods_with_refunds(config, payment, payment_information)
data = {
"transactions": [
@@ -175,7 +175,7 @@ def reregister_transaction_for_partial_return(
)
return errors_payment_result(error_messages)
- goods = get_goods_with_refunds(config, payment_information)
+ goods = get_goods_with_refunds(config, payment, 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 9181b17f56..435f7e78d1 100644
--- a/saleor/payment/gateways/np_atobarai/api_helpers.py
+++ b/saleor/payment/gateways/np_atobarai/api_helpers.py
@@ -9,6 +9,7 @@ from requests.auth import HTTPBasicAuth
from ....order.models import Order
from ...interface import AddressData, PaymentData, PaymentLineData, RefundData
+from ...models import Payment
from ...utils import price_to_minor_unit
from .api_types import NPResponse, error_np_response
from .const import NP_ATOBARAI, REQUEST_TIMEOUT
@@ -22,7 +23,13 @@ from .errors import (
SHIPPING_ADDRESS_INVALID,
SHIPPING_COMPANY_CODE_INVALID,
)
-from .utils import notify_dashboard, np_atobarai_opentracing_trace
+from .utils import (
+ calculate_manual_refund_amount,
+ calculate_refunded_shipping,
+ create_refunded_lines,
+ notify_dashboard,
+ np_atobarai_opentracing_trace,
+)
if TYPE_CHECKING:
from . import ApiConfig
@@ -167,6 +174,7 @@ def _get_voucher_and_shipping_goods(
def get_goods_with_refunds(
config: "ApiConfig",
+ payment: Payment,
payment_information: PaymentData,
) -> List[dict]:
"""Combine PaymentLinesData and RefundData into NP Atobarai's goods list.
@@ -176,12 +184,22 @@ def get_goods_with_refunds(
"""
goods_lines = []
refund_data = payment_information.refund_data or RefundData(
- lines={}, shipping=False, manual_amount=Decimal("0.00")
+ order_lines_to_refund=[],
+ fulfillment_lines_to_refund=[],
+ refund_shipping_costs=False,
+ )
+ order = payment.order
+ assert order
+
+ refunded_lines = create_refunded_lines(order, refund_data)
+ refunded_shipping = calculate_refunded_shipping(order, refund_data)
+ refunded_manual_amount = calculate_manual_refund_amount(
+ order, refund_data, payment_information
)
for line in payment_information.lines_data.lines:
quantity = line.quantity
- refunded_quantity = refund_data.lines.get(line.variant_id)
+ refunded_quantity = refunded_lines.get(line.variant_id)
if refunded_quantity:
quantity -= refunded_quantity
@@ -193,22 +211,19 @@ def get_goods_with_refunds(
}
)
- discount_amount = refund_data.manual_amount
- if discount_amount:
+ if refunded_manual_amount:
goods_lines.append(
{
"goods_name": "Discount",
"goods_price": format_price(
- -discount_amount, payment_information.currency
+ -refunded_manual_amount, payment_information.currency
),
"quantity": 1,
}
)
goods_lines.extend(
- _get_voucher_and_shipping_goods(
- config, payment_information, refund_data.shipping
- )
+ _get_voucher_and_shipping_goods(config, payment_information, refunded_shipping)
)
return goods_lines
diff --git a/saleor/payment/gateways/np_atobarai/plugin.py b/saleor/payment/gateways/np_atobarai/plugin.py
index 62bd5a05cb..f898cecc02 100644
--- a/saleor/payment/gateways/np_atobarai/plugin.py
+++ b/saleor/payment/gateways/np_atobarai/plugin.py
@@ -36,7 +36,7 @@ class NPAtobaraiGatewayPlugin(BasePlugin):
PLUGIN_ID = NP_PLUGIN_ID
PLUGIN_NAME = GATEWAY_NAME
CONFIGURATION_PER_CHANNEL = True
- SUPPORTED_CURRENCIES = "JPY"
+ SUPPORTED_CURRENCIES = "PLN"
DEFAULT_CONFIGURATION = [
{"name": MERCHANT_CODE, "value": None},
diff --git a/saleor/payment/gateways/np_atobarai/utils.py b/saleor/payment/gateways/np_atobarai/utils.py
index 7a7e120798..da0fc52dfc 100644
--- a/saleor/payment/gateways/np_atobarai/utils.py
+++ b/saleor/payment/gateways/np_atobarai/utils.py
@@ -1,13 +1,17 @@
+from collections import defaultdict
from contextlib import contextmanager
-from typing import Optional
+from decimal import Decimal
+from itertools import chain
+from typing import Dict, Optional
-from django.db.models import Q
+from django.db.models import Q, Sum
from ....core.tracing import opentracing_trace
from ....order import FulfillmentStatus
from ....order.events import external_notification_event
-from ....order.models import Fulfillment, Order
+from ....order.models import Fulfillment, FulfillmentLine, Order
from ... import PaymentError
+from ...interface import PaymentData, RefundData
from .api_types import ApiConfig
from .const import SHIPPING_COMPANY_CODE_METADATA_KEY, SHIPPING_COMPANY_CODES
@@ -62,3 +66,104 @@ def np_atobarai_opentracing_trace(span_name: str):
service_name="np-atobarai",
):
yield
+
+
+def create_refunded_lines(
+ order: Order,
+ refund_data: RefundData,
+) -> Dict[int, int]:
+ """Return all refunded product variants for specified order.
+
+ 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"
+ ).filter(
+ fulfillment__order_id=order.pk,
+ fulfillment__status__in=[
+ FulfillmentStatus.REFUNDED,
+ FulfillmentStatus.REFUNDED_AND_RETURNED,
+ ],
+ order_line__variant_id__isnull=False,
+ )
+
+ previous_refund_lines = (
+ (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, line1.quantity)
+ for line1 in refund_data.order_lines_to_refund
+ if (variant := line1.variant)
+ )
+ current_fulfillment_refund_lines = (
+ (f_variant_id, line1.quantity)
+ for line1 in refund_data.fulfillment_lines_to_refund
+ if (f_variant_id := line1.line.order_line.variant_id)
+ )
+
+ refund_lines = chain(
+ previous_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 dict(summed_refund_lines)
+
+
+def calculate_manual_refund_amount(
+ order: Order,
+ refund_data: RefundData,
+ payment_information: PaymentData,
+ # manual_amount_to_refund: Optional[Decimal],
+) -> Decimal:
+ """Return sum of all manual refunds for specified order.
+
+ Takes into account previous refunds and current refund mutation parameters.
+ """
+
+ if (
+ refund_data.fulfillment_lines_to_refund
+ or refund_data.order_lines_to_refund
+ or refund_data.refund_shipping_costs
+ ):
+ manual_amount_to_refund = Decimal("0.00")
+ else:
+ manual_amount_to_refund = payment_information.amount
+
+ previous_manual_amount_to_refund = order.fulfillments.filter(
+ status__in=[
+ FulfillmentStatus.REFUNDED,
+ FulfillmentStatus.REFUNDED_AND_RETURNED,
+ ],
+ lines__order_line__variant_id__isnull=True,
+ shipping_refund_amount__isnull=True,
+ ).aggregate(manual_amount=Sum("total_refund_amount"))["manual_amount"]
+
+ 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 calculate_refunded_shipping(
+ order: Order,
+ refund_data: RefundData,
+) -> 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_data.refund_shipping_costs
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index dfdfe2e7dd..368527fd65 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -4,6 +4,9 @@ from enum import Enum
from functools import cached_property
from typing import Any, Callable, Dict, List, Optional, Union
+from ..order import FulfillmentLineData
+from ..order.fetch import OrderLineInfo
+
JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
@@ -85,9 +88,9 @@ class PaymentLinesData:
@dataclass
class RefundData:
- shipping: bool
- manual_amount: Decimal
- lines: Dict[int, int]
+ order_lines_to_refund: List[OrderLineInfo]
+ fulfillment_lines_to_refund: List[FulfillmentLineData]
+ refund_shipping_costs: bool
@dataclass
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 3e6804f87d..fc8ae4a222 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -11,11 +11,13 @@ from ...order.actions import create_refund_fulfillment
from ...order.fetch import OrderLineInfo
from ...order.models import Order
from ...plugins.manager import get_plugins_manager
+from ..gateways.np_atobarai.utils import (
+ calculate_manual_refund_amount,
+ calculate_refunded_shipping,
+ create_refunded_lines,
+)
from ..interface import PaymentLineData, PaymentLinesData
from ..utils import (
- _create_refund_lines,
- _create_refund_manual_amount,
- _create_refund_shipping,
create_payment_lines_information,
get_channel_slug_from_payment,
try_void_or_refund_inactive_payment,
@@ -60,7 +62,7 @@ def test_create_refund_lines_order_lines(order_with_lines):
fulfillment_refund_lines = []
# when
- lines = _create_refund_lines(
+ lines = create_refunded_lines(
order_with_lines,
order_refund_lines,
fulfillment_refund_lines,
@@ -86,7 +88,7 @@ def test_create_refund_lines_fulfillment_lines(fulfilled_order):
]
# when
- lines = _create_refund_lines(
+ lines = create_refunded_lines(
fulfilled_order,
order_refund_lines,
fulfillment_refund_lines,
@@ -124,7 +126,7 @@ def test_create_refund_data_previously_refunded_order_lines(
fulfillment_refund_lines = []
# when
- lines = _create_refund_lines(
+ lines = create_refunded_lines(
order_with_lines,
current_order_refund_lines,
fulfillment_refund_lines,
@@ -175,7 +177,7 @@ def test_create_refund_data_previously_refunded_fulfillment_lines(
]
# when
- lines = _create_refund_lines(
+ lines = create_refunded_lines(
fulfilled_order,
order_refund_lines,
current_fulfillment_refund_lines,
@@ -210,7 +212,7 @@ def test_create_refund_manual_amount(
expected_manual_amount,
):
assert (
- _create_refund_manual_amount(order, current_manual_refund_amount)
+ calculate_manual_refund_amount(order, current_manual_refund_amount)
== expected_manual_amount
)
@@ -233,7 +235,7 @@ def test_create_refund_manual_amount_previously_refunded(
)
# when
- manual_amount = _create_refund_manual_amount(order, current_manual_refund_amount)
+ manual_amount = calculate_manual_refund_amount(order, current_manual_refund_amount)
# then
expected_manual_amount = (previous_manual_refund_amount or Decimal("0.00")) + (
@@ -244,7 +246,7 @@ def test_create_refund_manual_amount_previously_refunded(
@pytest.mark.parametrize("refund_shipping", [True, False])
def test_create_refund_shipping(order, refund_shipping):
- assert _create_refund_shipping(order, refund_shipping) is refund_shipping
+ assert calculate_refunded_shipping(order, refund_shipping) is refund_shipping
@patch("saleor.order.actions.gateway.refund")
@@ -275,7 +277,7 @@ def test_create_refund_shipping_previously_refunded(
)
# when
- refund = _create_refund_shipping(
+ refund = calculate_refunded_shipping(
order,
current_refund_shipping_costs,
)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index fa27d57ea4..897bff730f 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,14 +1,12 @@
import json
import logging
-from collections import defaultdict
from decimal import Decimal
-from itertools import chain
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, Sum
+from django.db.models import Q
from ..account.models import User
from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -16,9 +14,7 @@ from ..checkout.models import Checkout
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
from ..discount.utils import fetch_active_discounts
-from ..order import FulfillmentLineData, FulfillmentStatus
-from ..order.fetch import OrderLineInfo
-from ..order.models import Fulfillment, FulfillmentLine, Order
+from ..order.models import Order
from ..plugins.manager import PluginsManager, get_plugins_manager
from . import (
ChargeStatus,
@@ -219,115 +215,6 @@ def create_payment_information(
)
-def _create_refund_lines(
- order: Order,
- order_lines_to_refund: List[OrderLineInfo],
- fulfillment_lines_to_refund: List[FulfillmentLineData],
-) -> Dict[int, int]:
- """Return all refunded product variants for specified order.
-
- 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"
- ).filter(
- fulfillment__order_id=order.pk,
- fulfillment__status__in=[
- FulfillmentStatus.REFUNDED,
- FulfillmentStatus.REFUNDED_AND_RETURNED,
- ],
- order_line__variant_id__isnull=False,
- )
-
- previous_refund_lines = (
- (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, line1.quantity)
- for line1 in order_lines_to_refund
- if (variant := line1.variant)
- )
- current_fulfillment_refund_lines = (
- (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(
- previous_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 dict(summed_refund_lines)
-
-
-def _create_refund_manual_amount(
- order: Order,
- manual_amount_to_refund: Optional[Decimal],
-) -> Decimal:
- """Return sum of all manual refunds for specified order.
-
- Takes into account previous refunds and current refund mutation parameters.
- """
- previous_manual_amount_to_refund = (
- Fulfillment.objects.prefetch_related("lines__order_line")
- .filter(
- order_id=order.pk,
- lines__order_line__variant_id__isnull=True,
- shipping_refund_amount__isnull=True,
- )
- .aggregate(manual_amount=Sum("total_refund_amount"))["manual_amount"]
- )
-
- 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=_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
- ),
- )
-
-
def create_payment(
gateway: str,
total: Decimal,