Skip to content

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

Port net protections (#8640) to 3.1

Krzysztof Kuligea4d654b4faf
diff --git a/.isort.cfg b/.isort.cfg
index 7ade008a8d..dde7141ca1 100644
--- a/.isort.cfg
+++ b/.isort.cfg
@@ -1,2 +1,2 @@
[settings]
-known_third_party = Adyen,PIL,authorizenet,babel,boto3,botocore,braintree,celery,dateutil,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html2text,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,micawber,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pybars,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sendgrid,sentry_sdk,storages,stripe,urllib3,uvicorn,versatileimagefield,weasyprint
+known_third_party = Adyen,PIL,authorizenet,babel,boto3,botocore,braintree,celery,dateutil,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html2text,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,micawber,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,posuto,prices,promise,pybars,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sendgrid,sentry_sdk,storages,stripe,urllib3,uvicorn,versatileimagefield,weasyprint
diff --git a/pyproject.toml b/pyproject.toml
index 62a15f52d0..c7ac16c76e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -66,6 +66,7 @@ documentation = "https://docs.saleor.io/"
sendgrid = "^6.7.1"
micawber = "^0.5.2"
django-celery-beat = "^2.2.1"
+ posuto = "^2021.10.0"
[tool.poetry.dependencies.celery]
version = ">=4.4.5,<6.0.0"
diff --git a/requirements.txt b/requirements.txt
index 2f1ef888c9..6147aa9f10 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -92,6 +92,7 @@ opentracing==2.4.0
petl==1.7.4; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.4.0")
phonenumberslite==8.12.38
pillow==8.4.0; python_version >= "3.6"
+posuto==2021.10.0
prices==1.1.0
promise==2.3
prompt-toolkit==3.0.23; python_full_version >= "3.6.2" and python_version >= "3.6"
diff --git a/requirements_dev.txt b/requirements_dev.txt
index 13ac07af71..796451cff8 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -127,6 +127,7 @@ phonenumberslite==8.12.38
pillow==8.4.0; python_version >= "3.6"
platformdirs==2.4.0; python_version >= "3.6" and python_full_version >= "3.6.2"
pluggy==1.0.0; python_version >= "3.6" and python_full_version < "3.0.0" or python_full_version >= "3.5.0" and python_version >= "3.6"
+posuto==2021.10.0
pre-commit==2.15.0; python_full_version >= "3.6.1"
prices==1.1.0
promise==2.3; python_version >= "3.6" and python_version < "4.0"
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 78b3ab54b4..e86fea67f9 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -683,6 +683,7 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
line.pk,
"order_line_id",
)
+ variant = line.variant
replace = line_data.get("replace", False)
if replace and not line.variant_id:
cls._raise_error_for_line(
@@ -693,7 +694,9 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
)
cleaned_order_lines.append(
- OrderLineData(line=line, quantity=quantity, replace=replace)
+ OrderLineData(
+ line=line, quantity=quantity, variant=variant, replace=replace
+ )
)
cleaned_input["order_lines"] = cleaned_order_lines
diff --git a/saleor/graphql/order/tests/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
index c6458595ae..2b476438a4 100644
--- a/saleor/graphql/order/tests/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
@@ -160,6 +160,7 @@ def test_fulfillment_refund_products_amount_and_shipping_costs(
ANY,
amount=quantize_price(amount_to_refund, fulfilled_order.currency),
channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
@@ -269,6 +270,7 @@ def test_fulfillment_refund_products_order_lines(
ANY,
amount=line_to_refund.unit_price_gross_amount * 2,
channel_slug=order_with_lines.channel.slug,
+ refund_data=ANY,
)
@@ -377,6 +379,7 @@ def test_fulfillment_refund_products_fulfillment_lines(
ANY,
amount=fulfillment_line_to_refund.order_line.unit_price_gross_amount * 2,
channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
@@ -431,6 +434,7 @@ def test_fulfillment_refund_products_waiting_fulfillment_lines(
ANY,
amount=fulfillment_line_to_refund.order_line.unit_price_gross_amount * 3,
channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
@@ -590,7 +594,11 @@ def test_fulfillment_refund_products_fulfillment_lines_include_shipping_costs(
amount = fulfillment_line_to_refund.order_line.unit_price_gross_amount * 2
amount += fulfilled_order.shipping_price_gross_amount
mocked_refund.assert_called_with(
- payment_dummy, ANY, amount=amount, channel_slug=fulfilled_order.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
@@ -631,7 +639,11 @@ def test_fulfillment_refund_products_order_lines_include_shipping_costs(
amount = line_to_refund.unit_price_gross_amount * 2
amount += order_with_lines.shipping_price_gross_amount
mocked_refund.assert_called_with(
- payment_dummy, ANY, amount=amount, channel_slug=order_with_lines.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=order_with_lines.channel.slug,
+ refund_data=ANY,
)
@@ -683,6 +695,7 @@ def test_fulfillment_refund_products_fulfillment_lines_custom_amount(
ANY,
amount=amount_to_refund,
channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
@@ -726,6 +739,7 @@ def test_fulfillment_refund_products_order_lines_custom_amount(
ANY,
amount=amount_to_refund,
channel_slug=order_with_lines.channel.slug,
+ refund_data=ANY,
)
@@ -816,5 +830,9 @@ def test_fulfillment_refund_products_fulfillment_lines_and_order_lines(
amount += order_line.unit_price_gross_amount * 2
amount = quantize_price(amount, fulfilled_order.currency)
mocked_refund.assert_called_with(
- payment_dummy, ANY, amount=amount, channel_slug=fulfilled_order.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
diff --git a/saleor/graphql/order/tests/test_fulfillment_return_products.py b/saleor/graphql/order/tests/test_fulfillment_return_products.py
index f9b5bbaf5c..5a2139b5a2 100644
--- a/saleor/graphql/order/tests/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_return_products.py
@@ -114,6 +114,7 @@ def test_fulfillment_return_products_amount_and_shipping_costs(
ANY,
amount=quantize_price(amount_to_refund, fulfilled_order.currency),
channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
@@ -299,7 +300,11 @@ def test_fulfillment_return_products_order_lines(
amount = line_to_return.unit_price_gross_amount * line_quantity_to_return
amount += order_with_lines.shipping_price_gross_amount
mocked_refund.assert_called_with(
- payment_dummy, ANY, amount=amount, channel_slug=order_with_lines.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=order_with_lines.channel.slug,
+ refund_data=ANY,
)
@@ -457,6 +462,7 @@ def test_fulfillment_return_products_order_lines_custom_amount(
ANY,
amount=amount_to_refund,
channel_slug=order_with_lines.channel.slug,
+ refund_data=ANY,
)
@@ -578,7 +584,11 @@ def test_fulfillment_return_products_fulfillment_lines(
)
amount += fulfilled_order.shipping_price_gross_amount
mocked_refund.assert_called_with(
- payment_dummy, ANY, amount=amount, channel_slug=fulfilled_order.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
@@ -797,7 +807,11 @@ def test_fulfillment_return_products_fulfillment_lines_include_shipping_costs(
amount = fulfillment_line_to_return.order_line.unit_price_gross_amount * 2
amount += fulfilled_order.shipping_price_gross_amount
mocked_refund.assert_called_with(
- payment_dummy, ANY, amount=amount, channel_slug=fulfilled_order.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
@@ -905,5 +919,9 @@ def test_fulfillment_return_products_fulfillment_lines_and_order_lines(
amount = order_line.unit_price_gross_amount * 2
amount = quantize_price(amount, fulfilled_order.currency)
mocked_refund.assert_called_with(
- payment_dummy, ANY, amount=amount, channel_slug=fulfilled_order.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 595b71fc27..dc0a31184a 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -22,7 +22,7 @@ from ..payment import (
gateway,
)
from ..payment.models import Payment, Transaction
-from ..payment.utils import create_payment
+from ..payment.utils import create_payment, create_refund_data
from ..warehouse.management import (
deallocate_stock,
deallocate_stock_for_order,
@@ -318,6 +318,7 @@ def fulfillment_tracking_updated(
tracking_number=tracking_number,
fulfillment=fulfillment,
)
+ manager.tracking_number_updated(fulfillment)
manager.order_updated(fulfillment.order)
@@ -1453,7 +1454,16 @@ def _process_refund(
amount = min(payment.captured_amount, amount)
try:
gateway.refund(
- payment, manager, amount=amount, channel_slug=order.channel.slug
+ payment,
+ manager,
+ amount=amount,
+ channel_slug=order.channel.slug,
+ refund_data=create_refund_data(
+ order,
+ order_lines_to_refund,
+ fulfillment_lines_to_refund,
+ refund_shipping_costs,
+ ),
)
except PaymentError:
raise ValidationError(
diff --git a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
index bf68554073..1370fd0fd2 100644
--- a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
+++ b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
@@ -154,6 +154,7 @@ def test_create_return_fulfillment_only_order_lines_with_refund(
ANY,
amount=amount,
channel_slug=order_with_lines.channel.slug,
+ refund_data=ANY,
)
assert not replace_order
@@ -228,6 +229,7 @@ def test_create_return_fulfillment_only_order_lines_included_shipping_costs(
ANY,
amount=amount,
channel_slug=order_with_lines.channel.slug,
+ refund_data=ANY,
)
assert not replace_order
@@ -577,6 +579,7 @@ def test_create_return_fulfillment_with_lines_already_refunded(
refunded_fulfillment_line = refunded_fulfillment.lines.create(
order_line=order_line, quantity=2
)
+ fulfilled_order.fulfillments.add(refunded_fulfillment)
fulfillment_lines_to_process = [
FulfillmentLineData(line=line, quantity=2)
@@ -622,6 +625,7 @@ def test_create_return_fulfillment_with_lines_already_refunded(
ANY,
amount=amount,
channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
assert returned_and_refunded_fulfillment.total_refund_amount == amount
diff --git a/saleor/order/tests/test_order_actions_refund_products.py b/saleor/order/tests/test_order_actions_refund_products.py
index 6710871400..281fdda5fc 100644
--- a/saleor/order/tests/test_order_actions_refund_products.py
+++ b/saleor/order/tests/test_order_actions_refund_products.py
@@ -68,7 +68,11 @@ def test_create_refund_fulfillment_only_order_lines(
assert returned_fulfillemnt.shipping_refund_amount is None
mocked_refund.assert_called_once_with(
- payment_dummy, ANY, amount=amount, channel_slug=order_with_lines.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=order_with_lines.channel.slug,
+ refund_data=ANY,
)
mocked_order_updated.assert_called_once_with(order_with_lines)
@@ -122,7 +126,11 @@ def test_create_refund_fulfillment_included_shipping_costs(
)
mocked_refund.assert_called_once_with(
- payment_dummy, ANY, amount=amount, channel_slug=order_with_lines.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=order_with_lines.channel.slug,
+ refund_data=ANY,
)
mocked_order_updated.assert_called_once_with(order_with_lines)
@@ -169,7 +177,11 @@ def test_create_refund_fulfillment_only_fulfillment_lines(
[line.order_line.unit_price_gross_amount * 2 for line in fulfillment_lines]
)
mocked_refund.assert_called_once_with(
- payment_dummy, ANY, amount=amount, channel_slug=fulfilled_order.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
mocked_order_updated.assert_called_once_with(fulfilled_order)
@@ -218,7 +230,11 @@ def test_create_refund_fulfillment_custom_amount(
for line in fulfillment_lines:
assert line.quantity == original_quantity.get(line.pk) - 2
mocked_refund.assert_called_once_with(
- payment_dummy, ANY, amount=amount, channel_slug=fulfilled_order.channel.slug
+ payment_dummy,
+ ANY,
+ amount=amount,
+ channel_slug=fulfilled_order.channel.slug,
+ refund_data=ANY,
)
mocked_order_updated.assert_called_once_with(fulfilled_order)
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index b701477455..70b8b8477c 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -1,6 +1,6 @@
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Callable, List, Optional
+from typing import TYPE_CHECKING, Callable, Dict, List, Optional
from ..core.tracing import traced_atomic_transaction
from . import GatewayError, PaymentError, TransactionKind
@@ -81,6 +81,7 @@ def process_payment(
) -> Transaction:
payment_data = create_payment_information(
payment=payment,
+ manager=manager,
payment_token=token,
customer_id=customer_id,
store_source=store_source,
@@ -121,6 +122,7 @@ def authorize(
clean_authorize(payment)
payment_data = create_payment_information(
payment=payment,
+ manager=manager,
payment_token=token,
customer_id=customer_id,
store_source=store_source,
@@ -161,6 +163,7 @@ def capture(
token = _get_past_transaction_token(payment, TransactionKind.AUTH)
payment_data = create_payment_information(
payment=payment,
+ manager=manager,
payment_token=token,
amount=amount,
customer_id=customer_id,
@@ -192,6 +195,7 @@ def refund(
manager: "PluginsManager",
channel_slug: str,
amount: Decimal = None,
+ refund_data: Optional[Dict[int, int]] = None,
) -> Transaction:
if amount is None:
amount = payment.captured_amount
@@ -203,7 +207,11 @@ def refund(
token = _get_past_transaction_token(payment, kind)
payment_data = create_payment_information(
- payment=payment, payment_token=token, amount=amount
+ payment=payment,
+ manager=manager,
+ payment_token=token,
+ amount=amount,
+ refund_data=refund_data,
)
if payment.is_manual():
# for manual payment we just need to mark payment as a refunded
@@ -236,7 +244,9 @@ def void(
channel_slug: str,
) -> Transaction:
token = _get_past_transaction_token(payment, TransactionKind.AUTH)
- payment_data = create_payment_information(payment=payment, payment_token=token)
+ payment_data = create_payment_information(
+ payment=payment, manager=manager, payment_token=token
+ )
response, error = _fetch_gateway_response(
manager.void_payment, payment.gateway, payment_data, channel_slug=channel_slug
)
@@ -264,7 +274,10 @@ def confirm(
).last()
token = txn.token if txn else ""
payment_data = create_payment_information(
- payment=payment, payment_token=token, additional_data=additional_data
+ payment=payment,
+ manager=manager,
+ payment_token=token,
+ additional_data=additional_data,
)
response, error = _fetch_gateway_response(
manager.confirm_payment,
diff --git a/saleor/payment/gateways/np_atobarai/__init__.py b/saleor/payment/gateways/np_atobarai/__init__.py
new file mode 100644
index 0000000000..fa6f0fdd59
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/__init__.py
@@ -0,0 +1,156 @@
+import logging
+import os
+from typing import List
+
+from ....order.models import Fulfillment
+from ... import PaymentError, TransactionKind
+from ...interface import GatewayConfig, GatewayResponse, PaymentData
+from ...models import Payment
+from . import api
+from .api_types import ApiConfig, PaymentStatus, get_api_config
+from .utils import (
+ get_fulfillment_for_order,
+ get_payment_name,
+ get_shipping_company_code,
+ notify_dashboard,
+)
+
+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]
+
+
+@inject_api_config
+def process_payment(
+ payment_information: PaymentData, config: ApiConfig
+) -> GatewayResponse:
+ 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.")
+
+ result = api.register_transaction(payment.order, 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,
+ error=parse_errors(result.errors),
+ raw_response=result.raw_response,
+ psp_reference=result.psp_reference,
+ )
+
+
+@inject_api_config
+def capture(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
+ raise NotImplementedError
+
+
+@inject_api_config
+def void(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
+ raise NotImplementedError
+
+
+@inject_api_config
+def tracking_number_updated(fulfillment: Fulfillment, config: ApiConfig) -> None:
+ from .plugin import NPAtobaraiGatewayPlugin
+
+ order = fulfillment.order
+ payments = order.payments.filter(
+ gateway=NPAtobaraiGatewayPlugin.PLUGIN_ID, is_active=True
+ )
+
+ if payments:
+ results = [
+ api.report_fulfillment(config, payment, fulfillment) for payment in payments
+ ]
+ else:
+ results = [("", ["No active payments for this order"], False)]
+
+ for payment_id, errors, already_captured in results:
+ payment_name = get_payment_name(payment_id)
+
+ if already_captured:
+ logger.warning("%s was already captured", payment_name.capitalize())
+ notify_dashboard(
+ order, f"Error: {payment_name.capitalize()} was already captured"
+ )
+ elif errors:
+ error = ", ".join(errors)
+ logger.warning(
+ "Could not capture %s in NP Atobarai: %s", payment_name, error
+ )
+ notify_dashboard(order, f"Capture Error for {payment_name}")
+ else:
+ notify_dashboard(order, f"Captured {payment_name}")
+
+
+@inject_api_config
+def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
+ payment_id = payment_information.payment_id
+ payment = Payment.objects.filter(pk=payment_id).first()
+
+ if not payment:
+ raise PaymentError(f"Payment with id {payment_id} does not exist.")
+
+ 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}."
+ )
+
+ refund_data = payment_information.refund_data
+
+ result = api.change_transaction(
+ config, payment, payment_information, refund_data
+ )
+
+ if not result:
+ fulfillment = get_fulfillment_for_order(order)
+ shipping_company_code = get_shipping_company_code(fulfillment)
+ tracking_number = fulfillment.tracking_number
+ result = api.reregister_transaction_for_partial_return(
+ config,
+ payment,
+ payment_information,
+ shipping_company_code,
+ tracking_number,
+ refund_data,
+ )
+
+ else:
+ result = api.cancel_transaction(config, payment_information)
+
+ # NP may issue a new psp reference on partial refunds
+ if psp_reference := result.psp_reference:
+ payment.psp_reference = 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,
+ 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.py
new file mode 100644
index 0000000000..f78e2772c0
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/api.py
@@ -0,0 +1,237 @@
+import logging
+from typing import Dict, List, Optional, Tuple, Union
+
+from ....order.models import Fulfillment, Order
+from ...interface import PaymentData
+from ...models import Payment
+from .api_helpers import (
+ cancel,
+ format_price,
+ get_goods_with_discount,
+ get_refunded_goods,
+ 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,
+ PAYMENT_DOES_NOT_EXIST,
+ TRANSACTION_CANCELLATION,
+ TRANSACTION_CHANGE,
+ TRANSACTION_REGISTRATION,
+ add_action_to_code,
+ get_error_messages_from_codes,
+)
+from .utils import get_shipping_company_code, np_atobarai_opentracing_trace
+
+logger = logging.getLogger(__name__)
+
+
+def register_transaction(
+ order: Optional[Order], config: ApiConfig, payment_information: "PaymentData"
+) -> PaymentResult:
+ with np_atobarai_opentracing_trace("np-atobarai.checkout.payments.register"):
+ result, error_codes = register(config, payment_information)
+
+ if error_codes:
+ error_messages = get_error_messages_from_codes(
+ action=TRANSACTION_REGISTRATION, error_codes=error_codes
+ )
+ return errors_payment_result(error_messages)
+
+ 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(
+ order, "cancel", transaction_id, cancel_error_codes
+ )
+ error_messages = result["authori_hold"]
+
+ return PaymentResult(
+ status=status,
+ psp_reference=transaction_id,
+ errors=error_messages,
+ )
+
+
+def cancel_transaction(
+ config: ApiConfig, payment_information: PaymentData
+) -> PaymentResult:
+ with np_atobarai_opentracing_trace("np-atobarai.checkout.payments.cancel"):
+ action = TRANSACTION_CANCELLATION
+ payment_id = payment_information.payment_id
+ payment = Payment.objects.filter(id=payment_id).first()
+
+ if not payment:
+ return error_payment_result(
+ add_action_to_code(action, error_code=PAYMENT_DOES_NOT_EXIST)
+ )
+
+ psp_reference = payment.psp_reference
+
+ if not psp_reference:
+ return error_payment_result(
+ add_action_to_code(action, error_code=NO_PSP_REFERENCE)
+ )
+
+ result, error_codes = 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)
+
+ return PaymentResult(status=PaymentStatus.SUCCESS)
+
+
+def change_transaction(
+ config: ApiConfig,
+ payment: Payment,
+ payment_information: PaymentData,
+ refund_data: Optional[Dict[int, int]],
+) -> Optional[PaymentResult]:
+ with np_atobarai_opentracing_trace("np-atobarai.checkout.payments.change"):
+ if refund_data:
+ goods = get_refunded_goods(config, refund_data, payment_information)
+ else:
+ goods = get_goods_with_discount(config, payment_information)
+
+ data = {
+ "transactions": [
+ {
+ "np_transaction_id": payment.psp_reference,
+ "billed_amount": format_price(
+ payment.captured_amount - payment_information.amount,
+ payment_information.currency,
+ ),
+ "goods": goods,
+ }
+ ]
+ }
+
+ result, error_codes = 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)
+
+ return PaymentResult(
+ status=PaymentStatus.SUCCESS,
+ )
+
+ if PRE_FULFILLMENT_ERROR_CODE in error_codes:
+ return None
+
+ error_messages = get_error_messages_from_codes(
+ action=TRANSACTION_CHANGE, error_codes=error_codes
+ )
+ return errors_payment_result(error_messages)
+
+
+def reregister_transaction_for_partial_return(
+ config: ApiConfig,
+ payment: Payment,
+ payment_information: PaymentData,
+ shipping_company_code: Optional[str],
+ tracking_number: Optional[str],
+ refund_data: Optional[Dict[int, int]],
+) -> PaymentResult:
+ with np_atobarai_opentracing_trace("np-atobarai.checkout.payments.reregister"):
+ 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,
+ )
+ )
+
+ if cancel_error_codes := cancel(config, psp_reference).error_codes:
+ error_messages = get_error_messages_from_codes(
+ action=TRANSACTION_CANCELLATION, error_codes=cancel_error_codes
+ )
+ return errors_payment_result(error_messages)
+
+ if refund_data:
+ goods = get_refunded_goods(config, refund_data, payment_information)
+ else:
+ goods = get_goods_with_discount(config, payment_information)
+
+ billed_amount = format_price(
+ payment.captured_amount - payment_information.amount,
+ payment_information.currency,
+ )
+
+ result, error_codes = register(
+ config,
+ payment_information,
+ billed_amount,
+ goods,
+ )
+
+ if not error_codes:
+ new_psp_reference = result["np_transaction_id"]
+
+ report(config, shipping_company_code, new_psp_reference, tracking_number)
+
+ return PaymentResult(
+ status=PaymentStatus.SUCCESS,
+ psp_reference=new_psp_reference,
+ )
+
+ error_messages = get_error_messages_from_codes(action, error_codes=error_codes)
+
+ return errors_payment_result(error_messages)
+
+
+def report_fulfillment(
+ config: ApiConfig, payment: Payment, fulfillment: Fulfillment
+) -> Tuple[Union[str, int], List[str], bool]:
+ with np_atobarai_opentracing_trace(
+ "np-atobarai.checkout.payments.report-fulfillment"
+ ):
+ payment_id = payment.psp_reference or payment.id
+ already_reported = False
+ shipping_company_code = get_shipping_company_code(fulfillment)
+
+ result, error_codes = report(
+ config,
+ shipping_company_code,
+ payment.psp_reference,
+ fulfillment.tracking_number,
+ )
+
+ if PRE_FULFILLMENT_ERROR_CODE in error_codes:
+ already_reported = True
+
+ errors = get_error_messages_from_codes(
+ action=FULFILLMENT_REPORT, error_codes=error_codes
+ )
+
+ return payment_id, errors, already_reported
diff --git a/saleor/payment/gateways/np_atobarai/api_helpers.py b/saleor/payment/gateways/np_atobarai/api_helpers.py
new file mode 100644
index 0000000000..d329036aa7
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/api_helpers.py
@@ -0,0 +1,258 @@
+import logging
+from decimal import Decimal
+from typing import TYPE_CHECKING, Dict, Iterable, List, Optional
+
+import requests
+from django.utils import timezone
+from posuto import Posuto
+from requests.auth import HTTPBasicAuth
+
+from saleor.order.models import Order
+
+from ...interface import AddressData, PaymentData
+from ...utils import price_to_minor_unit
+from .api_types import NPResponse, error_np_response
+from .const import NP_ATOBARAI, NP_TEST_URL, NP_URL, REQUEST_TIMEOUT
+from .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 notify_dashboard, np_atobarai_opentracing_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"{NP_TEST_URL if config.test_mode else NP_URL}{path}"
+
+
+def _request(
+ config: "ApiConfig",
+ method: str,
+ path: str = "",
+ json: Optional[dict] = None,
+) -> requests.Response:
+ with np_atobarai_opentracing_trace("np-atobarai.utilities.request"):
+ response = requests.request(
+ method=method,
+ url=get_url(config, path),
+ timeout=REQUEST_TIMEOUT,
+ json=json or {},
+ auth=HTTPBasicAuth(config.merchant_code, config.sp_code),
+ headers={"X-NP-Terminal-Id": config.terminal_id},
+ )
+ if 400 < response.status_code <= 600:
+ raise requests.HTTPError
+ return response
+
+
+def np_request(
+ config: "ApiConfig", method: str, path: str = "", json: Optional[dict] = None
+) -> NPResponse:
+ try:
+ response = _request(config, method, path, json)
+ response_data = response.json()
+ if "errors" in response_data:
+ return NPResponse({}, response_data["errors"][0]["codes"])
+ return NPResponse(response_data["results"][0], [])
+ except requests.RequestException:
+ logger.warning("Cannot connect to NP Atobarai.", exc_info=True)
+ return NPResponse({}, [NP_CONNECTION_ERROR])
+
+
+def handle_unrecoverable_state(
+ order: Optional[Order],
+ 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) -> Optional[str]:
+ """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}"
+ with Posuto() as pp:
+ try:
+ jap_ad = pp.get(ad.postal_code)
+ except KeyError:
+ 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_refunded_goods(
+ config: "ApiConfig",
+ refund_data: Dict[int, int],
+ payment_information: PaymentData,
+) -> List[dict]:
+ return [
+ {
+ "goods_name": line.product_sku if config.sku_as_name else line.product_name,
+ "goods_price": format_price(line.gross, payment_information.currency),
+ "quantity": quantity,
+ }
+ for line in payment_information.lines
+ if (quantity := refund_data.get(line.variant_id, line.quantity))
+ ]
+
+
+def get_goods(config: "ApiConfig", payment_information: PaymentData) -> List[dict]:
+ return [
+ {
+ "quantity": line.quantity,
+ "goods_name": line.product_sku if config.sku_as_name else line.product_name,
+ "goods_price": format_price(line.gross, payment_information.currency),
+ }
+ for line in payment_information.lines
+ ]
+
+
+def get_goods_with_discount(
+ config: "ApiConfig",
+ payment_information: PaymentData,
+) -> List[dict]:
+ product_lines = get_goods(config, payment_information)
+ return product_lines + [
+ {
+ "goods_name": "Discount",
+ "goods_price": format_price(
+ -payment_information.amount,
+ payment_information.currency,
+ ),
+ "quantity": 1,
+ }
+ ]
+
+
+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: Optional[int] = None,
+ goods: Optional[List[dict]] = 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": billing.first_name,
+ "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: Optional[str],
+ psp_reference: Optional[str],
+ shipping_slip_number: Optional[str],
+) -> 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.py
new file mode 100644
index 0000000000..92bc18d203
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/api_types.py
@@ -0,0 +1,67 @@
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Dict, List, NamedTuple
+
+from .const import (
+ FILL_MISSING_ADDRESS,
+ MERCHANT_CODE,
+ SHIPPING_COMPANY,
+ SKU_AS_NAME,
+ SP_CODE,
+ TERMINAL_ID,
+ USE_SANDBOX,
+)
+
+
+class NPResponse(NamedTuple):
+ result: dict
+ error_codes: List[str]
+
+
+def error_np_response(error_message: str) -> NPResponse:
+ return NPResponse({}, [error_message])
+
+
+@dataclass
+class ApiConfig:
+ test_mode: bool
+ 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"
+
+
+@dataclass
+class PaymentResult:
+ status: PaymentStatus
+ psp_reference: str = ""
+ 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])
+
+
+def errors_payment_result(errors: List[str]) -> PaymentResult:
+ return PaymentResult(status=PaymentStatus.FAILED, errors=errors)
+
+
+def get_api_config(connection_params: dict) -> ApiConfig:
+ return ApiConfig(
+ test_mode=connection_params[USE_SANDBOX],
+ 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.py
new file mode 100644
index 0000000000..d4301956c8
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/const.py
@@ -0,0 +1,43 @@
+# This integration is currently supporting the settlement type 02 - NP Atobarai
+NP_ATOBARAI = "02"
+NP_ATOBARAI_WIZ = "03"
+
+REQUEST_TIMEOUT = 30
+
+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.py
new file mode 100644
index 0000000000..dbfbcd2e90
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/errors.py
@@ -0,0 +1,32 @@
+from typing import Iterable, List
+
+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.py
new file mode 100644
index 0000000000..b819714900
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/plugin.py
@@ -0,0 +1,204 @@
+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 . import (
+ GatewayConfig,
+ capture,
+ get_api_config,
+ process_payment,
+ refund,
+ tracking_number_updated,
+ void,
+)
+from .api_helpers import health_check
+from .const import (
+ FILL_MISSING_ADDRESS,
+ MERCHANT_CODE,
+ SHIPPING_COMPANY,
+ SHIPPING_COMPANY_CODES,
+ SKU_AS_NAME,
+ SP_CODE,
+ TERMINAL_ID,
+ USE_SANDBOX,
+)
+from .utils import np_atobarai_opentracing_trace
+
+GATEWAY_NAME = "NP後払い"
+
+if TYPE_CHECKING:
+ # flake8: noqa
+ from ....plugins.models import PluginConfiguration
+ from . import GatewayResponse, PaymentData
+
+
+class NPAtobaraiGatewayPlugin(BasePlugin):
+ PLUGIN_ID = "saleor.payments.np-atobarai"
+ 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, self._get_gateway_config())
+
+ def refund_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ return refund(payment_information, self._get_gateway_config())
+
+ def void_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ return void(payment_information, self._get_gateway_config())
+
+ def process_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ return process_payment(payment_information, self._get_gateway_config())
+
+ def tracking_number_updated(self, fulfillment: "Fulfillment", previous_value):
+ tracking_number_updated(fulfillment, self._get_gateway_config())
+
+ 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"):
+ conf = {
+ data["name"]: data["value"] for data in plugin_configuration.configuration
+ }
+ with np_atobarai_opentracing_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"):
+ """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 [MERCHANT_CODE, SP_CODE, TERMINAL_ID, SHIPPING_COMPANY]
+ 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)
+
+ 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__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/payment/gateways/np_atobarai/tests/conftest.py b/saleor/payment/gateways/np_atobarai/tests/conftest.py
new file mode 100644
index 0000000000..af901b6819
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/conftest.py
@@ -0,0 +1,101 @@
+import dataclasses
+from decimal import Decimal
+
+import pytest
+
+from .....plugins.manager import get_plugins_manager
+from .....plugins.models import PluginConfiguration
+from ....interface import AddressData, PaymentLineData
+from .. import get_api_config
+from ..const import (
+ FILL_MISSING_ADDRESS,
+ MERCHANT_CODE,
+ SHIPPING_COMPANY,
+ 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",
+ 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},
+ ]
+ PluginConfiguration.objects.create(
+ identifier=NPAtobaraiGatewayPlugin.PLUGIN_ID,
+ name=NPAtobaraiGatewayPlugin.PLUGIN_NAME,
+ description="",
+ active=active,
+ channel=channel_USD,
+ configuration=configuration,
+ )
+
+ manager = get_plugins_manager()
+ return manager.plugins_per_channel[channel_USD.slug][0]
+
+ return fun
+
+
+def _resolve_lines():
+ return [
+ PaymentLineData(
+ gross=Decimal("100.00"),
+ product_name=f"Product Name {i}",
+ product_sku=f"PRODUCT_SKU_{i}",
+ variant_id=i,
+ quantity=5,
+ )
+ for i in range(3)
+ ]
+
+
+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="",
+ )
+
+
+def np_payment_data(np_address_data, dummy_payment_data):
+ return dataclasses.replace(
+ dummy_payment_data,
+ billing=np_address_data,
+ shipping=np_address_data,
+ _resolve_lines=_resolve_lines,
+ )
+
+
+def config(np_atobarai_plugin):
+ return get_api_config(np_atobarai_plugin().config.connection_params)
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_api.py b/saleor/payment/gateways/np_atobarai/tests/test_api.py
new file mode 100644
index 0000000000..008be428d0
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api.py
@@ -0,0 +1,783 @@
+import logging
+from decimal import Decimal
+from unittest.mock import ANY, Mock, patch
+
+import pytest
+import requests
+
+from .... import PaymentError
+from .. import PaymentStatus, api, const
+from ..api_helpers import format_price, get_goods_with_discount, get_refunded_goods
+from ..api_types import NPResponse
+from ..errors import (
+ NO_PSP_REFERENCE,
+ NO_TRACKING_NUMBER,
+ NP_CONNECTION_ERROR,
+ PAYMENT_DOES_NOT_EXIST,
+ SHIPPING_COMPANY_CODE_INVALID,
+)
+from ..plugin import NPAtobaraiGatewayPlugin
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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
+ psp_reference = "18121200001"
+ payment_dummy.psp_reference = psp_reference
+ payment_dummy.save(update_fields=["psp_reference"])
+ response = Mock(
+ spec=requests.Response,
+ status_code=200,
+ json=Mock(return_value={"results": [{"np_transaction_id": psp_reference}]}),
+ )
+ mocked_request.return_value = response
+
+ # when
+ gateway_response = plugin.refund_payment(payment_data, None)
+
+ # then
+ assert gateway_response.is_success
+
+
+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, match=rf"Order.*{payment_dummy.id}.*"):
+ # when
+ plugin.refund_payment(payment_data, None)
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_refund_payment_payment_not_created(
+ mocked_request, np_atobarai_plugin, np_payment_data, payment_dummy
+):
+ # given
+ plugin = np_atobarai_plugin()
+ payment_data = np_payment_data
+ response = Mock(
+ spec=requests.Response,
+ status_code=200,
+ json=Mock(return_value={"results": [{"np_transaction_id": "18121200001"}]}),
+ )
+ mocked_request.return_value = response
+
+ # when
+ gateway_response = plugin.refund_payment(payment_data, None)
+
+ # then
+ assert not gateway_response.is_success
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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."
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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")
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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 = None
+ 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
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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 = Mock(
+ spec=requests.Response,
+ status_code=200,
+ json=Mock(return_value={"results": [{"np_transaction_id": psp_reference}]}),
+ )
+ 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 = Mock(
+ spec=requests.Response,
+ status_code=200,
+ json=Mock(return_value={"results": [{"np_transaction_id": psp_reference}]}),
+ )
+ 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}"]
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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 = Mock(
+ spec=requests.Response,
+ status_code=400,
+ json=Mock(return_value={"errors": [{"codes": error_codes}]}),
+ )
+ 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]
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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(
+ 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.")
+ ]
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_report_fulfillment_already_captured(
+ mocked_request, config, fulfillment, payment_dummy
+):
+ # given
+ payment_dummy.psp_reference = "123123123"
+ response = Mock(
+ spec=requests.Response,
+ status_code=400,
+ json=Mock(return_value={"errors": [{"codes": ["E0100115"]}]}),
+ )
+ 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
+ mocked_notify_dashboard.assert_called_once_with(order, "Captured payment")
+ 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
+ mocked_notify_dashboard.assert_called_once_with(order, "Capture Error for payment")
+ assert len(caplog.records) == 1
+ assert caplog.records[0].levelno == logging.WARNING
+ assert caplog.records[0].message == (
+ f"Could not capture payment in NP Atobarai: {', '.join(errors)}"
+ )
+
+
+@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
+ mocked_notify_dashboard.assert_called_once_with(
+ order, "Error: Payment was already captured"
+ )
+ assert len(caplog.records) == 1
+ assert caplog.records[0].levelno == logging.WARNING
+ assert caplog.records[0].message == "Payment 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, "Capture Error for payment")
+ assert len(caplog.records) == 1
+ assert caplog.records[0].levelno == logging.WARNING
+ assert caplog.records[0].message == (
+ "Could not capture payment in NP Atobarai: No active payments for this order"
+ )
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_change_transaction_success(
+ mocked_request, config, payment_dummy, np_payment_data
+):
+ # given
+ refund_data = None
+ response = Mock(
+ spec=requests.Response,
+ status_code=200,
+ json=Mock(
+ return_value={
+ "results": [
+ {
+ "authori_result": "00",
+ "np_transaction_id": payment_dummy.psp_reference,
+ }
+ ]
+ }
+ ),
+ )
+ mocked_request.return_value = response
+
+ # when
+ payment_response = api.change_transaction(
+ config, payment_dummy, np_payment_data, refund_data
+ )
+
+ # then
+ assert payment_response.status == PaymentStatus.SUCCESS
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.cancel")
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_change_transaction_pending(
+ mocked_request, mocked_cancel, config, payment_dummy, np_payment_data
+):
+ # given
+ refund_data = None
+ transaction_id = "123"
+ response = Mock(
+ spec=requests.Response,
+ status_code=200,
+ json=Mock(
+ return_value={
+ "results": [
+ {
+ "authori_result": "10",
+ "np_transaction_id": transaction_id,
+ "authori_hold": [
+ "RE009",
+ "REE021",
+ ],
+ }
+ ]
+ }
+ ),
+ )
+ mocked_request.return_value = response
+
+ # when
+ payment_response = api.change_transaction(
+ config, payment_dummy, np_payment_data, refund_data
+ )
+
+ # then
+ mocked_cancel.assert_called_once_with(config, transaction_id)
+ assert payment_response.status == PaymentStatus.FAILED
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_change_transaction_post_fulfillment(
+ mocked_request, config, payment_dummy, np_payment_data
+):
+ # given
+ refund_data = None
+ response = Mock(
+ spec=requests.Response,
+ status_code=200,
+ json=Mock(return_value={"errors": [{"codes": ["E0100115"]}]}),
+ )
+ mocked_request.return_value = response
+
+ # when
+ payment_response = api.change_transaction(
+ config, payment_dummy, np_payment_data, refund_data
+ )
+
+ # then
+ assert payment_response is None
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_change_transaction_failed(
+ mocked_request, config, payment_dummy, np_payment_data
+):
+ # given
+ refund_data = None
+ response = Mock(
+ spec=requests.Response,
+ status_code=200,
+ json=Mock(return_value={"errors": [{"codes": ["E0100050"]}]}),
+ )
+ mocked_request.return_value = response
+
+ # when
+ payment_response = api.change_transaction(
+ config, payment_dummy, np_payment_data, refund_data
+ )
+
+ # then
+ assert payment_response.status == PaymentStatus.FAILED
+ assert payment_response.errors
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.np_request")
+def test_change_transaction_refunded_goods(
+ mocked_request, config, payment_dummy, np_payment_data
+):
+ # given
+ refund_data = {i: i for i in range(1, 4)}
+ mocked_request.return_value = NPResponse(
+ result={
+ "authori_result": "00",
+ "np_transaction_id": "123123123",
+ },
+ error_codes=[],
+ )
+
+ # when
+ api.change_transaction(config, payment_dummy, np_payment_data, refund_data)
+
+ # then
+ data = mocked_request.call_args[1]["json"]
+ goods = data["transactions"][0]["goods"]
+ assert goods == get_refunded_goods(config, refund_data, np_payment_data)
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.np_request")
+def test_change_transaction_goods_with_discount(
+ mocked_request, config, payment_dummy, np_payment_data
+):
+ # given
+ refund_data = None
+ mocked_request.return_value = NPResponse(
+ result={
+ "authori_result": "00",
+ "np_transaction_id": "123123123",
+ },
+ error_codes=[],
+ )
+
+ # when
+ api.change_transaction(config, payment_dummy, np_payment_data, refund_data)
+
+ # then
+ data = mocked_request.call_args[1]["json"]
+ goods = data["transactions"][0]["goods"]
+ assert goods == get_goods_with_discount(config, np_payment_data)
+
+
+@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
+ refund_data = None
+ tracking_number = "123"
+ shipping_company_code = "50000"
+ payment_dummy.psp_reference = "123"
+ new_psp_reference = "234"
+ mocked_cancel.return_value = NPResponse(result={}, error_codes=[])
+ mocked_register.return_value = NPResponse(
+ result={
+ "np_transaction_id": new_psp_reference,
+ },
+ error_codes=[],
+ )
+
+ # when
+ payment_response = api.reregister_transaction_for_partial_return(
+ config,
+ payment_dummy,
+ np_payment_data,
+ shipping_company_code,
+ tracking_number,
+ refund_data,
+ )
+
+ # then
+ mocked_cancel.assert_called_once_with(config, payment_dummy.psp_reference)
+ billed_amount = format_price(
+ payment_dummy.captured_amount - np_payment_data.amount, np_payment_data.currency
+ )
+ goods = get_goods_with_discount(config, np_payment_data)
+ mocked_register.assert_called_once_with(
+ config, np_payment_data, billed_amount, 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
+
+
+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()
+ )
+
+ # 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)
+
+ # when
+ payment_response = api.reregister_transaction_for_partial_return(
+ config, payment_dummy, np_payment_data, Mock(), Mock(), Mock()
+ )
+
+ # 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.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=[])
+ error_codes = ["1", "2", "3"]
+ mocked_register.return_value = NPResponse(result={}, error_codes=error_codes)
+
+ # when
+ payment_response = api.reregister_transaction_for_partial_return(
+ config,
+ payment_dummy,
+ np_payment_data,
+ Mock(),
+ Mock(),
+ Mock(),
+ )
+
+ # 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=[])
+ mocked_cancel.return_value = NPResponse(result={}, error_codes=[])
+
+ # when
+ payment_response = api.register_transaction(None, 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 == errors
+
+
+def test_cancel_transaction_no_payment(np_payment_data):
+ # given
+ payment_id = -1
+ np_payment_data.payment_id = payment_id
+
+ # when
+ payment_response = api.cancel_transaction(Mock(), np_payment_data)
+
+ # then
+ assert payment_response.errors == [f"TC#{PAYMENT_DOES_NOT_EXIST}"]
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py b/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py
new file mode 100644
index 0000000000..24679adfe6
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py
@@ -0,0 +1,201 @@
+from dataclasses import fields
+from unittest.mock import DEFAULT, Mock, patch, sentinel
+
+import pytest
+from posuto import Posuto
+
+from saleor.payment.interface import AddressData
+from saleor.payment.utils import price_to_minor_unit
+
+from .. import api_helpers, errors
+from ..api_helpers import get_goods, get_refunded_goods
+
+
+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}"
+ f"{double_byte_space}"
+ f"{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.gross, np_payment_data.currency)
+ ),
+ "quantity": line.quantity,
+ }
+ for line in np_payment_data.lines
+ ]
+
+
[email protected]("sku_as_name", [True, False])
+def test_get_refunded_goods(
+ config,
+ np_payment_data,
+ sku_as_name,
+):
+ # given
+ config.sku_as_name = sku_as_name
+ refund_data = {1: 23, 2: 0, 3: 13}
+
+ # when
+ goods = get_refunded_goods(config, refund_data, 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.gross, np_payment_data.currency)
+ ),
+ "quantity": quantity,
+ }
+ for line in np_payment_data.lines
+ if (quantity := refund_data.get(line.variant_id, line.quantity))
+ ]
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_plugin.py b/saleor/payment/gateways/np_atobarai/tests/test_plugin.py
new file mode 100644
index 0000000000..98430ee97a
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_plugin.py
@@ -0,0 +1,90 @@
+import os
+from unittest.mock import Mock, patch
+
+import requests
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.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
+ )
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py b/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
new file mode 100644
index 0000000000..19373a7e19
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
@@ -0,0 +1,69 @@
+from unittest import mock
+from unittest.mock import Mock
+
+import pytest
+import requests
+from django.core.exceptions import ValidationError
+
+from ..plugin import NPAtobaraiGatewayPlugin
+
+
[email protected]("saleor.payment.gateways.np_atobarai.api_helpers.requests.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]("saleor.payment.gateways.np_atobarai.api_helpers.requests.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)
+ 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
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_utils.py b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
new file mode 100644
index 0000000000..1e60550b50
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
@@ -0,0 +1,99 @@
+import pytest
+
+from .....order import FulfillmentStatus, OrderEvents
+from .... import PaymentError
+from .. import get_fulfillment_for_order, get_payment_name, notify_dashboard
+
+
+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
+
+
+ "payment_id, result",
+ [
+ ("123", "payment with psp reference 123"),
+ (123, "payment with id 123"),
+ ("", "payment"),
+ ],
+)
+def test_get_payment_name(payment_id, result):
+ # when
+ payment_name = get_payment_name(payment_id)
+
+ # then
+ assert payment_name == result
+
+
+def test_get_fulfillment_for_order(order):
+ # given
+ expected_fulfillment = order.fulfillments.create(tracking_number="123")
+
+ # 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)
diff --git a/saleor/payment/gateways/np_atobarai/utils.py b/saleor/payment/gateways/np_atobarai/utils.py
new file mode 100644
index 0000000000..3a09da1947
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/utils.py
@@ -0,0 +1,69 @@
+from contextlib import contextmanager
+from typing import Optional, Union
+
+from django.db.models import Q
+
+from ....core.tracing import opentracing_trace
+from ....order import FulfillmentStatus
+from ....order.events import external_notification_event
+from ....order.models import Fulfillment, Order
+from ... import PaymentError
+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
+ )
+
+
+def get_payment_name(payment_id: Union[int, str]) -> str:
+ if not payment_id:
+ return "payment"
+ if isinstance(payment_id, str):
+ return f"payment with psp reference {payment_id}"
+ return f"payment with id {payment_id}"
+
+
+STATUSES_NOT_ALLOWED_TO_REFUND = [
+ FulfillmentStatus.CANCELED,
+ FulfillmentStatus.REFUNDED,
+ FulfillmentStatus.REPLACED,
+ FulfillmentStatus.REFUNDED_AND_RETURNED,
+ FulfillmentStatus.RETURNED,
+]
+
+
+def get_shipping_company_code(fulfillment: Fulfillment) -> Optional[str]:
+ code = fulfillment.get_value_from_private_metadata(
+ SHIPPING_COMPANY_CODE_METADATA_KEY, default="50000"
+ )
+ 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_opentracing_trace(span_name: str):
+ with opentracing_trace(
+ span_name=span_name,
+ component_name="payment",
+ service_name="np-atobarai",
+ ):
+ yield
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index dd5e7afaf1..1c7278aa18 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -1,7 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import InitVar, dataclass, field
from decimal import Decimal
from enum import Enum
-from typing import Any, Dict, List, Optional, Union
+from functools import cached_property
+from typing import Any, Callable, Dict, List, Optional, Union
JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
@@ -66,6 +67,15 @@ class StorePaymentMethodEnum(str, Enum):
OFF_SESSION = "OFF_SESSION"
+@dataclass
+class PaymentLineData:
+ gross: Decimal
+ variant_id: int
+ product_name: str
+ product_sku: Optional[str]
+ quantity: int
+
+
@dataclass
class PaymentData:
"""Dataclass for storing all payment information.
@@ -92,6 +102,18 @@ class PaymentData:
store_payment_method: StorePaymentMethodEnum = StorePaymentMethodEnum.NONE
payment_metadata: Dict[str, str] = field(default_factory=dict)
psp_reference: Optional[str] = None
+ refund_data: Optional[Dict[int, int]] = None
+ # Optional, lazy-evaluated gateway arguments
+ _resolve_lines: InitVar[Callable] = None
+
+ def __post_init__(self, _resolve_lines: Callable):
+ self.__resolve_lines = _resolve_lines
+
+ # Note: this field does not appear in webhook payloads,
+ # because it's not visible to dataclasses.asdict
+ @cached_property
+ def lines(self) -> List[PaymentLineData]:
+ return self.__resolve_lines()
@dataclass
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
new file mode 100644
index 0000000000..45bb71ebf5
--- /dev/null
+++ b/saleor/payment/tests/test_utils.py
@@ -0,0 +1,404 @@
+from itertools import chain, zip_longest
+from typing import List
+from unittest.mock import Mock, patch
+
+import pytest
+
+from ...checkout.calculations import checkout_line_total
+from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ...order import FulfillmentLineData, OrderLineData
+from ...order.actions import create_refund_fulfillment
+from ...order.models import Order
+from ...plugins.manager import get_plugins_manager
+from ..interface import PaymentLineData
+from ..utils import (
+ SHIPPING_PAYMENT_LINE_ID,
+ create_payment_lines_information,
+ create_refund_data,
+)
+
+
+def create_refund_fulfillment_helper(payment_dummy):
+ def factory(
+ order: Order,
+ order_lines: List[OrderLineData] = None,
+ fulfillment_lines: List[FulfillmentLineData] = None,
+ refund_shipping_costs: bool = False,
+ ):
+ with patch("saleor.order.actions.gateway.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(),
+ refund_shipping_costs=refund_shipping_costs,
+ )
+
+ return factory
+
+
+ ["refund_shipping_costs", "shipping_line_quantity"], [(True, 0), (False, 1)]
+)
+def test_create_refund_data_order_lines(
+ order_with_lines, refund_shipping_costs, shipping_line_quantity
+):
+ # given
+ order_lines = order_with_lines.lines.all()
+ order_refund_lines = [
+ OrderLineData(line=(line := order_lines[0]), quantity=2, variant=line.variant),
+ OrderLineData(line=(line := order_lines[1]), quantity=1, variant=line.variant),
+ ]
+ fulfillment_refund_lines = []
+
+ # when
+ refund_data = create_refund_data(
+ order_with_lines,
+ order_refund_lines,
+ fulfillment_refund_lines,
+ refund_shipping_costs,
+ )
+
+ # then
+ assert refund_data == {
+ **{
+ line.variant_id: line.quantity - refund_line.quantity
+ for line, refund_line in zip(order_lines, order_refund_lines)
+ },
+ SHIPPING_PAYMENT_LINE_ID: shipping_line_quantity,
+ }
+
+
+ ["refund_shipping_costs", "shipping_line_quantity"], [(True, 0), (False, 1)]
+)
+def test_create_refund_data_fulfillment_lines(
+ fulfilled_order, refund_shipping_costs, shipping_line_quantity
+):
+ # given
+ fulfillment_lines = 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,
+ ),
+ ]
+
+ # when
+ refund_data = create_refund_data(
+ fulfilled_order,
+ order_refund_lines,
+ fulfillment_refund_lines,
+ refund_shipping_costs,
+ )
+
+ # then
+ assert refund_data == {
+ **{
+ line.order_line.variant_id: line.quantity - refund_line.quantity
+ for line, refund_line in zip(fulfillment_lines, fulfillment_refund_lines)
+ },
+ SHIPPING_PAYMENT_LINE_ID: shipping_line_quantity,
+ }
+
+
+ ["refund_shipping_costs", "shipping_line_quantity"], [(True, 0), (False, 1)]
+)
+def test_create_refund_data_shipping_only(
+ order, refund_shipping_costs, shipping_line_quantity
+):
+ # given
+ order_refund_lines = []
+ fulfillment_refund_lines = []
+
+ # when
+ refund_data = create_refund_data(
+ order, order_refund_lines, fulfillment_refund_lines, refund_shipping_costs
+ )
+
+ # then
+ assert refund_data == {SHIPPING_PAYMENT_LINE_ID: shipping_line_quantity}
+
+
+@patch("saleor.order.actions.gateway.refund")
+ [
+ "previous_refund_shipping_costs",
+ "current_refund_shipping_costs",
+ "shipping_line_quantity",
+ ],
+ [
+ (True, True, 0),
+ (True, False, 0),
+ (False, True, 0),
+ (False, False, 1),
+ ],
+)
+def test_create_refund_data_previously_refunded_order_lines(
+ _mocked_refund,
+ order_with_lines,
+ create_refund_fulfillment_helper,
+ previous_refund_shipping_costs,
+ current_refund_shipping_costs,
+ shipping_line_quantity,
+):
+ # given
+ order_lines = order_with_lines.lines.all()
+ previous_order_refund_lines = [
+ OrderLineData(line=(line := order_lines[0]), quantity=1, variant=line.variant)
+ ]
+ create_refund_fulfillment_helper(
+ order_with_lines,
+ order_lines=previous_order_refund_lines,
+ refund_shipping_costs=previous_refund_shipping_costs,
+ )
+ current_order_refund_lines = [
+ OrderLineData(line=(line := order_lines[0]), quantity=1, variant=line.variant),
+ OrderLineData(line=(line := order_lines[1]), quantity=1, variant=line.variant),
+ ]
+ fulfillment_refund_lines = []
+
+ # when
+ refund_data = create_refund_data(
+ order_with_lines,
+ current_order_refund_lines,
+ fulfillment_refund_lines,
+ current_refund_shipping_costs,
+ )
+
+ # then
+ order_refund_lines = [
+ OrderLineData(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=OrderLineData, quantity=0),
+ )
+ ]
+ assert refund_data == {
+ **{
+ line.variant_id: line.quantity - refund_line.quantity
+ for line, refund_line in zip(order_lines, order_refund_lines)
+ },
+ SHIPPING_PAYMENT_LINE_ID: shipping_line_quantity,
+ }
+
+
+@patch("saleor.order.actions.gateway.refund")
+ [
+ "previous_refund_shipping_costs",
+ "current_refund_shipping_costs",
+ "shipping_line_quantity",
+ ],
+ [
+ (True, True, 0),
+ (True, False, 0),
+ (False, True, 0),
+ (False, False, 1),
+ ],
+)
+def test_create_refund_data_previously_refunded_fulfillment_lines(
+ _mocked_refund,
+ fulfilled_order,
+ create_refund_fulfillment_helper,
+ previous_refund_shipping_costs,
+ current_refund_shipping_costs,
+ shipping_line_quantity,
+):
+ # 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_fulfillment_helper(
+ 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,
+ ),
+ ]
+
+ # when
+ refund_data = create_refund_data(
+ fulfilled_order,
+ order_refund_lines,
+ current_fulfillment_refund_lines,
+ current_refund_shipping_costs,
+ )
+
+ # 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 refund_data == {
+ **{
+ line.variant_id: line.quantity - refund_line.quantity
+ for line, refund_line in zip(
+ fulfilled_order.lines.all(), fulfillment_refund_lines
+ )
+ },
+ SHIPPING_PAYMENT_LINE_ID: shipping_line_quantity,
+ }
+
+
+@patch("saleor.order.actions.gateway.refund")
+ [
+ "previous_refund_shipping_costs",
+ "current_refund_shipping_costs",
+ "shipping_line_quantity",
+ ],
+ [
+ (True, True, 0),
+ (True, False, 0),
+ (False, True, 0),
+ (False, False, 1),
+ ],
+)
+def test_create_refund_data_previously_refunded_shipping_only(
+ _mocked_refund,
+ order,
+ create_refund_fulfillment_helper,
+ previous_refund_shipping_costs,
+ current_refund_shipping_costs,
+ shipping_line_quantity,
+):
+ # given
+ create_refund_fulfillment_helper(
+ order, refund_shipping_costs=previous_refund_shipping_costs
+ )
+ order_refund_lines = []
+ fulfillment_refund_lines = []
+
+ # when
+ refund_data = create_refund_data(
+ order,
+ order_refund_lines,
+ fulfillment_refund_lines,
+ current_refund_shipping_costs,
+ )
+
+ # then
+ assert refund_data == {SHIPPING_PAYMENT_LINE_ID: shipping_line_quantity}
+
+
+def test_create_payment_lines_information_order(payment_dummy):
+ # given
+ manager = get_plugins_manager()
+
+ # when
+ payment_lines = create_payment_lines_information(payment_dummy, manager)
+
+ # then
+ order = payment_dummy.order
+ 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,
+ )
+ ]
+
+
+def test_create_payment_lines_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 = []
+
+ for line_info in lines:
+ total_price = checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ discounts=discounts,
+ )
+ unit_gross = manager.calculate_checkout_line_unit_price(
+ total_price,
+ line_info.line.quantity,
+ checkout_info,
+ lines,
+ line_info,
+ address,
+ discounts,
+ ).gross.amount
+ quantity = line_info.line.quantity
+ variant_id = line_info.variant.id
+ product_name = f"{line_info.variant.product.name}, {line_info.variant.name}"
+ product_sku = line_info.variant.sku
+ expected_payment_lines.append(
+ PaymentLineData(
+ gross=unit_gross,
+ variant_id=variant_id,
+ product_name=product_name,
+ product_sku=product_sku,
+ quantity=quantity,
+ )
+ )
+
+ shipping_gross = manager.calculate_checkout_shipping(
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ ).gross.amount
+ expected_payment_lines.append(
+ PaymentLineData(
+ gross=shipping_gross,
+ variant_id=SHIPPING_PAYMENT_LINE_ID,
+ product_name="Shipping",
+ product_sku="Shipping",
+ quantity=1,
+ )
+ )
+
+ assert payment_lines == expected_payment_lines
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index b6d7ec2c50..707b0fe365 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,7 +1,9 @@
import json
import logging
+from collections import defaultdict
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, List, Optional
+from itertools import chain
+from typing import Any, Dict, Iterator, List, Optional, Tuple
import graphene
from babel.numbers import get_currency_precision
@@ -9,10 +11,15 @@ from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Q
from ..account.models import User
+from ..checkout.calculations import checkout_line_total
+from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ..checkout.models import Checkout
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
-from ..order.models import Order
+from ..discount.utils import fetch_active_discounts
+from ..order import FulfillmentLineData, FulfillmentStatus, OrderLineData
+from ..order.models import FulfillmentLine, Order, OrderLine
+from ..plugins.manager import PluginsManager, get_plugins_manager
from . import (
ChargeStatus,
GatewayError,
@@ -25,27 +32,155 @@ from .interface import (
AddressData,
GatewayResponse,
PaymentData,
+ PaymentLineData,
PaymentMethodInfo,
StorePaymentMethodEnum,
)
from .models import Payment, Transaction
-if TYPE_CHECKING:
- from ..plugins.manager import PluginsManager
-
logger = logging.getLogger(__name__)
GENERIC_TRANSACTION_ERROR = "Transaction was unsuccessful"
ALLOWED_GATEWAY_KINDS = {choices[0] for choices in TransactionKind.CHOICES}
+def create_payment_lines_information(
+ payment: Payment,
+ manager: PluginsManager,
+) -> List[PaymentLineData]:
+ checkout = payment.checkout
+ order = payment.order
+ line_items = []
+ if checkout:
+ lines = fetch_checkout_lines(checkout)
+ discounts = fetch_active_discounts()
+ checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)
+ address = checkout_info.shipping_address or checkout_info.billing_address
+
+ for line_info in lines:
+ total = checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ discounts=discounts,
+ )
+ unit_price = manager.calculate_checkout_line_unit_price(
+ total,
+ line_info.line.quantity,
+ checkout_info,
+ lines,
+ line_info,
+ address,
+ discounts,
+ )
+ unit_gross = unit_price.gross.amount
+
+ quantity = line_info.line.quantity
+ product_name = f"{line_info.variant.product.name}, {line_info.variant.name}"
+ product_sku = line_info.variant.sku
+ line_items.append(
+ PaymentLineData(
+ quantity=quantity,
+ product_name=product_name,
+ product_sku=product_sku,
+ variant_id=line_info.variant.id,
+ gross=unit_gross,
+ )
+ )
+ shipping_amount = manager.calculate_checkout_shipping(
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ ).gross.amount
+
+ 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)
+
+ 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,
+ )
+ )
+
+ 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
+
+
+# Values are outside of model's pk range to resolve
+# any collision with actual product variant pk
+VOUCHER_PAYMENT_LINE_ID = 0
+SHIPPING_PAYMENT_LINE_ID = -1
+
+
+def create_shipping_payment_line_data(amount: Decimal) -> PaymentLineData:
+ return PaymentLineData(
+ quantity=1,
+ product_name="Shipping",
+ product_sku="Shipping",
+ variant_id=SHIPPING_PAYMENT_LINE_ID,
+ gross=amount,
+ )
+
+
+def create_checkout_voucher_payment_line_data(
+ checkout: Checkout,
+) -> Optional[PaymentLineData]:
+ discount_amount = -checkout.discount_amount
+ return create_voucher_payment_line_data(discount_amount)
+
+
+def create_order_voucher_payment_line_data(
+ order: Order,
+) -> Optional[PaymentLineData]:
+ discount_amount = order.total_gross_amount - order.undiscounted_total_gross_amount
+ return create_voucher_payment_line_data(discount_amount)
+
+
+def create_voucher_payment_line_data(amount: Decimal) -> Optional[PaymentLineData]:
+ if not amount:
+ return None
+ return PaymentLineData(
+ quantity=1,
+ product_name="Voucher",
+ product_sku="Voucher",
+ variant_id=VOUCHER_PAYMENT_LINE_ID,
+ gross=amount,
+ )
+
+
def create_payment_information(
payment: Payment,
payment_token: str = None,
amount: Decimal = None,
customer_id: str = None,
store_source: bool = False,
+ refund_data: Optional[Dict[int, int]] = None,
additional_data: Optional[dict] = None,
+ manager: Optional[PluginsManager] = None,
) -> PaymentData:
"""Extract order information along with payment details.
@@ -97,8 +232,89 @@ def create_payment_information(
],
payment_metadata=payment.metadata,
psp_reference=payment.psp_reference,
+ refund_data=refund_data,
+ _resolve_lines=lambda: create_payment_lines_information(
+ payment, manager or get_plugins_manager()
+ ),
+ )
+
+
+RefundLines = Iterator[Tuple[Any, OrderLine]]
+
+
+def _prepare_refund_lines(
+ order: Order,
+ order_lines_to_refund: List[OrderLineData],
+ fulfillment_lines_to_refund: List[FulfillmentLineData],
+) -> Iterator[Tuple[int, int]]:
+ previous_fulfillment_lines = FulfillmentLine.objects.prefetch_related(
+ "order_line"
+ ).filter(
+ fulfillment__order_id=order.pk,
+ fulfillment__status__in=[
+ FulfillmentStatus.REFUNDED,
+ FulfillmentStatus.REFUNDED_AND_RETURNED,
+ ],
+ order_line__variant_id__isnull=False,
+ )
+
+ previous_refund_lines = (
+ (p_variant_id, line.quantity)
+ for line in previous_fulfillment_lines
+ if (p_variant_id := line.order_line.variant_id)
+ )
+
+ current_order_refund_lines = (
+ (variant.id, line.quantity)
+ for line in order_lines_to_refund
+ if (variant := line.variant)
+ )
+
+ current_fulfillment_refund_lines = (
+ (f_variant_id, line.quantity)
+ for line in fulfillment_lines_to_refund
+ if (f_variant_id := line.line.order_line.variant_id)
)
+ return chain(
+ previous_refund_lines,
+ current_order_refund_lines,
+ current_fulfillment_refund_lines,
+ )
+
+
+def create_refund_data(
+ order: Order,
+ order_lines_to_refund: List[OrderLineData],
+ fulfillment_lines_to_refund: List[FulfillmentLineData],
+ refund_shipping_costs: bool,
+) -> Dict[int, int]:
+ order_lines = {line.variant_id: line.quantity for line in order.lines.all()}
+
+ refund_lines = _prepare_refund_lines(
+ order, order_lines_to_refund, fulfillment_lines_to_refund
+ )
+
+ summed_refund_lines: Dict[int, int] = defaultdict(int)
+
+ for variant_id, quantity in refund_lines:
+ summed_refund_lines[variant_id] += quantity
+
+ lines = {
+ variant_id: order_lines[variant_id] - summed_refund_lines[variant_id]
+ for variant_id in summed_refund_lines
+ }
+
+ shipping_previously_refunded = order.fulfillments.exclude(
+ shipping_refund_amount__isnull=True
+ ).exists()
+
+ lines[SHIPPING_PAYMENT_LINE_ID] = (
+ 0 if shipping_previously_refunded or refund_shipping_costs else 1
+ )
+
+ return lines
+
def create_payment(
gateway: str,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index f00ceb4803..d87e399581 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -494,6 +494,9 @@ class BasePlugin:
# storefront should append info to the price about "including/excluding X% VAT".
show_taxes_on_storefront: Callable[[bool], bool]
+ # Trigger when tracking number is updated.
+ tracking_number_updated: Callable[["Fulfillment", Any], Any]
+
void_payment: Callable[["PaymentData", Any], GatewayResponse]
# Handle received http request.
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 3b62a23b24..67e6c851ca 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -663,6 +663,15 @@ class PluginsManager(PaymentInterface):
channel_slug=fulfillment.order.channel.slug,
)
+ def tracking_number_updated(self, fulfillment: "Fulfillment"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "tracking_number_updated",
+ default_value,
+ fulfillment,
+ channel_slug=fulfillment.order.channel.slug,
+ )
+
def checkout_created(self, checkout: "Checkout"):
default_value = None
return self.__run_method_on_plugins(
diff --git a/saleor/settings.py b/saleor/settings.py
index 9a3ae9aa66..289068c58d 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -553,6 +553,7 @@ BUILTIN_PLUGINS = [
"saleor.payment.gateways.razorpay.plugin.RazorpayGatewayPlugin",
"saleor.payment.gateways.adyen.plugin.AdyenGatewayPlugin",
"saleor.payment.gateways.authorize_net.plugin.AuthorizeNetGatewayPlugin",
+ "saleor.payment.gateways.np_atobarai.plugin.NPAtobaraiGatewayPlugin",
"saleor.plugins.invoicing.plugin.InvoicingPlugin",
"saleor.plugins.user_email.plugin.UserEmailPlugin",
"saleor.plugins.admin_email.plugin.AdminEmailPlugin",