Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
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__.pyindex 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 Listfrom ....order.models import Fulfillmentfrom ... import PaymentError, TransactionKind-from ...interface import GatewayConfig, GatewayResponse, PaymentData+from ...interface import GatewayResponse, PaymentDatafrom ...models import Paymentfrom . import api-from .api_types import ApiConfig, PaymentStatus, get_api_config+from .api_types import ApiConfig, PaymentStatus+from .const import NP_PLUGIN_IDfrom .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_configdef 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_configdef capture(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:raise NotImplementedError-@inject_api_configdef void(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:raise NotImplementedError-@inject_api_configdef 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_configdef refund(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:payment_id = payment_information.payment_idpayment = Payment.objects.filter(pk=payment_id).first()@@ -124,7 +113,7 @@ def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayResponif 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_numberresult = api.reregister_transaction_for_partial_return(config,diff --git a/saleor/payment/gateways/np_atobarai/api.py b/saleor/payment/gateways/np_atobarai/api.pyindex 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_REGISTRATIONresult, 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 Noneerror_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_referenceaction = TRANSACTION_REGISTRATION@@ -218,7 +236,7 @@ def report_fulfillment():payment_id = payment.psp_reference or payment.idalready_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.pyindex 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 timezonefrom posuto import Posutofrom requests.auth import HTTPBasicAuth-from saleor.order.models import Order-+from ....order.models import Orderfrom ...interface import AddressData, PaymentDatafrom ...utils import price_to_minor_unitfrom .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_TIMEOUTfrom .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 Noneelse: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.pyindex 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, NamedTuplefrom .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:@dataclassclass ApiConfig:- test_mode: bool+ url: strfill_missing_address: boolmerchant_code: strterminal_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_URLreturn 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.pyindex 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.pyindex 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 ValidationErrorfrom ....order.models import Fulfillmentfrom ....plugins.base_plugin import BasePlugin, ConfigurationTypeFieldfrom ....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, voidfrom .api_helpers import health_check+from .api_types import get_api_configfrom .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_traceGATEWAY_NAME = "NP後払い"+REQUIRED_FIELDS = (MERCHANT_CODE, SP_CODE, TERMINAL_ID, SHIPPING_COMPANY)+if TYPE_CHECKING:# flake8: noqafrom ....plugins.models import PluginConfiguration@@ -36,7 +33,7 @@ if TYPE_CHECKING:class NPAtobaraiGatewayPlugin(BasePlugin):- PLUGIN_ID = "saleor.payments.np-atobarai"+ PLUGIN_ID = NP_PLUGIN_IDPLUGIN_NAME = GATEWAY_NAMECONFIGURATION_PER_CHANNEL = TrueSUPPORTED_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.configurationconfiguration = {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.pyindex 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 pytestfrom .....plugins.manager import get_plugins_managerfrom .....plugins.models import PluginConfigurationfrom ....interface import AddressData, PaymentLineData-from .. import get_api_config+from ..api_types import get_api_configfrom ..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.pyindex 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, patchimport pytestimport requests+from .....order import OrderEventsfrom .... import PaymentErrorfrom .. import PaymentStatus, api, constfrom ..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_NOTIFICATIONdef 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.pyindex 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, sentinelimport pytestfrom 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_unitfrom .. import api_helpers, errorsfrom ..api_helpers import get_goods, get_refunded_goodsdiff --git a/saleor/payment/gateways/np_atobarai/tests/test_plugin.py b/saleor/payment/gateways/np_atobarai/tests/test_plugin.pyindex 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 loggingimport os-from unittest.mock import Mock, patch+from unittest.mock import ANY, Mock, patch+import pytestimport 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_daassert 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.pyindex 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(# thenassert "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.pyindex 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 pytestfrom .....order import FulfillmentStatus, OrderEventsfrom .... 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_CODESdef test_notify_dashboard(order):@@ -97,3 +103,59 @@ def test_get_fulfillment_for_order_multiple_fulfillments(order, fulfillment):# whenget_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_codediff --git a/saleor/payment/gateways/np_atobarai/utils.py b/saleor/payment/gateways/np_atobarai/utils.pyindex 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 FulfillmentStatusfrom ....order.events import external_notification_eventfrom ....order.models import Fulfillment, Orderfrom ... import PaymentError+from .api_types import ApiConfigfrom .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 codediff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.pyindex 45bb71ebf5..eb3a2d6d40 100644--- a/saleor/payment/tests/test_utils.py+++ b/saleor/payment/tests/test_utils.py@@ -1,3 +1,4 @@+from decimal import Decimalfrom itertools import chain, zip_longestfrom typing import Listfrom unittest.mock import Mock, patch@@ -13,6 +14,7 @@ from ...plugins.manager import get_plugins_managerfrom ..interface import PaymentLineDatafrom ..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_amountmanager = get_plugins_manager()- payment_dummy.order = None- payment_dummy.checkout = checkout_with_items# whenpayment_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_linesdiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 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.checkoutorder = 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:+ continueline_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