Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove NP Atobarai plugin (#18927)
Lukasz Ostrowski5a8035eca8b4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9a66aad361..93cf9f3533 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,7 @@ All notable, unreleased changes to this project will be documented in this file.- `AppInstallInput` for `appInstall` mutation now requires `appName` and `manifestUrl` fields in the schema, matching the validation that was always enforced by the mutation logic.- Removed Adyen plugin (payment gateway). [Switch to the app](https://docs.saleor.io/developer/app-store/apps/adyen/overview).- Removed `partial` field from the `Payment` GraphQL type. This field was an Adyen-specific workaround and always returned `false` after the Adyen plugin removal. Ensure you are not relying on this field (on Adyen gateway in general) before upgrading.+- Removed the NP Atobarai payment gateway plugin (`saleor.payment.gateways.np_atobarai`). Use the [App](https://docs.saleor.io/developer/app-store/apps/np-atobarai/overview) instead.### GraphQL APIdiff --git a/pyproject.toml b/pyproject.tomlindex 533792e443..e0816e0f10 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -48,7 +48,6 @@ dependencies = ["petl==1.7.17","phonenumberslite>=9.0.7,<10","pillow>=12.1.1,<13",- "posuto>=2025.1.0,<2026","prices~=1.0","promise~=2.3","pybars3>=0.9.7,<0.10",diff --git a/saleor/payment/gateways/np_atobarai/__init__.py b/saleor/payment/gateways/np_atobarai/__init__.pydeleted file mode 100644index 7b03242820..0000000000--- a/saleor/payment/gateways/np_atobarai/__init__.py+++ /dev/null@@ -1,169 +0,0 @@-import logging-import os--from graphene import Node--from ....order.models import Fulfillment-from ... import PaymentError, TransactionKind-from ...interface import GatewayResponse, PaymentData-from ...models import Payment-from . import api-from .api_helpers import get_goods_with_refunds-from .api_types import ApiConfig, PaymentStatus-from .const import NP_PLUGIN_ID-from .utils import (- get_fulfillment_for_order,- get_shipping_company_code,- notify_dashboard,-)--logger = logging.getLogger(__name__)---def parse_errors(errors: list[str]) -> str:- # 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])---def process_payment(- payment_information: PaymentData, config: ApiConfig-) -> GatewayResponse:- """Create new transaction in NP Atobarai.-- Returns unsuccessful response if payment status from- NP response is PENDING or FAILED.- """- result = api.register_transaction(config, payment_information)-- return GatewayResponse(- is_success=result.status == PaymentStatus.SUCCESS,- action_required=False,- kind=TransactionKind.CAPTURE,- amount=payment_information.amount,- currency=payment_information.currency,- transaction_id=result.psp_reference or "",- error=parse_errors(result.errors),- raw_response=result.raw_response,- psp_reference=result.psp_reference,- )---def capture(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:- raise NotImplementedError---def void(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:- raise NotImplementedError---def tracking_number_updated(fulfillment: Fulfillment, config: ApiConfig) -> None:- """Event callback on updating order tracking number.-- Captures payment in NP Atobarai and sends dashboard notification of the result.- """- order = fulfillment.order- payments = order.payments.filter(gateway=NP_PLUGIN_ID, is_active=True)-- 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_graphql_id = Node.to_global_id("Payment", payment_id)-- if already_captured:- logger.warning(- "Payment with id %s was already captured", payment_graphql_id- )- msg = f"Error: Payment with id {payment_graphql_id} was already captured"- elif errors:- error = ", ".join(errors)- logger.warning(- "Could not capture payment with id %s in NP Atobarai: %s",- payment_graphql_id,- error,- )- msg = (- f"Error: Cannot capture payment with id {payment_graphql_id} ({error})"- )- else:- msg = f"Payment with id {payment_graphql_id} was captured"-- notify_dashboard(order, msg)---def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:- """Refund an existing transaction.-- A new psp reference may be issued,- which will be saved in payment object.- """- payment_id = payment_information.payment_id- payment = Payment.objects.filter(pk=payment_id).first()-- if not payment:- raise PaymentError(f"Payment with id {payment_id} does not exist.")-- goods, billed_amount = get_goods_with_refunds(config, payment, payment_information)-- # in case of refunding less than already captured- # and not all lines are being refunded,- # the transaction needs to be re-registered in NP Atobarai- if payment_information.amount < payment.captured_amount:- order = payment.order-- if not order:- raise PaymentError(- f"Order does not exist for payment with id {payment_id}."- )-- result = api.change_transaction(- config,- payment,- payment_information,- goods,- billed_amount,- )-- if result.status == PaymentStatus.FOR_REREGISTRATION:- fulfillment = get_fulfillment_for_order(order)- shipping_company_code = get_shipping_company_code(config, fulfillment)- tracking_number = fulfillment.tracking_number- result = api.reregister_transaction_for_partial_return(- config,- payment,- payment_information,- shipping_company_code,- tracking_number,- goods,- billed_amount,- )-- else:- result = api.cancel_transaction(config, payment_information)-- 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(- is_success=result.status == PaymentStatus.SUCCESS,- action_required=False,- kind=TransactionKind.REFUND,- amount=payment_information.amount,- currency=payment_information.currency,- transaction_id=result.psp_reference or "",- error=parse_errors(result.errors),- raw_response=result.raw_response,- psp_reference=result.psp_reference,- )diff --git a/saleor/payment/gateways/np_atobarai/api.py b/saleor/payment/gateways/np_atobarai/api.pydeleted file mode 100644index 44dbdf78ab..0000000000--- a/saleor/payment/gateways/np_atobarai/api.py+++ /dev/null@@ -1,235 +0,0 @@-import logging-from decimal import Decimal--from ....order.models import Fulfillment-from ...interface import PaymentData-from ...models import Payment-from .api_helpers import (- cancel,- format_price,- handle_unrecoverable_state,- np_request,- register,- report,-)-from .api_types import (- ApiConfig,- PaymentResult,- PaymentStatus,- error_payment_result,- errors_payment_result,-)-from .const import PRE_FULFILLMENT_ERROR_CODE-from .errors import (- FULFILLMENT_REPORT,- NO_PSP_REFERENCE,- TRANSACTION_CANCELLATION,- TRANSACTION_CHANGE,- TRANSACTION_REGISTRATION,- add_action_to_code,- get_error_messages_from_codes,-)-from .utils import get_shipping_company_code--logger = logging.getLogger(__name__)---def register_transaction(- 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.- """- action = TRANSACTION_REGISTRATION- result, error_codes, raw_response = register(config, payment_information)-- if error_codes:- error_messages = get_error_messages_from_codes(action, error_codes=error_codes)- return errors_payment_result(error_messages, result)-- status = result["authori_result"]- transaction_id = result["np_transaction_id"]- error_messages = []-- if status == PaymentStatus.PENDING:- if cancel_error_codes := cancel(config, transaction_id).error_codes:- handle_unrecoverable_state(- None, "cancel", transaction_id, cancel_error_codes- )- error_messages = get_error_messages_from_codes(- action, error_codes=result["authori_hold"]- )-- return PaymentResult(- status=status,- psp_reference=transaction_id,- errors=error_messages,- raw_response=raw_response,- )---def cancel_transaction(- config: ApiConfig, payment_information: PaymentData-) -> PaymentResult:- action = TRANSACTION_CANCELLATION- psp_reference = payment_information.psp_reference-- if not psp_reference:- return error_payment_result(- add_action_to_code(action, error_code=NO_PSP_REFERENCE)- )-- _result, error_codes, raw_response = cancel(config, psp_reference)-- if error_codes:- error_messages = get_error_messages_from_codes(action, error_codes=error_codes)- return errors_payment_result(error_messages, raw_response)-- return PaymentResult(status=PaymentStatus.SUCCESS, raw_response=raw_response)---def change_transaction(- config: ApiConfig,- payment: Payment,- payment_information: PaymentData,- goods: list[dict],- billed_amount: Decimal,-) -> PaymentResult:- """Change transaction.-- If the fulfillment was reported prior to changing given transaction,- then no change is applied and payment status is set to FOR_REREGISTRATION.- """- data = {- "transactions": [- {- "np_transaction_id": payment.psp_reference,- "billed_amount": format_price(- billed_amount,- payment_information.currency,- ),- "goods": goods,- }- ]- }-- result, error_codes, raw_response = np_request(- config, "patch", "/transactions/update", json=data- )-- if not error_codes:- status = result["authori_result"]- transaction_id = result["np_transaction_id"]-- if status == PaymentStatus.PENDING:- if cancel_error_codes := cancel(config, transaction_id).error_codes:- handle_unrecoverable_state(- payment.order, "cancel", transaction_id, cancel_error_codes- )- error_messages = result["authori_hold"]- return errors_payment_result(error_messages, raw_response)-- return PaymentResult(status=PaymentStatus.SUCCESS, raw_response=raw_response)-- if PRE_FULFILLMENT_ERROR_CODE in error_codes:- logger.info(- "Fulfillment for payment with id %s was reported",- payment_information.graphql_payment_id,- )- return PaymentResult(- status=PaymentStatus.FOR_REREGISTRATION, raw_response=raw_response- )-- error_messages = get_error_messages_from_codes(- action=TRANSACTION_CHANGE, error_codes=error_codes- )- return errors_payment_result(error_messages, raw_response)---def reregister_transaction_for_partial_return(- config: ApiConfig,- payment: Payment,- payment_information: PaymentData,- shipping_company_code: str | None,- tracking_number: str | None,- goods: list[dict],- billed_amount: Decimal,-) -> PaymentResult:- """Change transaction.-- Use it after capturing the payment, otherwise `change_transaction`- is the preferred function.- """- psp_reference = payment.psp_reference- action = TRANSACTION_REGISTRATION-- if not psp_reference:- return error_payment_result(- add_action_to_code(- action,- error_code=NO_PSP_REFERENCE,- )- )-- result, cancel_error_codes, raw_response = cancel(config, psp_reference)- if cancel_error_codes:- error_messages = get_error_messages_from_codes(- action=TRANSACTION_CANCELLATION, error_codes=cancel_error_codes- )- return errors_payment_result(error_messages, raw_response)-- result, error_codes, raw_response = register(- config,- payment_information,- format_price(billed_amount, payment_information.currency),- goods,- )-- if not error_codes:- new_psp_reference = result["np_transaction_id"]-- result, error_codes, raw_response = report(- config, shipping_company_code, new_psp_reference, tracking_number- )-- if error_codes:- error_messages = get_error_messages_from_codes(- FULFILLMENT_REPORT, error_codes=error_codes- )- return errors_payment_result(error_messages, raw_response)-- return PaymentResult(- status=PaymentStatus.SUCCESS,- psp_reference=new_psp_reference,- raw_response=raw_response,- )-- error_messages = get_error_messages_from_codes(action, error_codes=error_codes)-- return errors_payment_result(error_messages, raw_response)---def report_fulfillment(- config: ApiConfig, payment: Payment, fulfillment: Fulfillment-) -> tuple[list[str], bool]:- """Report fulfillment.-- After this action, given payment is captured in NP Atobarai.- """- shipping_company_code = get_shipping_company_code(config, fulfillment)-- _result, error_codes, _raw_response = report(- config,- shipping_company_code,- payment.psp_reference,- fulfillment.tracking_number,- )-- errors = get_error_messages_from_codes(- action=FULFILLMENT_REPORT, error_codes=error_codes- )- already_reported = PRE_FULFILLMENT_ERROR_CODE in error_codes-- return errors, already_reporteddiff --git a/saleor/payment/gateways/np_atobarai/api_helpers.py b/saleor/payment/gateways/np_atobarai/api_helpers.pydeleted file mode 100644index de02cfb35e..0000000000--- a/saleor/payment/gateways/np_atobarai/api_helpers.py+++ /dev/null@@ -1,345 +0,0 @@-import logging-from collections.abc import Iterable-from decimal import Decimal-from typing import TYPE_CHECKING--import requests-from django.conf import settings-from django.utils import timezone-from posuto import Posuto-from requests.auth import HTTPBasicAuth--from ....core.http_client import HTTPClient-from ....order.models import Order-from ... import PaymentError-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-from .errors import (- BILLING_ADDRESS_INVALID,- NO_BILLING_ADDRESS,- NO_PSP_REFERENCE,- NO_SHIPPING_ADDRESS,- NO_TRACKING_NUMBER,- NP_CONNECTION_ERROR,- SHIPPING_ADDRESS_INVALID,- SHIPPING_COMPANY_CODE_INVALID,-)-from .utils import (- create_refunded_lines,- notify_dashboard,- np_atobarai_otel_trace,-)--if TYPE_CHECKING:- from . import ApiConfig---logger = logging.getLogger(__name__)---def get_url(config: "ApiConfig", path: str = "") -> str:- """Resolve test/production URLs based on the api config."""- return f"{config.url}{path}"---def _request(- config: "ApiConfig",- method: str,- path: str = "",- json: dict | None = None,-) -> requests.Response:- trace_name = f"np-atobarai.request.{path.lstrip('/')}"- with np_atobarai_otel_trace(trace_name):- response = HTTPClient.send_request(- method,- get_url(config, path),- timeout=(settings.REQUESTS_CONN_EST_TIMEOUT, REQUEST_TIMEOUT),- json=json or {},- auth=HTTPBasicAuth(config.merchant_code, config.sp_code),- headers={"X-NP-Terminal-Id": config.terminal_id},- allow_redirects=False,- )- # NP Atobarai returns error codes with http status code 400- # Because we want to pass those errors to the end user,- # we treat 400 as valid response.- if 400 < response.status_code <= 600:- raise requests.HTTPError(request=response.request, response=response)- return response---def np_request(- config: "ApiConfig", method: str, path: str = "", json: dict | None = None-) -> NPResponse:- response_data = {}- try:- response = _request(config, method, path, json)- response_data = response.json()- if "errors" in response_data:- return NPResponse({}, response_data["errors"][0]["codes"], response_data)- return NPResponse(response_data["results"][0], [], response_data)- except requests.RequestException:- logger.warning("Cannot connect to NP Atobarai.", exc_info=True)- return NPResponse({}, [NP_CONNECTION_ERROR], response_data)---def handle_unrecoverable_state(- order: Order | None,- action: str,- transaction_id: str,- error_codes: Iterable[str],-) -> None:- message = f"Payment #{transaction_id} {action.capitalize()} Unrecoverable Error"- logger.error("%s: %s", message, ", ".join(error_codes))- if order:- notify_dashboard(order, message)---def health_check(config: "ApiConfig") -> bool:- try:- _request(config, "post", "/authorizations/find")- return True- except requests.RequestException:- return False---def format_name(ad: AddressData) -> str:- """Follow the Japanese name guidelines."""- return f"{ad.last_name} {ad.first_name}".strip()---def format_address(config: "ApiConfig", ad: AddressData) -> str | None:- """Follow the Japanese address guidelines."""- # example: "東京都千代田区麹町4-2-6 住友不動産麹町ファーストビル5階"- if not config.fill_missing_address:- return f"{ad.country_area}{ad.street_address_1}{ad.street_address_2}"- try:- with Posuto() as pp:- jap_ad = pp.get(ad.postal_code)- except KeyError:- logger.warning("Invalid japanese postal code: %s", ad.postal_code)- return None- else:- return (- f"{ad.country_area}"- f"{jap_ad.city}"- f"{jap_ad.neighborhood}"- f"{ad.street_address_1}"- f"{ad.street_address_2}"- )---def format_price(price: Decimal, currency: str) -> int:- return int(price_to_minor_unit(price, currency))---def _get_goods_name(line: PaymentLineData, config: "ApiConfig") -> str:- if not config.sku_as_name:- return line.product_name- if sku := line.product_sku:- return sku- return str(line.variant_id)---def _get_voucher_and_shipping_goods(- config: "ApiConfig",- payment_information: PaymentData,-) -> list[dict]:- """Convert voucher and shipping amount into NP Atobarai goods lines."""- goods_lines = []- voucher_amount = payment_information.lines_data.voucher_amount- if voucher_amount:- goods_lines.append(- {- "goods_name": "Voucher",- "goods_price": format_price(- voucher_amount, payment_information.currency- ),- "quantity": 1,- }- )- shipping_amount = payment_information.lines_data.shipping_amount- if shipping_amount:- goods_lines.append(- {- "goods_name": "Shipping",- "goods_price": format_price(- shipping_amount, payment_information.currency- ),- "quantity": 1,- }- )-- return goods_lines---def get_goods_with_refunds(- config: "ApiConfig",- payment: Payment,- payment_information: PaymentData,-) -> tuple[list[dict], Decimal]:- """Combine PaymentLinesData and RefundData into NP Atobarai's goods list.-- Used for payment updates.- Returns current state of order lines after refunds and total order amount.- """- goods_lines = []- refund_data = payment_information.refund_data or RefundData()-- order = payment.order- if not order:- raise PaymentError("Cannot refund payment without order.")-- refunded_lines = create_refunded_lines(order, refund_data)-- total = Decimal("0.00")- for line in payment_information.lines_data.lines:- quantity = line.quantity- refunded_quantity = refunded_lines.get(line.variant_id)- if refunded_quantity:- quantity -= refunded_quantity-- if quantity:- goods_lines.append(- {- "goods_name": _get_goods_name(line, config),- "goods_price": format_price(- line.amount, payment_information.currency- ),- "quantity": quantity,- }- )- total += line.amount * quantity-- goods_lines.extend(_get_voucher_and_shipping_goods(config, payment_information))- total += payment_information.lines_data.shipping_amount- total += payment_information.lines_data.voucher_amount-- billed_amount = payment.captured_amount - payment_information.amount- # NP requires that the sum of all goods prices is equal to billing amount- refunded_manual_amount = billed_amount - total-- if refunded_manual_amount:- goods_lines.append(- {- "goods_name": "Discount",- "goods_price": format_price(- refunded_manual_amount, payment_information.currency- ),- "quantity": 1,- }- )-- return goods_lines, billed_amount---def get_goods(config: "ApiConfig", payment_information: PaymentData) -> list[dict]:- """Convert PaymentLinesData into NP Atobarai's goods list.-- Used for initial payment registration only.- """- return [- {- "quantity": line.quantity,- "goods_name": _get_goods_name(line, config),- "goods_price": format_price(line.amount, payment_information.currency),- }- for line in payment_information.lines_data.lines- ] + _get_voucher_and_shipping_goods(config, payment_information)---def cancel(config: "ApiConfig", transaction_id: str) -> NPResponse:- data = {"transactions": [{"np_transaction_id": transaction_id}]}- return np_request(config, "patch", "/transactions/cancel", json=data)---def register(- config: "ApiConfig",- payment_information: "PaymentData",- billed_amount: int | None = None,- goods: list[dict] | None = None,-) -> NPResponse:- if billed_amount is None:- billed_amount = format_price(- payment_information.amount, payment_information.currency- )-- if goods is None:- goods = get_goods(config, payment_information)-- order_date = timezone.now().strftime("%Y-%m-%d")-- billing = payment_information.billing- shipping = payment_information.shipping-- if not billing:- return error_np_response(NO_BILLING_ADDRESS)- if not shipping:- return error_np_response(NO_SHIPPING_ADDRESS)-- formatted_billing = format_address(config, billing)- formatted_shipping = format_address(config, shipping)-- if not formatted_billing:- return error_np_response(BILLING_ADDRESS_INVALID)- if not formatted_shipping:- return error_np_response(SHIPPING_ADDRESS_INVALID)-- data = {- "transactions": [- {- "shop_transaction_id": payment_information.payment_id,- "shop_order_date": order_date,- "settlement_type": NP_ATOBARAI,- "billed_amount": billed_amount,- "customer": {- "customer_name": format_name(billing),- "company_name": billing.company_name,- "zip_code": billing.postal_code,- "address": formatted_billing,- "tel": billing.phone.replace("+81", "0"),- "email": payment_information.customer_email,- },- "dest_customer": {- "customer_name": format_name(shipping),- "company_name": shipping.company_name,- "zip_code": shipping.postal_code,- "address": formatted_shipping,- "tel": shipping.phone.replace("+81", "0"),- },- "goods": goods,- },- ]- }-- return np_request(config, "post", "/transactions", json=data)---def report(- config: "ApiConfig",- shipping_company_code: str | None,- psp_reference: str | None,- shipping_slip_number: str | None,-) -> NPResponse:- if not shipping_company_code:- return error_np_response(SHIPPING_COMPANY_CODE_INVALID)-- if not psp_reference:- return error_np_response(NO_PSP_REFERENCE)-- if not shipping_slip_number:- return error_np_response(NO_TRACKING_NUMBER)-- data = {- "transactions": [- {- "np_transaction_id": psp_reference,- "pd_company_code": shipping_company_code,- "slip_no": shipping_slip_number,- }- ]- }-- return np_request(config, "post", "/shipments", json=data)diff --git a/saleor/payment/gateways/np_atobarai/api_types.py b/saleor/payment/gateways/np_atobarai/api_types.pydeleted file mode 100644index 6225252285..0000000000--- a/saleor/payment/gateways/np_atobarai/api_types.py+++ /dev/null@@ -1,76 +0,0 @@-from dataclasses import dataclass, field-from enum import Enum-from typing import NamedTuple--from .const import (- FILL_MISSING_ADDRESS,- MERCHANT_CODE,- NP_TEST_URL,- NP_URL,- SHIPPING_COMPANY,- SKU_AS_NAME,- SP_CODE,- TERMINAL_ID,- USE_SANDBOX,-)---class NPResponse(NamedTuple):- result: dict- error_codes: list[str]- raw_response: dict---def error_np_response(error_message: str) -> NPResponse:- return NPResponse({}, [error_message], {})---@dataclass-class ApiConfig:- url: str- fill_missing_address: bool- merchant_code: str- terminal_id: str- sp_code: str- shipping_company: str- sku_as_name: bool---class PaymentStatus(str, Enum):- SUCCESS = "00"- PENDING = "10"- FAILED = "20"- FOR_REREGISTRATION = "RE"---@dataclass-class PaymentResult:- status: PaymentStatus- psp_reference: str | None = None- raw_response: dict[str, str] = field(default_factory=dict)- errors: list[str] = field(default_factory=list)---def error_payment_result(error_message: str) -> PaymentResult:- return PaymentResult(- status=PaymentStatus.FAILED, errors=[error_message], raw_response={}- )---def errors_payment_result(errors: list[str], response: dict) -> PaymentResult:- return PaymentResult(- status=PaymentStatus.FAILED, errors=errors, raw_response=response- )---def get_api_config(connection_params: dict) -> ApiConfig:- url = NP_TEST_URL if connection_params[USE_SANDBOX] else NP_URL- return ApiConfig(- url=url,- fill_missing_address=connection_params[FILL_MISSING_ADDRESS],- merchant_code=connection_params[MERCHANT_CODE],- sp_code=connection_params[SP_CODE],- terminal_id=connection_params[TERMINAL_ID],- shipping_company=connection_params[SHIPPING_COMPANY],- sku_as_name=connection_params[SKU_AS_NAME],- )diff --git a/saleor/payment/gateways/np_atobarai/const.py b/saleor/payment/gateways/np_atobarai/const.pydeleted file mode 100644index cd940f3dc3..0000000000--- a/saleor/payment/gateways/np_atobarai/const.py+++ /dev/null@@ -1,46 +0,0 @@-# This integration is currently supporting the settlement type 02 - NP Atobarai.-NP_ATOBARAI = "02"-NP_ATOBARAI_WIZ = "03"--# Custom timeout, as NetProtections recommends a timeout of around 30s.-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"--MERCHANT_CODE = "merchant_code"-FILL_MISSING_ADDRESS = "fill_missing_address"-SP_CODE = "sp_code"-TERMINAL_ID = "terminal_id"-USE_SANDBOX = "use_sandbox"-SHIPPING_COMPANY = "shipping_company"-SKU_AS_NAME = "sku_in_invoice"--SHIPPING_COMPANY_CODES = [- "50000",- "59010",- "59020",- "59030",- "59040",- "59041",- "59042",- "59043",- "59050",- "59060",- "59080",- "59090",- "59110",- "59140",- "59150",- "59100",- "59160",- "55555",-]--PRE_FULFILLMENT_ERROR_CODE = "E0100115"-ALREADY_REREGISTERED_ERROR_CODE = "E0131006"-EXCEEDED_NUMBER_OF_REREGISTRATIONS_ERROR_CODE = "E0131011"--SHIPPING_COMPANY_CODE_METADATA_KEY = "np-atobarai.pd-company-code"diff --git a/saleor/payment/gateways/np_atobarai/errors.py b/saleor/payment/gateways/np_atobarai/errors.pydeleted file mode 100644index 8c49c396ff..0000000000--- a/saleor/payment/gateways/np_atobarai/errors.py+++ /dev/null@@ -1,32 +0,0 @@-from collections.abc import Iterable--TRANSACTION_REGISTRATION = "TR"-TRANSACTION_CANCELLATION = "TC"-TRANSACTION_CHANGE = "CH"-FULFILLMENT_REPORT = "FR"---def add_action_to_code(action: str, error_code: str) -> str:- return f"{action}#{error_code}"---def get_error_messages_from_codes(action: str, error_codes: Iterable[str]) -> list[str]:- return [add_action_to_code(action, code) for code in error_codes]---# connection error codes-NP_CONNECTION_ERROR = "SALEORNP000"--# address error codes-NO_BILLING_ADDRESS = "SALEORNP001"-NO_SHIPPING_ADDRESS = "SALEORNP002"-BILLING_ADDRESS_INVALID = "SALEORNP003"-SHIPPING_ADDRESS_INVALID = "SALEORNP004"--# payment error codes-NO_PSP_REFERENCE = "SALEORNP005"-PAYMENT_DOES_NOT_EXIST = "SALEORNP006"--# fulfillment error codes-NO_TRACKING_NUMBER = "SALEORNP007"-SHIPPING_COMPANY_CODE_INVALID = "SALEORNP008"diff --git a/saleor/payment/gateways/np_atobarai/plugin.py b/saleor/payment/gateways/np_atobarai/plugin.pydeleted file mode 100644index 4c69619ef9..0000000000--- a/saleor/payment/gateways/np_atobarai/plugin.py+++ /dev/null@@ -1,212 +0,0 @@-from typing import TYPE_CHECKING--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 ...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,- SP_CODE,- TERMINAL_ID,- USE_SANDBOX,-)-from .utils import np_atobarai_otel_trace--GATEWAY_NAME = "NP後払い"--REQUIRED_FIELDS = (MERCHANT_CODE, SP_CODE, TERMINAL_ID, SHIPPING_COMPANY)--if TYPE_CHECKING:- from ....plugins.models import PluginConfiguration- from . import GatewayResponse, PaymentData---class NPAtobaraiGatewayPlugin(BasePlugin):- PLUGIN_ID = NP_PLUGIN_ID- PLUGIN_NAME = GATEWAY_NAME- CONFIGURATION_PER_CHANNEL = True- SUPPORTED_CURRENCIES = "JPY"-- DEFAULT_CONFIGURATION = [- {"name": MERCHANT_CODE, "value": None},- {"name": SP_CODE, "value": None},- {"name": TERMINAL_ID, "value": None},- {"name": USE_SANDBOX, "value": True},- {"name": FILL_MISSING_ADDRESS, "value": True},- {"name": SHIPPING_COMPANY, "value": "50000"},- {"name": SKU_AS_NAME, "value": False},- ]-- CONFIG_STRUCTURE = {- MERCHANT_CODE: {- "type": ConfigurationTypeField.SECRET,- "help_text": "Provide NP後払い Merchant Code.",- "label": "Merchant Code",- },- SP_CODE: {- "type": ConfigurationTypeField.SECRET,- "help_text": "Provide NP後払い SP Code.",- "label": "SP Code",- },- TERMINAL_ID: {- "type": ConfigurationTypeField.SECRET,- "help_text": "Provide NP後払い Terminal ID.",- "label": "Terminal ID",- },- USE_SANDBOX: {- "type": ConfigurationTypeField.BOOLEAN,- "help_text": "Determines if Saleor should use NP後払い sandbox API.",- "label": "Use sandbox",- },- FILL_MISSING_ADDRESS: {- "type": ConfigurationTypeField.BOOLEAN,- "help_text": (- "Determines if Saleor should generate missing "- "AddressData.city and AddressData.city_area"- ),- "label": "Fill missing address",- },- SHIPPING_COMPANY: {- "type": ConfigurationTypeField.STRING,- "help_text": "Determines shipping company used in fulfillment report.",- "label": "Shipping company",- },- SKU_AS_NAME: {- "type": ConfigurationTypeField.BOOLEAN,- "help_text": (- "Determines whether product sku or variant name will be used in NP."- ),- "label": "Product SKU as name",- },- }-- def __init__(self, *args, **kwargs):- super().__init__(*args, **kwargs)- configuration = {item["name"]: item["value"] for item in self.configuration}- self.config = GatewayConfig(- gateway_name=GATEWAY_NAME,- auto_capture=False,- supported_currencies=self.SUPPORTED_CURRENCIES,- connection_params={- MERCHANT_CODE: configuration[MERCHANT_CODE],- SP_CODE: configuration[SP_CODE],- TERMINAL_ID: configuration[TERMINAL_ID],- USE_SANDBOX: configuration[USE_SANDBOX],- FILL_MISSING_ADDRESS: configuration[FILL_MISSING_ADDRESS],- SHIPPING_COMPANY: configuration[SHIPPING_COMPANY],- SKU_AS_NAME: configuration[SKU_AS_NAME],- },- )-- def _get_gateway_config(self) -> GatewayConfig:- return self.config-- def capture_payment(- self, payment_information: "PaymentData", previous_value- ) -> "GatewayResponse":- 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,- get_api_config(self._get_gateway_config().connection_params),- )-- def void_payment(- self, payment_information: "PaymentData", previous_value- ) -> "GatewayResponse":- 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,- get_api_config(self._get_gateway_config().connection_params),- )-- def tracking_number_updated(self, fulfillment: "Fulfillment", previous_value):- tracking_number_updated(- fulfillment, get_api_config(self._get_gateway_config().connection_params)- )-- def get_supported_currencies(self, previous_value):- return self.SUPPORTED_CURRENCIES-- def token_is_required_as_payment_input(self, previous_value):- return False-- @classmethod- def validate_authentication(cls, plugin_configuration: "PluginConfiguration"):- configuration = plugin_configuration.configuration- conf = {data["name"]: data["value"] for data in configuration}- with np_atobarai_otel_trace("np-atobarai.utilities.ping"):- response = health_check(get_api_config(conf))-- if not response:- raise ValidationError(- {- field: ValidationError(- "Authentication failed. Please check provided data.",- code=PluginErrorCode.PLUGIN_MISCONFIGURED.value,- )- for field in [MERCHANT_CODE, SP_CODE, TERMINAL_ID]- }- )-- @classmethod- def validate_plugin_configuration(- cls, plugin_configuration: "PluginConfiguration", **kwargs- ):- """Validate if provided configuration is correct."""- if not plugin_configuration.active:- return-- configuration = plugin_configuration.configuration- configuration = {item["name"]: item["value"] for item in configuration}- missing_fields = [- field for field in REQUIRED_FIELDS if not configuration[field]- ]-- if missing_fields:- raise ValidationError(- {- field: ValidationError(- "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(- "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/__init__.py b/saleor/payment/gateways/np_atobarai/tests/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/saleor/payment/gateways/np_atobarai/tests/conftest.py b/saleor/payment/gateways/np_atobarai/tests/conftest.pydeleted file mode 100644index 6caf126f51..0000000000--- a/saleor/payment/gateways/np_atobarai/tests/conftest.py+++ /dev/null@@ -1,173 +0,0 @@-import dataclasses-from decimal import Decimal-from unittest.mock import patch--import pytest--from .....order.actions import create_refund_fulfillment-from .....order.tests.fixtures import recalculate_order-from .....plugins.manager import get_plugins_manager-from .....plugins.models import PluginConfiguration-from ....interface import AddressData, PaymentLineData, PaymentLinesData-from ..api_types import get_api_config-from ..const import (- FILL_MISSING_ADDRESS,- MERCHANT_CODE,- SHIPPING_COMPANY,- SKU_AS_NAME,- SP_CODE,- TERMINAL_ID,- USE_SANDBOX,-)-from ..plugin import NPAtobaraiGatewayPlugin---def np_atobarai_plugin(settings, monkeypatch, channel_USD):- def fun(- merchant_code="merchant-code",- sp_code="sp-code",- terminal_id="terminal-id",- use_sandbox=True,- fill_missing_address=True,- shipping_company="50000",- sku_as_name=False,- active=True,- ):- settings.PLUGINS = [- "saleor.payment.gateways.np_atobarai.plugin.NPAtobaraiGatewayPlugin"- ]-- configuration = [- {"name": MERCHANT_CODE, "value": merchant_code},- {"name": SP_CODE, "value": sp_code},- {"name": TERMINAL_ID, "value": terminal_id},- {"name": USE_SANDBOX, "value": use_sandbox},- {"name": FILL_MISSING_ADDRESS, "value": fill_missing_address},- {"name": SHIPPING_COMPANY, "value": shipping_company},- {"name": SKU_AS_NAME, "value": sku_as_name},- ]- PluginConfiguration.objects.create(- identifier=NPAtobaraiGatewayPlugin.PLUGIN_ID,- name=NPAtobaraiGatewayPlugin.PLUGIN_NAME,- description="",- active=active,- channel=channel_USD,- configuration=configuration,- )-- manager = get_plugins_manager(allow_replica=False)- manager.get_all_plugins()- return manager.plugins_per_channel[channel_USD.slug][0]-- return fun---def payment_lines_data(order_with_lines):- return PaymentLinesData(- lines=[- PaymentLineData(- amount=line.unit_price_gross_amount,- product_name=f"{line.product_name} {line.variant_name}",- product_sku=line.product_sku,- variant_id=line.variant_id,- quantity=line.quantity,- )- for line in order_with_lines.lines.all()- ],- shipping_amount=order_with_lines.shipping_price_gross_amount,- voucher_amount=(- order_with_lines.total_gross_amount- - order_with_lines.undiscounted_total_gross_amount- ),- )---def np_address_data():- return AddressData(- first_name="John",- last_name="Doe",- company_name="",- phone="+81 03-1234-5678",- country="JP",- postal_code="370-2625",- country_area="群馬県",- city="甘楽郡下仁田町",- city_area="本宿",- street_address_1="2-16-3",- street_address_2="",- metadata={},- private_metadata={},- )---def np_payment_data(np_address_data, dummy_payment_data, payment_lines_data):- return dataclasses.replace(- dummy_payment_data,- billing=np_address_data,- shipping=np_address_data,- amount=Decimal("0.00"),- _resolve_lines_data=lambda: payment_lines_data,- )---def config(np_atobarai_plugin):- return get_api_config(np_atobarai_plugin().config.connection_params)---def payment_dummy(payment_dummy, order_with_lines):- payment_dummy.captured_amount = order_with_lines.total_gross_amount- payment_dummy.save(update_fields=["captured_amount"])- return payment_dummy---def order_with_lines(order_with_lines):- order_with_lines.shipping_price_net_amount = Decimal("5.55")- order_with_lines.shipping_price_gross_amount = Decimal("5.55") * Decimal("1.34")- order_with_lines.shipping_tax_rate = Decimal("1.34")-- order_with_lines.save()-- recalculate_order(order_with_lines)-- return order_with_lines---def order_lines(order_with_lines):- return list(order_with_lines.lines.all())---def create_refund(payment_dummy):- def factory(- order,- order_lines=None,- fulfillment_lines=None,- manual_refund_amount=None,- refund_shipping_costs=False,- ):- def mocked_refund(payment, manager, channel_slug, amount, refund_data):- payment.captured_amount -= amount- payment.save(update_fields=["captured_amount"])-- with patch("saleor.payment.gateway.refund", side_effect=mocked_refund):- return create_refund_fulfillment(- user=None,- app=None,- order=order,- payment=payment_dummy,- order_lines_to_refund=order_lines or [],- fulfillment_lines_to_refund=fulfillment_lines or [],- manager=get_plugins_manager(allow_replica=False),- amount=manual_refund_amount,- refund_shipping_costs=refund_shipping_costs,- )-- return factorydiff --git a/saleor/payment/gateways/np_atobarai/tests/test_api.py b/saleor/payment/gateways/np_atobarai/tests/test_api.pydeleted file mode 100644index 96d708e930..0000000000--- a/saleor/payment/gateways/np_atobarai/tests/test_api.py+++ /dev/null@@ -1,867 +0,0 @@-import logging-from decimal import Decimal-from unittest.mock import ANY, Mock, patch--import pytest-import requests-from graphene import Node-from requests_hardened import HTTPSession--from .... import PaymentError-from .. import PaymentStatus, api, const-from ..api_helpers import format_price, get_goods_with_refunds-from ..api_types import NPResponse, PaymentResult-from ..errors import (- NO_PSP_REFERENCE,- NO_TRACKING_NUMBER,- NP_CONNECTION_ERROR,- SHIPPING_COMPANY_CODE_INVALID,-)-from ..plugin import NPAtobaraiGatewayPlugin--[email protected](HTTPSession, "request")-def test_refund_payment(- mocked_request, np_atobarai_plugin, np_payment_data, payment_dummy-):- # given- plugin = np_atobarai_plugin()- payment_data = np_payment_data- payment_data.amount = payment_dummy.captured_amount- psp_reference = "18121200001"- payment_data.psp_reference = psp_reference- response_value = {"results": [{"np_transaction_id": psp_reference}]}- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response-- # when- gateway_response = plugin.refund_payment(payment_data, None)-- # then- assert gateway_response.is_success- assert gateway_response.raw_response == response_value---def test_refund_payment_no_order(np_atobarai_plugin, np_payment_data, payment_dummy):- # given- plugin = np_atobarai_plugin()- payment_data = np_payment_data- payment_dummy.captured_amount = payment_data.amount + Decimal("3.00")- payment_dummy.order = None- payment_dummy.save(update_fields=["order", "captured_amount"])-- # then- with pytest.raises(PaymentError):- # when- plugin.refund_payment(payment_data, None)---@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")-def test_refund_payment_no_psp_reference_payment_not_created(- mocked_request, np_atobarai_plugin, np_payment_data, payment_dummy-):- # given- plugin = np_atobarai_plugin()- payment_data = np_payment_data- payment_data.amount = payment_dummy.captured_amount- response_value = {"results": [{"np_transaction_id": "18121200001"}]}- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response-- # when- gateway_response = plugin.refund_payment(payment_data, None)-- # then- assert not gateway_response.is_success- assert not gateway_response.raw_response--[email protected](HTTPSession, "request")-def test_refund_payment_np_errors(- mocked_request, np_atobarai_plugin, np_payment_data, payment_dummy-):- # given- 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"])- response = Mock(- spec=requests.Response,- status_code=400,- json=Mock(return_value={"errors": [{"codes": ["E0100002", "E0100003"]}]}),- )- mocked_request.return_value = response-- # when- gateway_response = plugin.refund_payment(payment_data, None)-- # then- assert not gateway_response.is_success- assert gateway_response.error---@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")-def test_refund_payment_no_payment(- _mocked_request, np_atobarai_plugin, np_payment_data, payment_dummy-):- # given- payment_id = -1- plugin = np_atobarai_plugin()- payment_data = np_payment_data- payment_data.payment_id = payment_id-- # when- with pytest.raises(PaymentError) as excinfo:- plugin.refund_payment(payment_data, None)-- # then- assert excinfo.value.message == f"Payment with id {payment_id} does not exist."--[email protected](HTTPSession, "request")-def test_refund_payment_partial_refund_change_transaction(- mocked_request, np_atobarai_plugin, np_payment_data, payment_dummy-):- # given- plugin = np_atobarai_plugin()- payment_data = np_payment_data- payment_dummy.captured_amount = payment_data.amount + Decimal("3.00")- psp_reference = "psp_reference"- payment_dummy.psp_reference = psp_reference- payment_dummy.save(update_fields=["captured_amount", "psp_reference"])- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(- return_value={- "results": [- {- "np_transaction_id": psp_reference,- "authori_result": "00",- }- ]- }- ),- )- mocked_request.return_value = response-- # when- gateway_response = plugin.refund_payment(payment_data, None)-- # then- assert gateway_response.is_success---@patch("saleor.payment.gateways.np_atobarai.api.change_transaction")[email protected](HTTPSession, "request")-def test_refund_payment_partial_refund_reregister_transaction(- mocked_request,- mocked_change_transaction,- np_atobarai_plugin,- np_payment_data,- payment_dummy,- fulfillment,-):- # given- fulfillment.tracking_number = "123123"- fulfillment.save(update_fields=["tracking_number"])- plugin = np_atobarai_plugin()- payment_data = np_payment_data- payment_dummy.captured_amount = payment_data.amount + Decimal("3.00")- psp_reference = "psp_reference"- payment_dummy.psp_reference = psp_reference- payment_dummy.save(update_fields=["captured_amount", "psp_reference"])- mocked_change_transaction.return_value = PaymentResult(- status=PaymentStatus.FOR_REREGISTRATION- )- new_psp_reference = "new_psp_reference"- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(- return_value={- "results": [- {- "base_np_transaction_id": payment_dummy.psp_reference,- "np_transaction_id": new_psp_reference,- }- ]- }- ),- )- mocked_request.return_value = response-- # when- gateway_response = plugin.refund_payment(payment_data, None)-- # then- assert gateway_response.is_success- assert gateway_response.psp_reference == new_psp_reference--[email protected](HTTPSession, "request")-def test_report_fulfillment(mocked_request, config, fulfillment, payment_dummy):- # given- psp_reference = "18121200001"- payment_dummy.psp_reference = psp_reference- payment_dummy.save(update_fields=["psp_reference"])- response_value = {"results": [{"np_transaction_id": psp_reference}]}- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response-- # when- errors, already_captured = api.report_fulfillment(- config, payment_dummy, fulfillment- )-- # then- assert not errors- assert not already_captured---@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")-def test_report_fulfillment_invalid_shipping_company_code(- mocked_request, config, fulfillment, payment_dummy-):- # given- psp_reference = "18121200001"- payment_dummy.psp_reference = psp_reference- payment_dummy.save(update_fields=["psp_reference"])- response_value = {"results": [{"np_transaction_id": psp_reference}]}- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response- fulfillment.store_value_in_private_metadata(- {const.SHIPPING_COMPANY_CODE_METADATA_KEY: "invalid_shipping_company_code"}- )-- # when- errors, already_captured = api.report_fulfillment(- config, payment_dummy, fulfillment- )-- # then- assert not already_captured- assert errors == [f"FR#{SHIPPING_COMPANY_CODE_INVALID}"]---@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")-def test_report_fulfillment_no_psp_reference(- _mocked_request, config, fulfillment, payment_dummy-):- # when- errors, already_captured = api.report_fulfillment(- config, payment_dummy, fulfillment- )-- # then- assert not already_captured- assert errors == [f"FR#{NO_PSP_REFERENCE}"]---@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")-def test_report_fulfillment_no_tracking_number(- _mocked_request, config, fulfillment, payment_dummy-):- # given- psp_reference = "18121200001"- payment_dummy.psp_reference = psp_reference- payment_dummy.save(update_fields=["psp_reference"])- fulfillment.tracking_number = ""-- # when- errors, already_captured = api.report_fulfillment(- config, payment_dummy, fulfillment- )-- # then- assert not already_captured- assert errors == [f"FR#{NO_TRACKING_NUMBER}"]--[email protected](HTTPSession, "request")-def test_report_fulfillment_np_errors(- mocked_request, config, fulfillment, payment_dummy-):- # given- psp_reference = "18121200001"- payment_dummy.psp_reference = psp_reference- payment_dummy.save(update_fields=["psp_reference"])- error_codes = ["EPRO0101", "EPRO0102"]- response_value = {"errors": [{"codes": error_codes}]}- response = Mock(- spec=requests.Response,- status_code=400,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response-- # when- errors, already_captured = api.report_fulfillment(- config, payment_dummy, fulfillment- )-- # then- assert not already_captured- assert errors == [f"FR#{code}" for code in error_codes]--[email protected](HTTPSession, "request")-def test_report_fulfillment_connection_errors(- mocked_request, config, fulfillment, payment_dummy, caplog-):- # given- psp_reference = "18121200001"- payment_dummy.psp_reference = psp_reference- payment_dummy.save(update_fields=["psp_reference"])- response = Mock(- request=Mock(),- spec=requests.Response,- status_code=404,- )- mocked_request.return_value = response-- # when- errors, already_captured = api.report_fulfillment(- config, payment_dummy, fulfillment- )-- # then- assert not already_captured- assert errors == [f"FR#{NP_CONNECTION_ERROR}"]- assert caplog.record_tuples == [- (ANY, logging.WARNING, "Cannot connect to NP Atobarai.")- ]--[email protected](HTTPSession, "request")-def test_report_fulfillment_already_captured(- mocked_request, config, fulfillment, payment_dummy-):- # given- payment_dummy.psp_reference = "123123123"- response_value = {"errors": [{"codes": ["E0100115"]}]}- response = Mock(- spec=requests.Response,- status_code=400,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response-- # when- _, already_captured = api.report_fulfillment(config, payment_dummy, fulfillment)-- # then- assert already_captured---def payment_np(payment_dummy):- payment_dummy.gateway = NPAtobaraiGatewayPlugin.PLUGIN_ID- payment_dummy.save(update_fields=["gateway"])- return payment_dummy---@patch("saleor.payment.gateways.np_atobarai.notify_dashboard")-@patch("saleor.payment.gateways.np_atobarai.api.report_fulfillment")-def test_tracking_number_updated(- mocked_report_fulfillment,- mocked_notify_dashboard,- np_atobarai_plugin,- payment_np,- fulfillment,- caplog,-):- # given- plugin = np_atobarai_plugin()- result = ([], False)- mocked_report_fulfillment.return_value = result- order = fulfillment.order- order.payments.add(payment_np)-- # when- 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, f"Payment with id {payment_graphql_id} was captured"- )- assert not caplog.record_tuples---@patch("saleor.payment.gateways.np_atobarai.notify_dashboard")-@patch("saleor.payment.gateways.np_atobarai.api.report_fulfillment")-def test_tracking_number_updated_errors(- mocked_report_fulfillment,- mocked_notify_dashboard,- np_atobarai_plugin,- payment_np,- fulfillment,- caplog,-):- # given- errors = ["error1", "error2"]- plugin = np_atobarai_plugin()- result = (errors, False)- mocked_report_fulfillment.return_value = result- order = fulfillment.order- order.payments.add(payment_np)-- # when- plugin.tracking_number_updated(fulfillment, None)-- # then- 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 with id {payment_graphql_id} "- f"in NP Atobarai: {error}"- )---@patch("saleor.payment.gateways.np_atobarai.notify_dashboard")-@patch("saleor.payment.gateways.np_atobarai.api.report_fulfillment")-def test_tracking_number_updated_already_captured(- mocked_report_fulfillment,- mocked_notify_dashboard,- np_atobarai_plugin,- payment_np,- fulfillment,- caplog,-):- # given- plugin = np_atobarai_plugin()- result = ([], True)- mocked_report_fulfillment.return_value = result- order = fulfillment.order- order.payments.add(payment_np)-- # when- 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,- 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- == f"Payment with id {payment_graphql_id} was already captured"- )---@patch("saleor.payment.gateways.np_atobarai.notify_dashboard")-@patch("saleor.payment.gateways.np_atobarai.api.report_fulfillment")-def test_tracking_number_updated_no_payments(- _mocked_report_fulfillment,- mocked_notify_dashboard,- np_atobarai_plugin,- fulfillment,- caplog,-):- # given- plugin = np_atobarai_plugin()- order = fulfillment.order-- # when- plugin.tracking_number_updated(fulfillment, None)-- # then- 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 == "No active payments for this order"--[email protected](HTTPSession, "request")-def test_change_transaction_success(- mocked_request, config, payment_dummy, np_payment_data-):- # given- response_value = {- "results": [- {- "authori_result": "00",- "np_transaction_id": payment_dummy.psp_reference,- }- ]- }- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response-- # when- payment_response = api.change_transaction(- config, payment_dummy, np_payment_data, Mock(), Decimal("12.34")- )-- # then- assert payment_response.status == PaymentStatus.SUCCESS- assert payment_response.raw_response == response_value- assert payment_response.raw_response == response_value---@patch("saleor.payment.gateways.np_atobarai.api.cancel")[email protected](HTTPSession, "request")-def test_change_transaction_pending(- mocked_request, mocked_cancel, config, payment_dummy, np_payment_data-):- # given- transaction_id = "123"- response_value = {- "results": [- {- "authori_result": "10",- "np_transaction_id": transaction_id,- "authori_hold": [- "RE009",- "REE021",- ],- }- ]- }- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response-- # when- payment_response = api.change_transaction(- config, payment_dummy, np_payment_data, Mock(), Decimal("12.34")- )-- # then- mocked_cancel.assert_called_once_with(config, transaction_id)- assert payment_response.status == PaymentStatus.FAILED- assert payment_response.raw_response == response_value--[email protected](HTTPSession, "request")-def test_change_transaction_post_fulfillment(- mocked_request, config, payment_dummy, np_payment_data-):- # given- response_value = {"errors": [{"codes": ["E0100115"]}]}- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response-- # when- payment_response = api.change_transaction(- config, payment_dummy, np_payment_data, Mock(), Decimal("12.34")- )-- # then- assert payment_response.status == PaymentStatus.FOR_REREGISTRATION- assert payment_response.raw_response == response_value--[email protected](HTTPSession, "request")-def test_change_transaction_failed(- mocked_request, config, payment_dummy, np_payment_data-):- # given- response_value = {"errors": [{"codes": ["E0100050"]}]}- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(return_value=response_value),- )- mocked_request.return_value = response-- # when- payment_response = api.change_transaction(- config, payment_dummy, np_payment_data, Mock(), Decimal("12.34")- )-- # then- assert payment_response.status == PaymentStatus.FAILED- assert payment_response.errors- assert payment_response.raw_response == response_value---@patch("saleor.payment.gateways.np_atobarai.api.report")-@patch("saleor.payment.gateways.np_atobarai.api.register")-@patch("saleor.payment.gateways.np_atobarai.api.cancel")-def test_reregister_transaction_success(- mocked_cancel,- mocked_register,- mocked_report,- config,- payment_dummy,- np_payment_data,-):- # given- tracking_number = "123"- shipping_company_code = "50000"- payment_dummy.psp_reference = "123"- new_psp_reference = "234"- mocked_cancel.return_value = NPResponse(result={}, error_codes=[], raw_response={})- transaction_id = "18121200001"- register_response_value = {- "results": [- {- "shop_transaction_id": "abc1234567890",- "np_transaction_id": transaction_id,- "authori_result": "00",- "authori_required_date": "2018-12-12T12:00:00+09:00",- }- ]- }- mocked_register.return_value = NPResponse(- result={- "np_transaction_id": new_psp_reference,- },- error_codes=[],- raw_response=register_response_value,- )- report_response_value = {"results": [{"np_transaction_id": transaction_id}]}- mocked_report.return_value = NPResponse(- result={}, error_codes=[], raw_response=report_response_value- )-- # when- goods, billed_amount = get_goods_with_refunds(- config, payment_dummy, np_payment_data- )- payment_response = api.reregister_transaction_for_partial_return(- config,- payment_dummy,- np_payment_data,- shipping_company_code,- tracking_number,- goods,- billed_amount,- )-- # then- mocked_cancel.assert_called_once_with(config, payment_dummy.psp_reference)- mocked_register.assert_called_once_with(- config,- np_payment_data,- int(format_price(billed_amount, np_payment_data.currency)),- goods,- )- mocked_report.assert_called_once_with(- config, shipping_company_code, new_psp_reference, tracking_number- )- assert payment_response.status == PaymentStatus.SUCCESS- assert payment_response.psp_reference == new_psp_reference- assert payment_response.raw_response == report_response_value---def test_reregister_transaction_no_psp_reference(payment_dummy, np_payment_data):- # when- payment_response = api.reregister_transaction_for_partial_return(- Mock(),- payment_dummy,- np_payment_data,- Mock(),- Mock(),- Mock(),- Decimal("12.34"),- )-- # then- assert payment_response.status == PaymentStatus.FAILED- assert payment_response.errors == [f"TR#{NO_PSP_REFERENCE}"]---@patch("saleor.payment.gateways.np_atobarai.api.cancel")-def test_reregister_transaction_cancel_error(- mocked_cancel, config, payment_dummy, np_payment_data-):- # given- payment_dummy.psp_reference = "123"- error_codes = ["1", "2", "3"]- mocked_cancel.return_value = NPResponse(- result={}, error_codes=error_codes, raw_response={}- )-- # when- payment_response = api.reregister_transaction_for_partial_return(- config, payment_dummy, np_payment_data, Mock(), Mock(), Mock(), Decimal("12.34")- )-- # then- assert payment_response.status == PaymentStatus.FAILED- assert payment_response.errors == [f"TC#{code}" for code in error_codes]---@patch("saleor.payment.gateways.np_atobarai.api.report")-@patch("saleor.payment.gateways.np_atobarai.api.register")-@patch("saleor.payment.gateways.np_atobarai.api.cancel")-def test_reregister_transaction_report_error(- mocked_cancel,- mocked_register,- mocked_report,- config,- payment_dummy,- np_payment_data,-):- # given- tracking_number = "123"- shipping_company_code = "50000"- payment_dummy.psp_reference = "123"- new_psp_reference = "234"- error_codes = ["1", "2", "3"]- mocked_cancel.return_value = NPResponse(result={}, error_codes=[], raw_response={})- mocked_register.return_value = NPResponse(- result={- "np_transaction_id": new_psp_reference,- },- error_codes=[],- raw_response={},- )- mocked_report.return_value = NPResponse(- result={}, error_codes=error_codes, raw_response={}- )-- # when- payment_response = api.reregister_transaction_for_partial_return(- config,- payment_dummy,- np_payment_data,- shipping_company_code,- tracking_number,- Mock(),- Decimal("12.34"),- )-- # then- assert payment_response.status == PaymentStatus.FAILED- assert payment_response.errors == [f"FR#{code}" for code in error_codes]---@patch("saleor.payment.gateways.np_atobarai.api.register")-@patch("saleor.payment.gateways.np_atobarai.api.cancel")-def test_reregister_transaction_general_error(- mocked_cancel,- mocked_register,- config,- payment_dummy,- np_payment_data,-):- # given- payment_dummy.psp_reference = "123"- mocked_cancel.return_value = NPResponse(result={}, error_codes=[], raw_response={})- error_codes = ["1", "2", "3"]- mocked_register.return_value = NPResponse(- result={}, error_codes=error_codes, raw_response={}- )-- # when- payment_response = api.reregister_transaction_for_partial_return(- config, payment_dummy, np_payment_data, Mock(), Mock(), Mock(), Decimal("12.34")- )-- # then- assert payment_response.status == PaymentStatus.FAILED- assert payment_response.errors == [f"TR#{code}" for code in error_codes]---@patch("saleor.payment.gateways.np_atobarai.api.cancel")-@patch("saleor.payment.gateways.np_atobarai.api.register")-def test_register_transaction_pending(- mocked_register, mocked_cancel, config, np_payment_data-):- # 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=[], raw_response={}- )- mocked_cancel.return_value = NPResponse(result={}, error_codes=[], raw_response={})-- # when- payment_response = api.register_transaction(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]---@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, 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=[], raw_response=register_result- )- cancel_errors = ["1", "2", "3"]- mocked_cancel.return_value = NPResponse(- result={}, error_codes=cancel_errors, raw_response={}- )-- # when- payment_response = api.register_transaction(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)]- assert payment_response.raw_response == register_result---def test_cancel_transaction_no_payment(np_payment_data):- # given- np_payment_data.psp_reference = ""-- # when- payment_response = api.cancel_transaction(Mock(), np_payment_data)-- # then- assert payment_response.errors == [f"TC#{NO_PSP_REFERENCE}"]diff --git a/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py b/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.pydeleted file mode 100644index 2bbd33acc8..0000000000--- a/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py+++ /dev/null@@ -1,389 +0,0 @@-from dataclasses import fields-from decimal import Decimal-from unittest.mock import DEFAULT, Mock, patch, sentinel--import pytest-from posuto import Posuto--from .....order.fetch import OrderLineInfo-from ....interface import AddressData, RefundData-from ....utils import price_to_minor_unit-from .. import api_helpers, errors-from ..api_helpers import get_goods, get_goods_with_refunds---def test_register_no_billing_address(config, np_payment_data):- # given- np_payment_data.billing = None-- # when- np_response = api_helpers.register(config, np_payment_data)-- # then- assert not np_response.result- assert np_response.error_codes == [f"{errors.NO_BILLING_ADDRESS}"]---def test_register_no_shipping_address(config, np_payment_data):- # given- np_payment_data.shipping = None-- # when- np_response = api_helpers.register(config, np_payment_data)-- # then- assert not np_response.result- assert np_response.error_codes == [f"{errors.NO_SHIPPING_ADDRESS}"]---INVALID = sentinel.INVALID---def format_address_side_effect(config, address):- return None if address is INVALID else DEFAULT---@patch(- "saleor.payment.gateways.np_atobarai.api_helpers.format_address",- new=Mock(side_effect=format_address_side_effect),-)-@patch("saleor.payment.gateways.np_atobarai.api_helpers._request", new=Mock())-def test_register_invalid_billing_address(config, np_payment_data):- # given- np_payment_data.billing = INVALID-- # when- np_response = api_helpers.register(config, np_payment_data)-- # then- assert not np_response.result- assert np_response.error_codes == [f"{errors.BILLING_ADDRESS_INVALID}"]---@patch(- "saleor.payment.gateways.np_atobarai.api_helpers.format_address",- new=Mock(side_effect=format_address_side_effect),-)-@patch("saleor.payment.gateways.np_atobarai.api_helpers._request", new=Mock())-def test_register_invalid_shipping_address(config, np_payment_data):- # given- np_payment_data.shipping = INVALID-- # when- np_response = api_helpers.register(config, np_payment_data)-- # then- assert not np_response.result- assert np_response.error_codes == [f"{errors.SHIPPING_ADDRESS_INVALID}"]---def test_format_name(np_address_data):- # given- double_byte_space = "\u3000"-- # when- formatted_name = api_helpers.format_name(np_address_data)-- # then- assert formatted_name == (- f"{np_address_data.last_name}{double_byte_space}{np_address_data.first_name}"- )---def test_format_address_do_not_fill(config, np_address_data):- # given- config.fill_missing_address = False-- # when- formatted_address = api_helpers.format_address(config, np_address_data)-- # then- assert formatted_address == (- f"{np_address_data.country_area}"- f"{np_address_data.street_address_1}"- f"{np_address_data.street_address_2}"- )---def test_format_address_fill(config, np_address_data):- # when- formatted_address = api_helpers.format_address(config, np_address_data)-- # then- pp = Posuto()- japanese_address = pp.get(np_address_data.postal_code)- assert formatted_address == (- f"{np_address_data.country_area}"- f"{japanese_address.city}"- f"{japanese_address.neighborhood}"- f"{np_address_data.street_address_1}"- f"{np_address_data.street_address_2}"- )---def test_format_address_fill_invalid_postal_code(config, np_address_data):- # given- np_address_data.postal_code = ""-- # when- formatted_address = api_helpers.format_address(config, np_address_data)-- # then- assert formatted_address is None---def test_format_address_proper_formatting(config):- # given- config.fill_missing_address = False- address_data = AddressData(**{f.name: f.name for f in fields(AddressData)})-- # when- formatted_address = api_helpers.format_address(config, address_data)-- # then- assert formatted_address == (- f"{address_data.country_area}"- f"{address_data.street_address_1}"- f"{address_data.street_address_2}"- )--[email protected]("sku_as_name", [True, False])-def test_get_goods(- config,- np_payment_data,- sku_as_name,-):- # given- config.sku_as_name = sku_as_name-- # when- goods = get_goods(config, np_payment_data)-- # then- assert goods == [- {- "goods_name": line.product_sku if sku_as_name else line.product_name,- "goods_price": int(- price_to_minor_unit(line.amount, np_payment_data.currency)- ),- "quantity": line.quantity,- }- for line in np_payment_data.lines_data.lines- ] + [- {- "goods_name": "Shipping",- "goods_price": int(- price_to_minor_unit(- np_payment_data.lines_data.shipping_amount, np_payment_data.currency- )- ),- "quantity": 1,- },- ]--- ("refund_amount", "discount_goods"),- [- (Decimal("0.00"), []),- (- Decimal("5.00"),- [{"goods_name": "Discount", "goods_price": -500, "quantity": 1}],- ),- ],-)[email protected]("sku_as_name", [True, False])-def test_get_goods_with_refunds(- config,- payment_dummy,- np_payment_data,- sku_as_name,- refund_amount,- discount_goods,-):- # given- config.sku_as_name = sku_as_name- np_payment_data.amount = refund_amount- np_payment_data.refund_data = RefundData(- refund_amount_is_automatically_calculated=False- )-- # when- goods, billed_amount = get_goods_with_refunds(- config, payment_dummy, np_payment_data- )-- # then- assert (- goods- == [- {- "goods_name": line.product_sku if sku_as_name else line.product_name,- "goods_price": int(- price_to_minor_unit(line.amount, np_payment_data.currency)- ),- "quantity": line.quantity,- }- for line in np_payment_data.lines_data.lines- ]- + [- {- "goods_name": "Shipping",- "goods_price": int(- price_to_minor_unit(- np_payment_data.lines_data.shipping_amount,- np_payment_data.currency,- )- ),- "quantity": 1,- },- ]- + discount_goods- )- manual_refund_amount = refund_amount or Decimal("0.00")- assert (- billed_amount- == sum(line.amount * line.quantity for line in np_payment_data.lines_data.lines)- + np_payment_data.lines_data.voucher_amount- + np_payment_data.lines_data.shipping_amount- - manual_refund_amount- )---def order_lines(order_with_lines):- return list(order_with_lines.lines.all())---def test_get_goods_with_refunds_manual_product_refund_product_refund(- create_refund, order_with_lines, config, np_payment_data, payment_dummy, order_lines-):- # given- line_to_refund = order_lines[0]-- create_refund(- order_with_lines,- order_lines=[- OrderLineInfo(- line=line_to_refund, quantity=1, variant=line_to_refund.variant- )- ],- manual_refund_amount=Decimal("3.00"),- )-- # when- np_payment_data.refund_data = RefundData(- order_lines_to_refund=[- OrderLineInfo(- line=line_to_refund, quantity=1, variant=line_to_refund.variant- ),- ]- )- np_payment_data.amount = line_to_refund.unit_price_gross_amount- goods, billed_amount = get_goods_with_refunds(- config, payment_dummy, np_payment_data- )-- # then- expected_billed_amount = order_with_lines.total_gross_amount - (- Decimal("3.00") + line_to_refund.unit_price_gross_amount- )- assert billed_amount == expected_billed_amount- assert goods[0]["quantity"] == line_to_refund.quantity - 1- for goods_line, order_line in zip(goods[1:], order_lines[1:], strict=False):- assert goods_line["quantity"] == order_line.quantity---def test_get_goods_with_refunds_product_refund_shipping_refund(- create_refund, order_with_lines, config, np_payment_data, payment_dummy, order_lines-):- # given- line_to_refund = order_lines[0]-- create_refund(- order_with_lines,- order_lines=[- OrderLineInfo(- line=line_to_refund, quantity=1, variant=line_to_refund.variant- )- ],- )-- # when- np_payment_data.refund_data = RefundData(refund_shipping_costs=True)- np_payment_data.amount = order_with_lines.shipping_price_gross_amount- goods, billed_amount = get_goods_with_refunds(- config, payment_dummy, np_payment_data- )-- # then- expected_billed_amount = order_with_lines.total_gross_amount - (- line_to_refund.unit_price_gross_amount- + order_with_lines.shipping_price_gross_amount- )- assert billed_amount == expected_billed_amount- assert goods[0]["quantity"] == line_to_refund.quantity - 1- for goods_line, order_line in zip(goods[1:], order_lines[1:], strict=False):- assert goods_line["quantity"] == order_line.quantity---def test_get_goods_with_refunds_manual_shipping_misc_refund(- create_refund, order_with_lines, config, np_payment_data, payment_dummy, order_lines-):- # given- create_refund(- order_with_lines,- refund_shipping_costs=True,- manual_refund_amount=Decimal("5.30"),- )-- # when- np_payment_data.refund_data = RefundData(refund_shipping_costs=True)- np_payment_data.amount = Decimal("4.30")- goods, billed_amount = get_goods_with_refunds(- config, payment_dummy, np_payment_data- )-- # then- expected_billed_amount = order_with_lines.total_gross_amount - (- Decimal("5.30") + Decimal("4.30")- )- assert billed_amount == expected_billed_amount- for goods_line, order_line in zip(goods, order_lines, strict=False):- assert goods_line["quantity"] == order_line.quantity---def test_get_goods_with_refunds_shipping_refund_manual_product_refund(- create_refund, order_with_lines, config, np_payment_data, payment_dummy, order_lines-):- # given- create_refund(- order_with_lines,- refund_shipping_costs=True,- )-- # when- line_to_refund = order_lines[0]- np_payment_data.refund_data = RefundData(- order_lines_to_refund=[- OrderLineInfo(- line=line_to_refund,- quantity=1,- variant=line_to_refund.variant,- )- ],- refund_amount_is_automatically_calculated=False,- )- np_payment_data.amount = Decimal("8.20")- goods, billed_amount = get_goods_with_refunds(- config, payment_dummy, np_payment_data- )-- # then- expected_billed_amount = order_with_lines.total_gross_amount - (- order_with_lines.shipping_price_gross_amount + Decimal("8.20")- )- assert billed_amount == expected_billed_amount- for goods_line, order_line in zip(goods, order_lines, strict=False):- assert goods_line["quantity"] == order_line.quantitydiff --git a/saleor/payment/gateways/np_atobarai/tests/test_plugin.py b/saleor/payment/gateways/np_atobarai/tests/test_plugin.pydeleted file mode 100644index 7a385c420f..0000000000--- a/saleor/payment/gateways/np_atobarai/tests/test_plugin.py+++ /dev/null@@ -1,112 +0,0 @@-import os-from unittest.mock import Mock, patch--import pytest-import requests-from requests_hardened import HTTPSession--[email protected](HTTPSession, "request")-def test_process_payment_authorized(- mocked_request, np_atobarai_plugin, np_payment_data-):- # given- plugin = np_atobarai_plugin()- payment_data = np_payment_data- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(- return_value={- "results": [- {- "shop_transaction_id": "abc1234567890",- "np_transaction_id": "18121200001",- "authori_result": "00",- "authori_required_date": "2018-12-12T12:00:00+09:00",- }- ]- }- ),- )- mocked_request.return_value = response-- # when- gateway_response = plugin.process_payment(payment_data, None)-- # then- assert gateway_response.is_success- assert not gateway_response.error--[email protected](HTTPSession, "request")-def test_process_payment_refused(mocked_request, np_atobarai_plugin, np_payment_data):- # given- plugin = np_atobarai_plugin()- payment_data = np_payment_data- response = Mock(- spec=requests.Response,- status_code=200,- json=Mock(- return_value={- "results": [- {- "shop_transaction_id": "abc1234567890",- "np_transaction_id": "18121200001",- "authori_result": "20",- "authori_required_date": "2018-12-12T12:00:00+09:00",- }- ]- }- ),- )- mocked_request.return_value = response-- # when- gateway_response = plugin.process_payment(payment_data, None)-- # then- assert not gateway_response.is_success--[email protected](HTTPSession, "request")-def test_process_payment_error(mocked_request, np_atobarai_plugin, np_payment_data):- # given- plugin = np_atobarai_plugin()- payment_data = np_payment_data- error_codes = ["E0100059", "E0100083"]- response = Mock(- spec=requests.Response,- status_code=400,- json=Mock(return_value={"errors": [{"codes": error_codes}]}),- )- mocked_request.return_value = response-- # when- gateway_response = plugin.process_payment(payment_data, None)-- # then- assert not gateway_response.is_success- 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.pydeleted file mode 100644index 85ce47dbc9..0000000000--- a/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py+++ /dev/null@@ -1,82 +0,0 @@-from unittest import mock-from unittest.mock import Mock--import pytest-import requests-from django.core.exceptions import ValidationError-from requests_hardened import HTTPSession--from ..plugin import NPAtobaraiGatewayPlugin--[email protected](HTTPSession, "request")[email protected]("status_code", [200, 400])-def test_validate_plugin_configuration_valid_credentials(- mocked_request, np_atobarai_plugin, status_code-):- # given- plugin = np_atobarai_plugin()- response = Mock(spec=requests.Response, status_code=status_code)- mocked_request.return_value = response- # when- NPAtobaraiGatewayPlugin.validate_plugin_configuration(plugin)- # then: no exception--[email protected](HTTPSession, "request")[email protected]("status_code", [401, 403])-def test_validate_plugin_configuration_invalid_credentials(- mocked_request, np_atobarai_plugin, status_code-):- # given- plugin = np_atobarai_plugin()- response = Mock(spec=requests.Response, status_code=status_code, request=Mock())- mocked_request.return_value = response- # then- with pytest.raises(ValidationError):- # when- NPAtobaraiGatewayPlugin.validate_plugin_configuration(plugin)--[email protected]("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")-def test_validate_plugin_configuration_missing_data(mocked_request, np_atobarai_plugin):- # given- plugin = np_atobarai_plugin(merchant_code=None, sp_code=None, terminal_id=None)- response = Mock(spec=requests.Response, status_code=200)- mocked_request.return_value = response-- # when- with pytest.raises(ValidationError) as excinfo:- NPAtobaraiGatewayPlugin.validate_plugin_configuration(plugin)-- # then- assert len(excinfo.value.error_dict) == 3--[email protected]("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")-def test_validate_plugin_configuration_invalid_shipping_company_code(- mocked_request, np_atobarai_plugin-):- # given- plugin = np_atobarai_plugin(shipping_company="00")- response = Mock(spec=requests.Response, status_code=200)- mocked_request.return_value = response-- # when- with pytest.raises(ValidationError) as excinfo:- NPAtobaraiGatewayPlugin.validate_plugin_configuration(plugin)-- # 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.pydeleted file mode 100644index 3f1d49f5f0..0000000000--- a/saleor/payment/gateways/np_atobarai/tests/test_utils.py+++ /dev/null@@ -1,304 +0,0 @@-from itertools import chain, zip_longest-from unittest.mock import Mock, patch--import pytest--from .....order import FulfillmentLineData, FulfillmentStatus, OrderEvents-from .....order.fetch import OrderLineInfo-from .... import PaymentError-from ....interface import RefundData-from .. import get_fulfillment_for_order, get_shipping_company_code, notify_dashboard-from ..const import SHIPPING_COMPANY_CODE_METADATA_KEY, SHIPPING_COMPANY_CODES-from ..utils import create_refunded_lines---def test_notify_dashboard(order):- # given- message = "message"-- # when- notify_dashboard(order, message)-- # then- event = order.events.first()- assert event.type == OrderEvents.EXTERNAL_SERVICE_NOTIFICATION- assert event.parameters["message"] == message---def test_get_fulfillment_for_order(order):- # given- expected_fulfillment = order.fulfillments.create(tracking_number="123")-- # when- fulfillment = get_fulfillment_for_order(order)-- # then- assert expected_fulfillment == fulfillment---def test_get_fulfillment_for_order_multiple_fulfillments_one_valid(order):- # then- expected_fulfillment = order.fulfillments.create(tracking_number="123")- order.fulfillments.create(tracking_number="234", status=FulfillmentStatus.REFUNDED)-- # when- fulfillment = get_fulfillment_for_order(order)-- # then- assert expected_fulfillment == fulfillment---def test_get_fulfillment_for_order_no_fulfillment(order):- # then- with pytest.raises(PaymentError, match=r".* not exist .*"):- # when- get_fulfillment_for_order(order)---def test_get_fulfillment_for_order_no_fulfillment_with_tracking_number(order):- # given- order.fulfillments.create()-- # then- with pytest.raises(PaymentError, match=r".* not exist .*"):- # when- get_fulfillment_for_order(order)---def test_get_fulfillment_for_order_no_refundable_fulfillment(order):- # given- order.fulfillments.create(tracking_number="123", status=FulfillmentStatus.REFUNDED)-- # then- with pytest.raises(PaymentError, match=r".* not exist .*"):- # when- get_fulfillment_for_order(order)---def test_get_fulfillment_for_order_multiple_fulfillments(order, fulfillment):- # given- order.fulfillments.create(tracking_number="123")- order.fulfillments.create(tracking_number="234")-- # then- with pytest.raises(PaymentError, match=r"More than one .* exist .*"):- # 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],- strict=False,- ),-)-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---def test_create_refunded_lines_order_lines(order_with_lines):- # given- order_lines = order_with_lines.lines.all()- order_refund_lines = [- OrderLineInfo(line=(line := order_lines[0]), quantity=2, variant=line.variant),- OrderLineInfo(line=(line := order_lines[1]), quantity=1, variant=line.variant),- ]- fulfillment_refund_lines = []- refund_data = RefundData(- order_lines_to_refund=order_refund_lines,- fulfillment_lines_to_refund=fulfillment_refund_lines,- )-- # when- lines = create_refunded_lines(- order_with_lines,- refund_data,- )-- # then- assert lines == {line.line.variant_id: line.quantity for line in order_refund_lines}---def test_create_refunded_lines_fulfillment_lines(fulfilled_order):- # given- fulfillment_lines = list(fulfilled_order.fulfillments.first().lines.all())- order_refund_lines = []- fulfillment_refund_lines = [- FulfillmentLineData(- line=fulfillment_lines[0],- quantity=2,- ),- FulfillmentLineData(- line=fulfillment_lines[1],- quantity=1,- ),- ]- refund_data = RefundData(- order_lines_to_refund=order_refund_lines,- fulfillment_lines_to_refund=fulfillment_refund_lines,- )-- # when- lines = create_refunded_lines(- fulfilled_order,- refund_data,- )-- # then- assert lines == {- line.line.order_line.variant_id: line.quantity- for line in fulfillment_refund_lines- }---@patch("saleor.payment.gateway.refund")[email protected]("previous_refund_shipping_costs", [True, False])-def test_create_refunded_lines_previously_refunded_order_lines(- _mocked_refund,- order_with_lines,- create_refund,- previous_refund_shipping_costs,-):- # given- order_lines = order_with_lines.lines.all()- previous_order_refund_lines = [- OrderLineInfo(line=(line := order_lines[0]), quantity=1, variant=line.variant)- ]- create_refund(- order_with_lines,- order_lines=previous_order_refund_lines,- refund_shipping_costs=previous_refund_shipping_costs,- )- current_order_refund_lines = [- OrderLineInfo(line=(line := order_lines[0]), quantity=1, variant=line.variant),- OrderLineInfo(line=(line := order_lines[1]), quantity=1, variant=line.variant),- ]- fulfillment_refund_lines = []- refund_data = RefundData(- order_lines_to_refund=current_order_refund_lines,- fulfillment_lines_to_refund=fulfillment_refund_lines,- )-- # when- lines = create_refunded_lines(- order_with_lines,- refund_data,- )-- # then- order_refund_lines = [- OrderLineInfo(line=cl.line, quantity=pl.quantity + cl.quantity)- for pl, cl in zip_longest(- previous_order_refund_lines,- current_order_refund_lines,- fillvalue=Mock(spec=OrderLineInfo, quantity=0),- )- ]- assert lines == {line.line.variant_id: line.quantity for line in order_refund_lines}---@patch("saleor.payment.gateway.refund")[email protected]("previous_refund_shipping_costs", [True, False])-def test_create_refunded_lines_previously_refunded_fulfillment_lines(- _mocked_refund,- fulfilled_order,- create_refund,- previous_refund_shipping_costs,-):- # given- fulfillment_lines = list(- chain.from_iterable(f.lines.all() for f in fulfilled_order.fulfillments.all())- )- previous_fulfillment_refund_lines = [- FulfillmentLineData(line=fulfillment_lines[0], quantity=1)- ]- create_refund(- fulfilled_order,- fulfillment_lines=previous_fulfillment_refund_lines,- refund_shipping_costs=previous_refund_shipping_costs,- )- order_refund_lines = []- current_fulfillment_refund_lines = [- FulfillmentLineData(- line=fulfillment_lines[0],- quantity=1,- ),- FulfillmentLineData(- line=fulfillment_lines[1],- quantity=1,- ),- ]- refund_data = RefundData(- order_lines_to_refund=order_refund_lines,- fulfillment_lines_to_refund=current_fulfillment_refund_lines,- )-- # when- lines = create_refunded_lines(- fulfilled_order,- refund_data,- )-- # then- fulfillment_refund_lines = [- FulfillmentLineData(line=cl.line, quantity=pl.quantity + cl.quantity)- for pl, cl in zip_longest(- previous_fulfillment_refund_lines,- current_fulfillment_refund_lines,- fillvalue=Mock(spec=FulfillmentLineData, quantity=0),- )- ]- assert lines == {- line.line.order_line.variant_id: line.quantity- for line in fulfillment_refund_lines- }diff --git a/saleor/payment/gateways/np_atobarai/utils.py b/saleor/payment/gateways/np_atobarai/utils.pydeleted file mode 100644index d9c038e757..0000000000--- a/saleor/payment/gateways/np_atobarai/utils.py+++ /dev/null@@ -1,152 +0,0 @@-from collections import defaultdict-from collections.abc import Iterable-from contextlib import contextmanager-from decimal import Decimal-from itertools import chain--from django.db.models import Q--from ....core.tracing import otel_trace-from ....order import FulfillmentStatus-from ....order.events import external_notification_event-from ....order.models import Fulfillment, FulfillmentLine, Order-from ... import PaymentError-from ...interface import RefundData-from .api_types import ApiConfig-from .const import SHIPPING_COMPANY_CODE_METADATA_KEY, SHIPPING_COMPANY_CODES---def notify_dashboard(order: Order, message: str):- external_notification_event(- order=order, user=None, app=None, message=message, parameters=None- )---STATUSES_NOT_ALLOWED_TO_REFUND = [- FulfillmentStatus.CANCELED,- FulfillmentStatus.REFUNDED,- FulfillmentStatus.REPLACED,- FulfillmentStatus.REFUNDED_AND_RETURNED,- FulfillmentStatus.RETURNED,-]---def get_shipping_company_code(- config: ApiConfig, fulfillment: Fulfillment-) -> str | None:- code = fulfillment.get_value_from_private_metadata(- SHIPPING_COMPANY_CODE_METADATA_KEY, default=config.shipping_company- )- return None if code not in SHIPPING_COMPANY_CODES else code---def get_fulfillment_for_order(order: Order) -> Fulfillment:- fulfillments = order.fulfillments.exclude(- Q(tracking_number="") | Q(status__in=STATUSES_NOT_ALLOWED_TO_REFUND)- )-- if fulfillments.count() == 0:- raise PaymentError(- "Fulfillment with tracking number does not exist for this order"- )-- if fulfillments.count() > 1:- raise PaymentError(- "More than one fulfillment with tracking number exist for this order"- )-- return fulfillments[0]---@contextmanager-def np_atobarai_otel_trace(span_name: str):- with otel_trace(span_name=span_name, component_name="payment"):- yield---def _is_refunded_with_automatic_amount(line: FulfillmentLine) -> bool:- fulfillment = line.fulfillment- order_line = line.order_line-- shipping_amount = fulfillment.shipping_refund_amount or Decimal("0.00")- if not fulfillment.total_refund_amount:- return False-- refund_amount_is_a_multiply_of_unit_price = (- (fulfillment.total_refund_amount - shipping_amount)- % order_line.unit_price_gross_amount- ) == 0-- return (- order_line.variant_id is not None- and refund_amount_is_a_multiply_of_unit_price- and fulfillment.total_refund_amount <= order_line.total_price_gross_amount- )---def _get_refunded_fulfillment_lines_with_automatic_amount(- order: Order,-) -> Iterable[FulfillmentLine]:- return (- line- for line in FulfillmentLine.objects.select_related(- "order_line", "fulfillment"- ).filter(- fulfillment__order_id=order.pk,- fulfillment__status__in=[- FulfillmentStatus.REFUNDED,- FulfillmentStatus.REFUNDED_AND_RETURNED,- ],- )- if _is_refunded_with_automatic_amount(line)- )---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.- """- if not refund_data.refund_amount_is_automatically_calculated:- order_lines_to_refund = []- fulfillment_lines_to_refund = []- else:- order_lines_to_refund = refund_data.order_lines_to_refund- fulfillment_lines_to_refund = refund_data.fulfillment_lines_to_refund-- # Refund fulfillments for product refunds with automatic amount- previous_fulfillment_lines = _get_refunded_fulfillment_lines_with_automatic_amount(- order- )-- 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)diff --git a/saleor/settings.py b/saleor/settings.pyindex 3b0f251f66..70b7739dab 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -892,7 +892,6 @@ BUILTIN_PLUGINS = ["saleor.payment.gateways.braintree.plugin.DeprecatedBraintreeGatewayPlugin","saleor.payment.gateways.razorpay.plugin.DeprecatedRazorpayGatewayPlugin","saleor.payment.gateways.authorize_net.plugin.AuthorizeNetGatewayPlugin",- "saleor.payment.gateways.np_atobarai.plugin.NPAtobaraiGatewayPlugin","saleor.plugins.user_email.plugin.UserEmailPlugin","saleor.plugins.admin_email.plugin.AdminEmailPlugin","saleor.plugins.sendgrid.plugin.DeprecatedSendgridEmailPlugin",diff --git a/uv.lock b/uv.lockindex 374039ccc0..3591b5c3c7 100644--- a/uv.lock+++ b/uv.lock@@ -1822,15 +1822,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/b1/1f/4e7a9b6b33a085172a826d1f9d0a19a2e77982298acea13d40442f14ef28/poethepoet-0.32.2-py3-none-any.whl", hash = "sha256:97e165de8e00b07d33fd8d72896fad8b20ccafcd327b1118bb6a3da26af38d33", size = 81726, upload-time = "2025-01-26T19:53:35.45Z" },]-[[package]]-name = "posuto"-version = "2025.9.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/4f/c9/e4402bd121c4af54c07511bb84341b87a26f937b8da43fb9e4bdb230c0bd/posuto-2025.9.0.tar.gz", hash = "sha256:b0498da5626b7d47755f05eb6dc19cfc78198d324333eedb2f1d0b60427e57ef", size = 8531672, upload-time = "2025-08-31T09:22:30.089Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/74/24/b8e701003eab3790aa56d0ca91150aacd11a7f3a855f28fbc790d7fda00b/posuto-2025.9.0-py3-none-any.whl", hash = "sha256:01e8f914b9583ae40fc0bf790a59f1156f3869f8634a9aeee1be3527c2b46c0a", size = 7307332, upload-time = "2025-08-31T09:22:28.318Z" },-]-[[package]]name = "pre-commit"version = "4.3.0"@@ -2567,7 +2558,6 @@ dependencies = [{ name = "petl", marker = "platform_python_implementation != 'PyPy'" },{ name = "phonenumberslite", marker = "platform_python_implementation != 'PyPy'" },{ name = "pillow", marker = "platform_python_implementation != 'PyPy'" },- { name = "posuto", marker = "platform_python_implementation != 'PyPy'" },{ name = "prices", marker = "platform_python_implementation != 'PyPy'" },{ name = "promise", marker = "platform_python_implementation != 'PyPy'" },{ name = "psycopg", extra = ["binary"], marker = "platform_python_implementation != 'PyPy'" },@@ -2680,7 +2670,6 @@ requires-dist = [{ name = "petl", specifier = "==1.7.17" },{ name = "phonenumberslite", specifier = ">=9.0.7,<10" },{ name = "pillow", specifier = ">=12.1.1,<13" },- { name = "posuto", specifier = ">=2025.1.0,<2026" },{ name = "prices", specifier = "~=1.0" },{ name = "promise", specifier = "~=2.3" },{ name = "psycopg", extras = ["binary"], specifier = ">=3.2.9,<4" },