Skip to content

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

Refactor tracking_number_updated

Mateusz Grzybb46e8e90591a
diff --git a/saleor/payment/gateways/np_atobarai/__init__.py b/saleor/payment/gateways/np_atobarai/__init__.py
index 3a8cbdb33a..fbb848e6b0 100644
--- a/saleor/payment/gateways/np_atobarai/__init__.py
+++ b/saleor/payment/gateways/np_atobarai/__init__.py
@@ -2,6 +2,8 @@ import logging
import os
from typing import List
+from graphene import Node
+
from ....order.models import Fulfillment
from ... import PaymentError, TransactionKind
from ...interface import GatewayResponse, PaymentData
@@ -11,7 +13,6 @@ from .api_types import ApiConfig, PaymentStatus
from .const import NP_PLUGIN_ID
from .utils import (
get_fulfillment_for_order,
- get_payment_name,
get_shipping_company_code,
notify_dashboard,
)
@@ -78,27 +79,35 @@ def tracking_number_updated(fulfillment: Fulfillment, config: ApiConfig) -> None
order = fulfillment.order
payments = order.payments.filter(gateway=NP_PLUGIN_ID, is_active=True)
- if payments:
- results = [
- api.report_fulfillment(config, payment, fulfillment) for payment in payments
- ]
- else:
- results = [("", ["No active payments for this order"], False)]
+ if not payments:
+ logger.warning("No active payments for this order")
+ notify_dashboard(order, "No active payments for this order")
+ return
+
+ results = [
+ (payment.id, *api.report_fulfillment(config, payment, fulfillment))
+ for payment in payments
+ ]
for payment_id, errors, already_captured in results:
- payment_name = get_payment_name(payment_id)
+ payment_graphql_id = Node.to_global_id("Payment", payment_id)
if already_captured:
- logger.warning("%s was already captured", payment_name.capitalize())
- notify_dashboard(
- order, f"Error: {payment_name.capitalize()} was already captured"
- )
+ logger.warning(f"Payment with id {payment_graphql_id} was already captured")
+ msg = f"Error: Payment with id {payment_graphql_id} was already captured"
elif errors:
error = ", ".join(errors)
- logger.warning(f"Could not capture {payment_name} in NP Atobarai: {error}")
- notify_dashboard(order, f"Capture Error for {payment_name}")
+ logger.warning(
+ f"Could not capture payment with id {payment_graphql_id} "
+ f"in NP Atobarai: {error}"
+ )
+ msg = (
+ f"Error: Cannot capture payment with id {payment_graphql_id} ({error})"
+ )
else:
- notify_dashboard(order, f"Captured {payment_name}")
+ msg = f"Payment with id {payment_graphql_id} was captured"
+
+ notify_dashboard(order, msg)
def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
@@ -113,6 +122,8 @@ def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayRespon
if not payment:
raise PaymentError(f"Payment with id {payment_id} does not exist.")
+ # in case of refunding less than already captured
+ # the transaction needs to be re-registered in NP Atobarai
if payment_information.amount < payment.captured_amount:
order = payment.order
@@ -143,8 +154,9 @@ def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayRespon
else:
result = api.cancel_transaction(config, payment_information)
- if psp_reference := result.psp_reference:
- payment.psp_reference = psp_reference
+ new_psp_reference = result.psp_reference
+ if new_psp_reference and payment.psp_reference != new_psp_reference:
+ payment.psp_reference = new_psp_reference
payment.save(update_fields=["psp_reference"])
return GatewayResponse(
diff --git a/saleor/payment/gateways/np_atobarai/api.py b/saleor/payment/gateways/np_atobarai/api.py
index 9b7825d9ea..4f521967c2 100644
--- a/saleor/payment/gateways/np_atobarai/api.py
+++ b/saleor/payment/gateways/np_atobarai/api.py
@@ -1,5 +1,5 @@
import logging
-from typing import Dict, List, Optional, Tuple, Union
+from typing import Dict, List, Optional, Tuple
from ....order.models import Fulfillment, Order
from ...interface import PaymentData
@@ -25,7 +25,6 @@ from .const import PRE_FULFILLMENT_ERROR_CODE
from .errors import (
FULFILLMENT_REPORT,
NO_PSP_REFERENCE,
- PAYMENT_DOES_NOT_EXIST,
TRANSACTION_CANCELLATION,
TRANSACTION_CHANGE,
TRANSACTION_REGISTRATION,
@@ -80,15 +79,7 @@ def cancel_transaction(
) -> PaymentResult:
with np_atobarai_opentracing_trace("np-atobarai.checkout.payments.cancel"):
action = TRANSACTION_CANCELLATION
- payment_id = payment_information.payment_id
- payment = Payment.objects.filter(id=payment_id).first()
-
- if not payment:
- return error_payment_result(
- add_action_to_code(action, error_code=PAYMENT_DOES_NOT_EXIST)
- )
-
- psp_reference = payment.psp_reference
+ psp_reference = payment_information.psp_reference
if not psp_reference:
return error_payment_result(
@@ -234,7 +225,7 @@ def reregister_transaction_for_partial_return(
def report_fulfillment(
config: ApiConfig, payment: Payment, fulfillment: Fulfillment
-) -> Tuple[Union[str, int], List[str], bool]:
+) -> Tuple[List[str], bool]:
"""Report fulfillment.
After this action, given payment is captured in NP Atobarai.
@@ -242,8 +233,6 @@ def report_fulfillment(
with np_atobarai_opentracing_trace(
"np-atobarai.checkout.payments.report-fulfillment"
):
- payment_id = payment.psp_reference or payment.id
- already_reported = False
shipping_company_code = get_shipping_company_code(config, fulfillment)
result, error_codes = report(
@@ -253,11 +242,9 @@ def report_fulfillment(
fulfillment.tracking_number,
)
- if PRE_FULFILLMENT_ERROR_CODE in error_codes:
- already_reported = True
-
errors = get_error_messages_from_codes(
action=FULFILLMENT_REPORT, error_codes=error_codes
)
+ already_reported = PRE_FULFILLMENT_ERROR_CODE in error_codes
- return payment_id, errors, already_reported
+ return errors, already_reported
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_api.py b/saleor/payment/gateways/np_atobarai/tests/test_api.py
index dab6812644..77b6f47fe7 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_api.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api.py
@@ -4,6 +4,7 @@ from unittest.mock import ANY, Mock, patch
import pytest
import requests
+from graphene import Node
from .....order import OrderEvents
from .... import PaymentError
@@ -14,7 +15,6 @@ from ..errors import (
NO_PSP_REFERENCE,
NO_TRACKING_NUMBER,
NP_CONNECTION_ERROR,
- PAYMENT_DOES_NOT_EXIST,
SHIPPING_COMPANY_CODE_INVALID,
)
from ..plugin import NPAtobaraiGatewayPlugin
@@ -28,8 +28,7 @@ def test_refund_payment(
plugin = np_atobarai_plugin()
payment_data = np_payment_data
psp_reference = "18121200001"
- payment_dummy.psp_reference = psp_reference
- payment_dummy.save(update_fields=["psp_reference"])
+ payment_data.psp_reference = psp_reference
response = Mock(
spec=requests.Response,
status_code=200,
@@ -215,7 +214,7 @@ def test_report_fulfillment(mocked_request, config, fulfillment, payment_dummy):
mocked_request.return_value = response
# when
- _, errors, already_captured = api.report_fulfillment(
+ errors, already_captured = api.report_fulfillment(
config, payment_dummy, fulfillment
)
@@ -243,7 +242,7 @@ def test_report_fulfillment_invalid_shipping_company_code(
)
# when
- _, errors, already_captured = api.report_fulfillment(
+ errors, already_captured = api.report_fulfillment(
config, payment_dummy, fulfillment
)
@@ -257,7 +256,7 @@ def test_report_fulfillment_no_psp_reference(
_mocked_request, config, fulfillment, payment_dummy
):
# when
- _, errors, already_captured = api.report_fulfillment(
+ errors, already_captured = api.report_fulfillment(
config, payment_dummy, fulfillment
)
@@ -277,7 +276,7 @@ def test_report_fulfillment_no_tracking_number(
fulfillment.tracking_number = ""
# when
- _, errors, already_captured = api.report_fulfillment(
+ errors, already_captured = api.report_fulfillment(
config, payment_dummy, fulfillment
)
@@ -303,7 +302,7 @@ def test_report_fulfillment_np_errors(
mocked_request.return_value = response
# when
- _, errors, already_captured = api.report_fulfillment(
+ errors, already_captured = api.report_fulfillment(
config, payment_dummy, fulfillment
)
@@ -327,7 +326,7 @@ def test_report_fulfillment_connection_errors(
mocked_request.return_value = response
# when
- _, errors, already_captured = api.report_fulfillment(
+ errors, already_captured = api.report_fulfillment(
config, payment_dummy, fulfillment
)
@@ -353,7 +352,7 @@ def test_report_fulfillment_already_captured(
mocked_request.return_value = response
# when
- _, _, already_captured = api.report_fulfillment(config, payment_dummy, fulfillment)
+ _, already_captured = api.report_fulfillment(config, payment_dummy, fulfillment)
# then
assert already_captured
@@ -378,7 +377,7 @@ def test_tracking_number_updated(
):
# given
plugin = np_atobarai_plugin()
- result = ("", [], False)
+ result = ([], False)
mocked_report_fulfillment.return_value = result
order = fulfillment.order
order.payments.add(payment_np)
@@ -387,7 +386,10 @@ def test_tracking_number_updated(
plugin.tracking_number_updated(fulfillment, None)
# then
- mocked_notify_dashboard.assert_called_once_with(order, "Captured payment")
+ payment_graphql_id = Node.to_global_id("Payment", payment_np.id)
+ mocked_notify_dashboard.assert_called_once_with(
+ order, f"Payment with id {payment_graphql_id} was captured"
+ )
assert not caplog.record_tuples
@@ -404,7 +406,7 @@ def test_tracking_number_updated_errors(
# given
errors = ["error1", "error2"]
plugin = np_atobarai_plugin()
- result = ("", errors, False)
+ result = (errors, False)
mocked_report_fulfillment.return_value = result
order = fulfillment.order
order.payments.add(payment_np)
@@ -413,11 +415,16 @@ def test_tracking_number_updated_errors(
plugin.tracking_number_updated(fulfillment, None)
# then
- mocked_notify_dashboard.assert_called_once_with(order, "Capture Error for payment")
+ payment_graphql_id = Node.to_global_id("Payment", payment_np.id)
+ error = ", ".join(errors)
+ mocked_notify_dashboard.assert_called_once_with(
+ order, f"Error: Cannot capture payment with id {payment_graphql_id} ({error})"
+ )
assert len(caplog.records) == 1
assert caplog.records[0].levelno == logging.WARNING
assert caplog.records[0].message == (
- f"Could not capture payment in NP Atobarai: {', '.join(errors)}"
+ f"Could not capture payment with id {payment_graphql_id} "
+ f"in NP Atobarai: {error}"
)
@@ -433,7 +440,7 @@ def test_tracking_number_updated_already_captured(
):
# given
plugin = np_atobarai_plugin()
- result = ("", [], True)
+ result = ([], True)
mocked_report_fulfillment.return_value = result
order = fulfillment.order
order.payments.add(payment_np)
@@ -442,12 +449,17 @@ def test_tracking_number_updated_already_captured(
plugin.tracking_number_updated(fulfillment, None)
# then
+ payment_graphql_id = Node.to_global_id("Payment", payment_np.id)
mocked_notify_dashboard.assert_called_once_with(
- order, "Error: Payment was already captured"
+ order,
+ f"Error: Payment with id {payment_graphql_id} was already captured",
)
assert len(caplog.records) == 1
assert caplog.records[0].levelno == logging.WARNING
- assert caplog.records[0].message == "Payment was already captured"
+ assert (
+ caplog.records[0].message
+ == f"Payment with id {payment_graphql_id} was already captured"
+ )
@patch("saleor.payment.gateways.np_atobarai.notify_dashboard")
@@ -467,12 +479,12 @@ def test_tracking_number_updated_no_payments(
plugin.tracking_number_updated(fulfillment, None)
# then
- mocked_notify_dashboard.assert_called_once_with(order, "Capture Error for payment")
+ mocked_notify_dashboard.assert_called_once_with(
+ order, "No active payments for this order"
+ )
assert len(caplog.records) == 1
assert caplog.records[0].levelno == logging.WARNING
- assert caplog.records[0].message == (
- "Could not capture payment in NP Atobarai: No active payments for this order"
- )
+ assert caplog.records[0].message == ("No active payments for this order")
@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
@@ -804,11 +816,10 @@ def test_register_transaction_pending_unrecoverable(
def test_cancel_transaction_no_payment(np_payment_data):
# given
- payment_id = -1
- np_payment_data.payment_id = payment_id
+ np_payment_data.psp_reference = ""
# when
payment_response = api.cancel_transaction(Mock(), np_payment_data)
# then
- assert payment_response.errors == [f"TC#{PAYMENT_DOES_NOT_EXIST}"]
+ assert payment_response.errors == [f"TC#{NO_PSP_REFERENCE}"]
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_utils.py b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
index 51bce39ff3..6e4f4f35a9 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_utils.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
@@ -2,12 +2,7 @@ import pytest
from .....order import FulfillmentStatus, OrderEvents
from .... import PaymentError
-from .. import (
- get_fulfillment_for_order,
- get_payment_name,
- get_shipping_company_code,
- notify_dashboard,
-)
+from .. import get_fulfillment_for_order, get_shipping_company_code, notify_dashboard
from ..const import SHIPPING_COMPANY_CODE_METADATA_KEY, SHIPPING_COMPANY_CODES
@@ -24,22 +19,6 @@ def test_notify_dashboard(order):
assert event.parameters["message"] == message
- "payment_id, result",
- [
- ("123", "payment with psp reference 123"),
- (123, "payment with id 123"),
- ("", "payment"),
- ],
-)
-def test_get_payment_name(payment_id, result):
- # when
- payment_name = get_payment_name(payment_id)
-
- # then
- assert payment_name == result
-
-
def test_get_fulfillment_for_order(order):
# given
expected_fulfillment = order.fulfillments.create(tracking_number="123")
diff --git a/saleor/payment/gateways/np_atobarai/utils.py b/saleor/payment/gateways/np_atobarai/utils.py
index 23cfcaa758..7a7e120798 100644
--- a/saleor/payment/gateways/np_atobarai/utils.py
+++ b/saleor/payment/gateways/np_atobarai/utils.py
@@ -1,5 +1,5 @@
from contextlib import contextmanager
-from typing import Optional, Union
+from typing import Optional
from django.db.models import Q
@@ -18,14 +18,6 @@ def notify_dashboard(order: Order, message: str):
)
-def get_payment_name(payment_id: Union[int, str]) -> str:
- if not payment_id:
- return "payment"
- if isinstance(payment_id, str):
- return f"payment with psp reference {payment_id}"
- return f"payment with id {payment_id}"
-
-
STATUSES_NOT_ALLOWED_TO_REFUND = [
FulfillmentStatus.CANCELED,
FulfillmentStatus.REFUNDED,