Skip to content

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

Add NP final code review feedback onto 3.1

Krzysztof Kulig7ad5490580ba
diff --git a/saleor/payment/gateways/np_atobarai/__init__.py b/saleor/payment/gateways/np_atobarai/__init__.py
index fa6f0fdd59..33b07ae79d 100644
--- a/saleor/payment/gateways/np_atobarai/__init__.py
+++ b/saleor/payment/gateways/np_atobarai/__init__.py
@@ -4,10 +4,11 @@ from typing import List
from ....order.models import Fulfillment
from ... import PaymentError, TransactionKind
-from ...interface import GatewayConfig, GatewayResponse, PaymentData
+from ...interface import GatewayResponse, PaymentData
from ...models import Payment
from . import api
-from .api_types import ApiConfig, PaymentStatus, get_api_config
+from .api_types import ApiConfig, PaymentStatus
+from .const import NP_PLUGIN_ID
from .utils import (
get_fulfillment_for_order,
get_payment_name,
@@ -18,20 +19,14 @@ from .utils import (
logger = logging.getLogger(__name__)
-def inject_api_config(fun):
- def inner(payment_information: PaymentData, config: GatewayConfig):
- return fun(payment_information, get_api_config(config.connection_params))
-
- return inner
-
-
def parse_errors(errors: List[str]) -> str:
- # FIXME: better solution?
- # Transaction.error in database has max_length of 256
- return os.linesep.join(errors)[:256]
+ # Field error of Transaction db model has max length of 256
+ # Error codes have max length of 11
+ # We are limiting errors to maximum of 11 codes, because:
+ # 11 * 11 + 10 * 2 (max length of linesep) == 141 < 256
+ return os.linesep.join(errors[:11])
-@inject_api_config
def process_payment(
payment_information: PaymentData, config: ApiConfig
) -> GatewayResponse:
@@ -39,7 +34,11 @@ def process_payment(
payment = Payment.objects.filter(pk=payment_id).first()
if not payment:
- raise PaymentError(f"Payment with id {payment_id} does not exist.")
+ logger.error(
+ "Payment with id %s does not exist",
+ payment_information.graphql_payment_id,
+ )
+ raise PaymentError("Payment does not exist.")
result = api.register_transaction(payment.order, config, payment_information)
@@ -56,24 +55,17 @@ def process_payment(
)
-@inject_api_config
def capture(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
raise NotImplementedError
-@inject_api_config
def void(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
raise NotImplementedError
-@inject_api_config
def tracking_number_updated(fulfillment: Fulfillment, config: ApiConfig) -> None:
- from .plugin import NPAtobaraiGatewayPlugin
-
order = fulfillment.order
- payments = order.payments.filter(
- gateway=NPAtobaraiGatewayPlugin.PLUGIN_ID, is_active=True
- )
+ payments = order.payments.filter(gateway=NP_PLUGIN_ID, is_active=True)
if payments:
results = [
@@ -92,15 +84,12 @@ def tracking_number_updated(fulfillment: Fulfillment, config: ApiConfig) -> None
)
elif errors:
error = ", ".join(errors)
- logger.warning(
- "Could not capture %s in NP Atobarai: %s", payment_name, error
- )
+ logger.warning(f"Could not capture {payment_name} in NP Atobarai: {error}")
notify_dashboard(order, f"Capture Error for {payment_name}")
else:
notify_dashboard(order, f"Captured {payment_name}")
-@inject_api_config
def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
payment_id = payment_information.payment_id
payment = Payment.objects.filter(pk=payment_id).first()
@@ -124,7 +113,7 @@ def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayRespon
if not result:
fulfillment = get_fulfillment_for_order(order)
- shipping_company_code = get_shipping_company_code(fulfillment)
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
tracking_number = fulfillment.tracking_number
result = api.reregister_transaction_for_partial_return(
config,
diff --git a/saleor/payment/gateways/np_atobarai/api.py b/saleor/payment/gateways/np_atobarai/api.py
index f78e2772c0..6ff72ca605 100644
--- a/saleor/payment/gateways/np_atobarai/api.py
+++ b/saleor/payment/gateways/np_atobarai/api.py
@@ -40,12 +40,18 @@ logger = logging.getLogger(__name__)
def register_transaction(
order: Optional[Order], config: ApiConfig, payment_information: "PaymentData"
) -> PaymentResult:
+ """Create a new transaction in NP Atobarai.
+
+ On pending status from NP the transaction is cancelled and
+ reason for pending is returned as error message.
+ """
with np_atobarai_opentracing_trace("np-atobarai.checkout.payments.register"):
+ action = TRANSACTION_REGISTRATION
result, error_codes = register(config, payment_information)
if error_codes:
error_messages = get_error_messages_from_codes(
- action=TRANSACTION_REGISTRATION, error_codes=error_codes
+ action, error_codes=error_codes
)
return errors_payment_result(error_messages)
@@ -58,7 +64,9 @@ def register_transaction(
handle_unrecoverable_state(
order, "cancel", transaction_id, cancel_error_codes
)
- error_messages = result["authori_hold"]
+ error_messages = get_error_messages_from_codes(
+ action, error_codes=result["authori_hold"]
+ )
return PaymentResult(
status=status,
@@ -104,6 +112,11 @@ def change_transaction(
payment_information: PaymentData,
refund_data: Optional[Dict[int, int]],
) -> Optional[PaymentResult]:
+ """Partial refund.
+
+ If the fulfillment was reported prior to changing given transaction,
+ then this function is a noop and return value is None.
+ """
with np_atobarai_opentracing_trace("np-atobarai.checkout.payments.change"):
if refund_data:
goods = get_refunded_goods(config, refund_data, payment_information)
@@ -144,6 +157,10 @@ def change_transaction(
)
if PRE_FULFILLMENT_ERROR_CODE in error_codes:
+ logger.info(
+ "Fulfillment for payment with id %s was reported",
+ payment_information.graphql_payment_id,
+ )
return None
error_messages = get_error_messages_from_codes(
@@ -160,6 +177,7 @@ def reregister_transaction_for_partial_return(
tracking_number: Optional[str],
refund_data: Optional[Dict[int, int]],
) -> PaymentResult:
+ """Partial refund after fulfillment report."""
with np_atobarai_opentracing_trace("np-atobarai.checkout.payments.reregister"):
psp_reference = payment.psp_reference
action = TRANSACTION_REGISTRATION
@@ -218,7 +236,7 @@ def report_fulfillment(
):
payment_id = payment.psp_reference or payment.id
already_reported = False
- shipping_company_code = get_shipping_company_code(fulfillment)
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
result, error_codes = report(
config,
diff --git a/saleor/payment/gateways/np_atobarai/api_helpers.py b/saleor/payment/gateways/np_atobarai/api_helpers.py
index d329036aa7..480cb3486f 100644
--- a/saleor/payment/gateways/np_atobarai/api_helpers.py
+++ b/saleor/payment/gateways/np_atobarai/api_helpers.py
@@ -7,12 +7,11 @@ from django.utils import timezone
from posuto import Posuto
from requests.auth import HTTPBasicAuth
-from saleor.order.models import Order
-
+from ....order.models import Order
from ...interface import AddressData, PaymentData
from ...utils import price_to_minor_unit
from .api_types import NPResponse, error_np_response
-from .const import NP_ATOBARAI, NP_TEST_URL, NP_URL, REQUEST_TIMEOUT
+from .const import NP_ATOBARAI, REQUEST_TIMEOUT
from .errors import (
BILLING_ADDRESS_INVALID,
NO_BILLING_ADDRESS,
@@ -34,7 +33,7 @@ logger = logging.getLogger(__name__)
def get_url(config: "ApiConfig", path: str = "") -> str:
"""Resolve test/production URLs based on the api config."""
- return f"{NP_TEST_URL if config.test_mode else NP_URL}{path}"
+ return f"{config.url}{path}"
def _request(
@@ -105,6 +104,7 @@ def format_address(config: "ApiConfig", ad: AddressData) -> Optional[str]:
try:
jap_ad = pp.get(ad.postal_code)
except KeyError:
+ logger.warning(f"Invalid japanese postal code: {ad.postal_code}")
return None
else:
return (
@@ -208,7 +208,7 @@ def register(
"settlement_type": NP_ATOBARAI,
"billed_amount": billed_amount,
"customer": {
- "customer_name": billing.first_name,
+ "customer_name": format_name(billing),
"company_name": billing.company_name,
"zip_code": billing.postal_code,
"address": formatted_billing,
diff --git a/saleor/payment/gateways/np_atobarai/api_types.py b/saleor/payment/gateways/np_atobarai/api_types.py
index 92bc18d203..780df79a8a 100644
--- a/saleor/payment/gateways/np_atobarai/api_types.py
+++ b/saleor/payment/gateways/np_atobarai/api_types.py
@@ -5,6 +5,8 @@ from typing import Dict, List, NamedTuple
from .const import (
FILL_MISSING_ADDRESS,
MERCHANT_CODE,
+ NP_TEST_URL,
+ NP_URL,
SHIPPING_COMPANY,
SKU_AS_NAME,
SP_CODE,
@@ -24,7 +26,7 @@ def error_np_response(error_message: str) -> NPResponse:
@dataclass
class ApiConfig:
- test_mode: bool
+ url: str
fill_missing_address: bool
merchant_code: str
terminal_id: str
@@ -56,8 +58,9 @@ def errors_payment_result(errors: List[str]) -> PaymentResult:
def get_api_config(connection_params: dict) -> ApiConfig:
+ url = NP_TEST_URL if connection_params[USE_SANDBOX] else NP_URL
return ApiConfig(
- test_mode=connection_params[USE_SANDBOX],
+ url=url,
fill_missing_address=connection_params[FILL_MISSING_ADDRESS],
merchant_code=connection_params[MERCHANT_CODE],
sp_code=connection_params[SP_CODE],
diff --git a/saleor/payment/gateways/np_atobarai/const.py b/saleor/payment/gateways/np_atobarai/const.py
index d4301956c8..67e0571017 100644
--- a/saleor/payment/gateways/np_atobarai/const.py
+++ b/saleor/payment/gateways/np_atobarai/const.py
@@ -4,6 +4,8 @@ NP_ATOBARAI_WIZ = "03"
REQUEST_TIMEOUT = 30
+NP_PLUGIN_ID = "saleor.payments.np-atobarai"
+
NP_TEST_URL = "https://ctcp.np-payment-gateway.com/v1"
NP_URL = "https://cp.np-payment-gateway.com/v1"
diff --git a/saleor/payment/gateways/np_atobarai/plugin.py b/saleor/payment/gateways/np_atobarai/plugin.py
index b819714900..9c5ae0b873 100644
--- a/saleor/payment/gateways/np_atobarai/plugin.py
+++ b/saleor/payment/gateways/np_atobarai/plugin.py
@@ -5,19 +5,14 @@ from django.core.exceptions import ValidationError
from ....order.models import Fulfillment
from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField
from ....plugins.error_codes import PluginErrorCode
-from . import (
- GatewayConfig,
- capture,
- get_api_config,
- process_payment,
- refund,
- tracking_number_updated,
- void,
-)
+from ...interface import GatewayConfig
+from . import capture, process_payment, refund, tracking_number_updated, void
from .api_helpers import health_check
+from .api_types import get_api_config
from .const import (
FILL_MISSING_ADDRESS,
MERCHANT_CODE,
+ NP_PLUGIN_ID,
SHIPPING_COMPANY,
SHIPPING_COMPANY_CODES,
SKU_AS_NAME,
@@ -29,6 +24,8 @@ from .utils import np_atobarai_opentracing_trace
GATEWAY_NAME = "NP後払い"
+REQUIRED_FIELDS = (MERCHANT_CODE, SP_CODE, TERMINAL_ID, SHIPPING_COMPANY)
+
if TYPE_CHECKING:
# flake8: noqa
from ....plugins.models import PluginConfiguration
@@ -36,7 +33,7 @@ if TYPE_CHECKING:
class NPAtobaraiGatewayPlugin(BasePlugin):
- PLUGIN_ID = "saleor.payments.np-atobarai"
+ PLUGIN_ID = NP_PLUGIN_ID
PLUGIN_NAME = GATEWAY_NAME
CONFIGURATION_PER_CHANNEL = True
SUPPORTED_CURRENCIES = "JPY"
@@ -118,25 +115,39 @@ class NPAtobaraiGatewayPlugin(BasePlugin):
def capture_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
- return capture(payment_information, self._get_gateway_config())
+ return capture(
+ payment_information,
+ get_api_config(self._get_gateway_config().connection_params),
+ )
def refund_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
- return refund(payment_information, self._get_gateway_config())
+ return refund(
+ payment_information,
+ get_api_config(self._get_gateway_config().connection_params),
+ )
def void_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
- return void(payment_information, self._get_gateway_config())
+ return void(
+ payment_information,
+ get_api_config(self._get_gateway_config().connection_params),
+ )
def process_payment(
self, payment_information: "PaymentData", previous_value
) -> "GatewayResponse":
- return process_payment(payment_information, self._get_gateway_config())
+ return process_payment(
+ payment_information,
+ get_api_config(self._get_gateway_config().connection_params),
+ )
def tracking_number_updated(self, fulfillment: "Fulfillment", previous_value):
- tracking_number_updated(fulfillment, self._get_gateway_config())
+ tracking_number_updated(
+ fulfillment, get_api_config(self._get_gateway_config().connection_params)
+ )
def get_supported_currencies(self, previous_value):
return self.SUPPORTED_CURRENCIES
@@ -172,33 +183,30 @@ class NPAtobaraiGatewayPlugin(BasePlugin):
configuration = plugin_configuration.configuration
configuration = {item["name"]: item["value"] for item in configuration}
missing_fields = [
- field
- for field in [MERCHANT_CODE, SP_CODE, TERMINAL_ID, SHIPPING_COMPANY]
- if not configuration[field]
+ field for field in REQUIRED_FIELDS if not configuration[field]
]
- if plugin_configuration.active:
- if missing_fields:
- raise ValidationError(
- {
- field: ValidationError(
- f"The parameter is required.",
- code=PluginErrorCode.REQUIRED.value,
- )
- for field in missing_fields
- }
- )
- if configuration[SHIPPING_COMPANY] not in SHIPPING_COMPANY_CODES:
- raise ValidationError(
- {
- SHIPPING_COMPANY: ValidationError(
- f"Shipping company code is invalid",
- code=PluginErrorCode.INVALID.value,
- )
- }
- )
-
- cls.validate_authentication(plugin_configuration)
+ if missing_fields:
+ raise ValidationError(
+ {
+ field: ValidationError(
+ f"The parameter is required.",
+ code=PluginErrorCode.REQUIRED.value,
+ )
+ for field in missing_fields
+ }
+ )
+ if configuration[SHIPPING_COMPANY] not in SHIPPING_COMPANY_CODES:
+ raise ValidationError(
+ {
+ SHIPPING_COMPANY: ValidationError(
+ f"Shipping company code is invalid",
+ code=PluginErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ cls.validate_authentication(plugin_configuration)
def get_payment_config(self, previous_value):
return []
diff --git a/saleor/payment/gateways/np_atobarai/tests/conftest.py b/saleor/payment/gateways/np_atobarai/tests/conftest.py
index af901b6819..e754b693d1 100644
--- a/saleor/payment/gateways/np_atobarai/tests/conftest.py
+++ b/saleor/payment/gateways/np_atobarai/tests/conftest.py
@@ -6,7 +6,7 @@ import pytest
from .....plugins.manager import get_plugins_manager
from .....plugins.models import PluginConfiguration
from ....interface import AddressData, PaymentLineData
-from .. import get_api_config
+from ..api_types import get_api_config
from ..const import (
FILL_MISSING_ADDRESS,
MERCHANT_CODE,
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_api.py b/saleor/payment/gateways/np_atobarai/tests/test_api.py
index 008be428d0..dab6812644 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_api.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api.py
@@ -5,6 +5,7 @@ from unittest.mock import ANY, Mock, patch
import pytest
import requests
+from .....order import OrderEvents
from .... import PaymentError
from .. import PaymentStatus, api, const
from ..api_helpers import format_price, get_goods_with_discount, get_refunded_goods
@@ -768,7 +769,37 @@ def test_register_transaction_pending(
mocked_register.assert_called_once()
mocked_cancel.assert_called_once_with(config, transaction_id)
assert payment_response.status == PaymentStatus.PENDING
- assert payment_response.errors == errors
+ assert payment_response.errors == [f"TR#{e}" for e in errors]
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.cancel")
+@patch("saleor.payment.gateways.np_atobarai.api.register")
+def test_register_transaction_pending_unrecoverable(
+ mocked_register, mocked_cancel, order, config, np_payment_data, caplog
+):
+ # given
+ transaction_id = "123123123"
+ errors = ["RE009", "RE015"]
+ register_result = {
+ "authori_result": "10",
+ "np_transaction_id": transaction_id,
+ "authori_hold": errors,
+ }
+ mocked_register.return_value = NPResponse(result=register_result, error_codes=[])
+ cancel_errors = ["1", "2", "3"]
+ mocked_cancel.return_value = NPResponse(result={}, error_codes=cancel_errors)
+
+ # when
+ payment_response = api.register_transaction(order, config, np_payment_data)
+
+ # then
+ mocked_register.assert_called_once()
+ mocked_cancel.assert_called_once_with(config, transaction_id)
+ assert payment_response.status == PaymentStatus.PENDING
+ assert payment_response.errors == [f"TR#{e}" for e in errors]
+ assert caplog.record_tuples == [(ANY, logging.ERROR, ANY)]
+ event = order.events.first()
+ assert event.type == OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
def test_cancel_transaction_no_payment(np_payment_data):
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 24679adfe6..0d0eb58df8 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py
@@ -4,9 +4,8 @@ from unittest.mock import DEFAULT, Mock, patch, sentinel
import pytest
from posuto import Posuto
-from saleor.payment.interface import AddressData
-from saleor.payment.utils import price_to_minor_unit
-
+from ....interface import AddressData
+from ....utils import price_to_minor_unit
from .. import api_helpers, errors
from ..api_helpers import get_goods, get_refunded_goods
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_plugin.py b/saleor/payment/gateways/np_atobarai/tests/test_plugin.py
index 98430ee97a..fe42294c81 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_plugin.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_plugin.py
@@ -1,8 +1,12 @@
+import logging
import os
-from unittest.mock import Mock, patch
+from unittest.mock import ANY, Mock, patch
+import pytest
import requests
+from .... import PaymentError
+
@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
def test_process_payment_authorized(
@@ -67,6 +71,23 @@ def test_process_payment_refused(mocked_request, np_atobarai_plugin, np_payment_
assert not gateway_response.is_success
+def test_process_payment_no_payment(np_atobarai_plugin, np_payment_data, caplog):
+ # given
+ plugin = np_atobarai_plugin()
+ payment_data = np_payment_data
+ payment_data.payment_id = -1
+
+ # when
+ with pytest.raises(PaymentError, match=r".*not exist.*"):
+ plugin.process_payment(payment_data, None)
+
+ # then
+ payment_id = np_payment_data.graphql_payment_id
+ assert caplog.record_tuples == [
+ (ANY, logging.ERROR, f"Payment with id {payment_id} does not exist")
+ ]
+
+
@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
def test_process_payment_error(mocked_request, np_atobarai_plugin, np_payment_data):
# given
@@ -88,3 +109,23 @@ def test_process_payment_error(mocked_request, np_atobarai_plugin, np_payment_da
assert gateway_response.error == os.linesep.join(
f"TR#{code}" for code in error_codes
)
+
+
+def test_capture_payment(np_atobarai_plugin):
+ # given
+ plugin = np_atobarai_plugin()
+
+ # then
+ with pytest.raises(NotImplementedError):
+ # when
+ plugin.capture_payment(Mock(), None)
+
+
+def test_void_payment(np_atobarai_plugin):
+ # given
+ plugin = np_atobarai_plugin()
+
+ # then
+ with pytest.raises(NotImplementedError):
+ # when
+ plugin.void_payment(Mock(), None)
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py b/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
index 19373a7e19..b5fa3be723 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
@@ -67,3 +67,15 @@ def test_validate_plugin_configuration_invalid_shipping_company_code(
# then
assert "shipping_company" in excinfo.value.error_dict
+
+
[email protected]("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_validate_plugin_configuration_inactive(mocked_request, np_atobarai_plugin):
+ # given
+ plugin = np_atobarai_plugin(active=False)
+
+ # when
+ NPAtobaraiGatewayPlugin.validate_plugin_configuration(plugin)
+
+ # then
+ mocked_request.assert_not_called()
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_utils.py b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
index 1e60550b50..51bce39ff3 100644
--- a/saleor/payment/gateways/np_atobarai/tests/test_utils.py
+++ b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
@@ -2,7 +2,13 @@ import pytest
from .....order import FulfillmentStatus, OrderEvents
from .... import PaymentError
-from .. import get_fulfillment_for_order, get_payment_name, notify_dashboard
+from .. import (
+ get_fulfillment_for_order,
+ get_payment_name,
+ get_shipping_company_code,
+ notify_dashboard,
+)
+from ..const import SHIPPING_COMPANY_CODE_METADATA_KEY, SHIPPING_COMPANY_CODES
def test_notify_dashboard(order):
@@ -97,3 +103,59 @@ def test_get_fulfillment_for_order_multiple_fulfillments(order, fulfillment):
# when
get_fulfillment_for_order(order)
+
+
+ "config_shipping_company_code",
+ SHIPPING_COMPANY_CODES,
+)
+def test_get_shipping_company_code_no_metadata(
+ config, fulfillment, config_shipping_company_code
+):
+ # given
+ config.shipping_company = config_shipping_company_code
+
+ # when
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
+
+ # then
+ assert shipping_company_code == config_shipping_company_code
+
+
+ ["config_shipping_company_code", "result_shipping_company_code"],
+ zip(SHIPPING_COMPANY_CODES + ["invalid_code"], SHIPPING_COMPANY_CODES + [None]),
+)
+def test_get_shipping_company_code_valid_metadata(
+ config, fulfillment, config_shipping_company_code, result_shipping_company_code
+):
+ # given
+ fulfillment.store_value_in_private_metadata(
+ {SHIPPING_COMPANY_CODE_METADATA_KEY: config_shipping_company_code}
+ )
+ fulfillment.save(update_fields=["private_metadata"])
+
+ # when
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
+
+ # then
+ assert shipping_company_code == result_shipping_company_code
+
+
+ "config_shipping_company_code",
+ SHIPPING_COMPANY_CODES,
+)
+def test_get_shipping_company_code_invalid_metadata(
+ config, fulfillment, config_shipping_company_code
+):
+ # given
+ config.shipping_company = config_shipping_company_code
+ fulfillment.store_value_in_private_metadata({"invalid_metadata_key": "50000"})
+ fulfillment.save(update_fields=["private_metadata"])
+
+ # when
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
+
+ # then
+ assert shipping_company_code == config_shipping_company_code
diff --git a/saleor/payment/gateways/np_atobarai/utils.py b/saleor/payment/gateways/np_atobarai/utils.py
index 3a09da1947..23cfcaa758 100644
--- a/saleor/payment/gateways/np_atobarai/utils.py
+++ b/saleor/payment/gateways/np_atobarai/utils.py
@@ -8,6 +8,7 @@ from ....order import FulfillmentStatus
from ....order.events import external_notification_event
from ....order.models import Fulfillment, Order
from ... import PaymentError
+from .api_types import ApiConfig
from .const import SHIPPING_COMPANY_CODE_METADATA_KEY, SHIPPING_COMPANY_CODES
@@ -34,9 +35,11 @@ STATUSES_NOT_ALLOWED_TO_REFUND = [
]
-def get_shipping_company_code(fulfillment: Fulfillment) -> Optional[str]:
+def get_shipping_company_code(
+ config: ApiConfig, fulfillment: Fulfillment
+) -> Optional[str]:
code = fulfillment.get_value_from_private_metadata(
- SHIPPING_COMPANY_CODE_METADATA_KEY, default="50000"
+ SHIPPING_COMPANY_CODE_METADATA_KEY, default=config.shipping_company
)
return None if code not in SHIPPING_COMPANY_CODES else code
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 45bb71ebf5..eb3a2d6d40 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from itertools import chain, zip_longest
from typing import List
from unittest.mock import Mock, patch
@@ -13,6 +14,7 @@ from ...plugins.manager import get_plugins_manager
from ..interface import PaymentLineData
from ..utils import (
SHIPPING_PAYMENT_LINE_ID,
+ VOUCHER_PAYMENT_LINE_ID,
create_payment_lines_information,
create_refund_data,
)
@@ -338,20 +340,48 @@ def test_create_payment_lines_information_order(payment_dummy):
]
-def test_create_payment_lines_checkout(payment_dummy, checkout_with_items):
+def test_create_payment_lines_information_order_with_voucher(payment_dummy):
# given
+ voucher_amount = Decimal("12.30")
+ order = payment_dummy.order
+ order.undiscounted_total_gross_amount += voucher_amount
manager = get_plugins_manager()
- payment_dummy.order = None
- payment_dummy.checkout = checkout_with_items
# when
payment_lines = create_payment_lines_information(payment_dummy, manager)
# then
- lines = fetch_checkout_lines(checkout_with_items)
- discounts = []
- checkout_info = fetch_checkout_info(checkout_with_items, lines, discounts, manager)
- address = checkout_with_items.shipping_address
+
+ assert payment_lines == [
+ PaymentLineData(
+ gross=line.unit_price_gross_amount,
+ variant_id=line.variant_id,
+ product_name=f"{line.product_name}, {line.variant_name}",
+ product_sku=line.product_sku,
+ quantity=line.quantity,
+ )
+ for line in order.lines.all()
+ ] + [
+ PaymentLineData(
+ gross=order.shipping_price_gross_amount,
+ variant_id=SHIPPING_PAYMENT_LINE_ID,
+ product_name="Shipping",
+ product_sku="Shipping",
+ quantity=1,
+ ),
+ PaymentLineData(
+ gross=-voucher_amount,
+ variant_id=VOUCHER_PAYMENT_LINE_ID,
+ product_name="Voucher",
+ product_sku="Voucher",
+ quantity=1,
+ ),
+ ]
+
+
+def get_expected_checkout_payment_lines(
+ manager, checkout_info, lines, address, discounts
+):
expected_payment_lines = []
for line_info in lines:
@@ -401,4 +431,71 @@ def test_create_payment_lines_checkout(payment_dummy, checkout_with_items):
)
)
+ return expected_payment_lines
+
+
+def test_create_payment_lines_information_checkout(payment_dummy, checkout_with_items):
+ # given
+ manager = get_plugins_manager()
+ payment_dummy.order = None
+ payment_dummy.checkout = checkout_with_items
+
+ # when
+ payment_lines = create_payment_lines_information(payment_dummy, manager)
+
+ # then
+ lines = fetch_checkout_lines(checkout_with_items)
+ discounts = []
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, discounts, manager)
+ address = checkout_with_items.shipping_address
+ expected_payment_lines = get_expected_checkout_payment_lines(
+ manager, checkout_info, lines, address, discounts
+ )
+
assert payment_lines == expected_payment_lines
+
+
+def test_create_payment_lines_information_checkout_with_voucher(
+ payment_dummy, checkout_with_items
+):
+ # given
+ manager = get_plugins_manager()
+ voucher_amount = Decimal("12.30")
+ payment_dummy.order = None
+ checkout_with_items.discount_amount = voucher_amount
+ payment_dummy.checkout = checkout_with_items
+
+ # when
+ payment_lines = create_payment_lines_information(payment_dummy, manager)
+
+ # then
+ lines = fetch_checkout_lines(checkout_with_items)
+ discounts = []
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, discounts, manager)
+ address = checkout_with_items.shipping_address
+ expected_payment_lines = get_expected_checkout_payment_lines(
+ manager, checkout_info, lines, address, discounts
+ )
+ expected_payment_lines.append(
+ PaymentLineData(
+ gross=-voucher_amount,
+ variant_id=VOUCHER_PAYMENT_LINE_ID,
+ product_name="Voucher",
+ product_sku="Voucher",
+ quantity=1,
+ )
+ )
+
+ assert payment_lines == expected_payment_lines
+
+
+def test_create_payment_lines_information_invalid_payment(payment_dummy):
+ # given
+ manager = get_plugins_manager()
+ payment_dummy.order = None
+
+ # when
+ payment_lines = create_payment_lines_information(payment_dummy, manager)
+
+ # then
+ assert not payment_lines
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 707b0fe365..3cd60a37b5 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -50,82 +50,97 @@ def create_payment_lines_information(
) -> List[PaymentLineData]:
checkout = payment.checkout
order = payment.order
- line_items = []
+
if checkout:
- lines = fetch_checkout_lines(checkout)
- discounts = fetch_active_discounts()
- checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)
- address = checkout_info.shipping_address or checkout_info.billing_address
-
- for line_info in lines:
- total = checkout_line_total(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- checkout_line_info=line_info,
- discounts=discounts,
- )
- unit_price = manager.calculate_checkout_line_unit_price(
- total,
- line_info.line.quantity,
- checkout_info,
- lines,
- line_info,
- address,
- discounts,
- )
- unit_gross = unit_price.gross.amount
-
- quantity = line_info.line.quantity
- product_name = f"{line_info.variant.product.name}, {line_info.variant.name}"
- product_sku = line_info.variant.sku
- line_items.append(
- PaymentLineData(
- quantity=quantity,
- product_name=product_name,
- product_sku=product_sku,
- variant_id=line_info.variant.id,
- gross=unit_gross,
- )
- )
- shipping_amount = manager.calculate_checkout_shipping(
+ return create_checkout_payment_lines_information(checkout, manager)
+ elif order:
+ return create_order_payment_lines_information(order)
+
+ return []
+
+
+def create_checkout_payment_lines_information(
+ checkout: Checkout, manager: PluginsManager
+) -> List[PaymentLineData]:
+ line_items = []
+ lines = fetch_checkout_lines(checkout)
+ discounts = fetch_active_discounts()
+ checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)
+ address = checkout_info.shipping_address or checkout_info.billing_address
+
+ for line_info in lines:
+ total = checkout_line_total(
+ manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
+ checkout_line_info=line_info,
discounts=discounts,
- ).gross.amount
+ )
+ unit_price = manager.calculate_checkout_line_unit_price(
+ total,
+ line_info.line.quantity,
+ checkout_info,
+ lines,
+ line_info,
+ address,
+ discounts,
+ )
+ unit_gross = unit_price.gross.amount
- line_items.append(create_shipping_payment_line_data(amount=shipping_amount))
+ quantity = line_info.line.quantity
+ product_name = f"{line_info.variant.product.name}, {line_info.variant.name}"
+ product_sku = line_info.variant.sku
+ line_items.append(
+ PaymentLineData(
+ quantity=quantity,
+ product_name=product_name,
+ product_sku=product_sku,
+ variant_id=line_info.variant.id,
+ gross=unit_gross,
+ )
+ )
+ shipping_amount = manager.calculate_checkout_shipping(
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ ).gross.amount
- voucher_line_item = create_checkout_voucher_payment_line_data(checkout)
- if voucher_line_item:
- line_items.append(voucher_line_item)
+ line_items.append(create_shipping_payment_line_data(amount=shipping_amount))
+
+ voucher_line_item = create_checkout_voucher_payment_line_data(checkout)
+ if voucher_line_item:
+ line_items.append(voucher_line_item)
+
+ return line_items
- elif order:
- for order_line in order.lines.all():
- product_name = f"{order_line.product_name}, {order_line.variant_name}"
-
- variant_id = order_line.variant_id
- if variant_id is None:
- continue
-
- line_items.append(
- PaymentLineData(
- quantity=order_line.quantity,
- product_name=product_name,
- product_sku=order_line.product_sku,
- variant_id=variant_id,
- gross=order_line.unit_price_gross_amount,
- )
- )
+
+def create_order_payment_lines_information(order: Order) -> List[PaymentLineData]:
+ line_items = []
+ for order_line in order.lines.all():
+ product_name = f"{order_line.product_name}, {order_line.variant_name}"
+
+ variant_id = order_line.variant_id
+ if variant_id is None:
+ continue
line_items.append(
- create_shipping_payment_line_data(amount=order.shipping_price_gross_amount)
+ PaymentLineData(
+ quantity=order_line.quantity,
+ product_name=product_name,
+ product_sku=order_line.product_sku,
+ variant_id=variant_id,
+ gross=order_line.unit_price_gross_amount,
+ )
)
- voucher_line_item = create_order_voucher_payment_line_data(order)
- if voucher_line_item:
- line_items.append(voucher_line_item)
+ line_items.append(
+ create_shipping_payment_line_data(amount=order.shipping_price_gross_amount)
+ )
+
+ voucher_line_item = create_order_voucher_payment_line_data(order)
+ if voucher_line_item:
+ line_items.append(voucher_line_item)
return line_items