Skip to content

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

Port NP Atobarai gateway to 3.1 (#8684)

Krzysztof Kuligbf654a5f958f
diff --git a/.isort.cfg b/.isort.cfg
index f774c71231..b4042edb7b 100644
--- a/.isort.cfg
+++ b/.isort.cfg
@@ -1,2 +1,2 @@
[settings]
-known_third_party = Adyen,PIL,authorizenet,babel,boto3,botocore,braintree,celery,cryptography,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_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,cryptography,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_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 58c3c0cf26..58e37a606a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -65,6 +65,7 @@ documentation = "https://docs.saleor.io/"
sendgrid = "^6.7.1"
micawber = "^0.5.2"
django-celery-beat = "^2.2.1"
+ posuto = "^2021.10.0"
cryptography = "^36.0.0"
[tool.poetry.dependencies.celery]
diff --git a/requirements.txt b/requirements.txt
index 4e32dae542..e6d50358fa 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -93,6 +93,7 @@ packaging==21.3; python_version >= "3.6"
petl==1.7.7; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.4.0")
phonenumberslite==8.12.43
pillow==9.0.1; python_version >= "3.7"
+posuto==2021.10.0
prices==1.1.0
promise==2.3
prompt-toolkit==3.0.28; python_full_version >= "3.6.2" and python_version >= "3.6"
diff --git a/requirements_dev.txt b/requirements_dev.txt
index 7f17c1b68a..ef54e8def4 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -127,6 +127,7 @@ phonenumberslite==8.12.43
pillow==9.0.1; python_version >= "3.7"
platformdirs==2.5.1; python_version >= "3.7" 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.17.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 9935991a76..0fc92e53f2 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -684,6 +684,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(
@@ -694,7 +695,9 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
)
cleaned_order_lines.append(
- OrderLineInfo(line=line, quantity=quantity, replace=replace)
+ OrderLineInfo(
+ 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..b4208bd477 100644
--- a/saleor/graphql/order/tests/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
@@ -5,9 +5,12 @@ import graphene
from prices import Money, TaxedMoney
from ....core.prices import quantize_price
+from ....order import FulfillmentLineData
from ....order.error_codes import OrderErrorCode
+from ....order.fetch import OrderLineInfo
from ....order.models import FulfillmentLine, FulfillmentStatus
from ....payment import ChargeStatus, PaymentError
+from ....payment.interface import RefundData
from ....warehouse.models import Allocation, Stock
from ...tests.utils import get_graphql_content
@@ -160,6 +163,10 @@ 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=RefundData(
+ refund_shipping_costs=True,
+ refund_amount_is_automatically_calculated=False,
+ ),
)
@@ -269,6 +276,15 @@ 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=RefundData(
+ order_lines_to_refund=[
+ OrderLineInfo(
+ line=line_to_refund,
+ quantity=2,
+ variant=line_to_refund.variant,
+ )
+ ],
+ ),
)
@@ -377,6 +393,14 @@ 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=RefundData(
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(
+ line=fulfillment_line_to_refund,
+ quantity=2,
+ )
+ ],
+ ),
)
@@ -431,6 +455,14 @@ 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=RefundData(
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(
+ line=fulfillment_line_to_refund,
+ quantity=3,
+ )
+ ],
+ ),
)
@@ -590,7 +622,16 @@ 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=RefundData(
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(line=fulfillment_line_to_refund, quantity=2)
+ ],
+ refund_shipping_costs=True,
+ ),
)
@@ -631,7 +672,18 @@ 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=RefundData(
+ order_lines_to_refund=[
+ OrderLineInfo(
+ line=line_to_refund, quantity=2, variant=line_to_refund.variant
+ )
+ ],
+ refund_shipping_costs=True,
+ ),
)
@@ -683,6 +735,15 @@ def test_fulfillment_refund_products_fulfillment_lines_custom_amount(
ANY,
amount=amount_to_refund,
channel_slug=fulfilled_order.channel.slug,
+ refund_data=RefundData(
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(
+ line=fulfillment_line_to_refund,
+ quantity=2,
+ )
+ ],
+ refund_amount_is_automatically_calculated=False,
+ ),
)
@@ -726,6 +787,14 @@ def test_fulfillment_refund_products_order_lines_custom_amount(
ANY,
amount=amount_to_refund,
channel_slug=order_with_lines.channel.slug,
+ refund_data=RefundData(
+ order_lines_to_refund=[
+ OrderLineInfo(
+ line=line_to_refund, quantity=2, variant=line_to_refund.variant
+ )
+ ],
+ refund_amount_is_automatically_calculated=False,
+ ),
)
@@ -816,5 +885,19 @@ 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=RefundData(
+ order_lines_to_refund=[
+ OrderLineInfo(line=order_line, quantity=2, variant=order_line.variant)
+ ],
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(
+ line=fulfillment_line_to_refund,
+ quantity=2,
+ )
+ ],
+ ),
)
diff --git a/saleor/graphql/order/tests/test_fulfillment_return_products.py b/saleor/graphql/order/tests/test_fulfillment_return_products.py
index f9b5bbaf5c..b930d2cc25 100644
--- a/saleor/graphql/order/tests/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_return_products.py
@@ -5,10 +5,12 @@ import graphene
from prices import Money, TaxedMoney
from ....core.prices import quantize_price
-from ....order import OrderOrigin, OrderStatus
+from ....order import FulfillmentLineData, OrderOrigin, OrderStatus
from ....order.error_codes import OrderErrorCode
+from ....order.fetch import OrderLineInfo
from ....order.models import FulfillmentStatus, Order
from ....payment import ChargeStatus, PaymentError
+from ....payment.interface import RefundData
from ....warehouse.models import Stock
from ...tests.utils import get_graphql_content
@@ -114,6 +116,10 @@ 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=RefundData(
+ refund_shipping_costs=True,
+ refund_amount_is_automatically_calculated=False,
+ ),
)
@@ -299,7 +305,20 @@ 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=RefundData(
+ order_lines_to_refund=[
+ OrderLineInfo(
+ line=line_to_return,
+ quantity=line_quantity_to_return,
+ variant=line_to_return.variant,
+ ),
+ ],
+ refund_shipping_costs=True,
+ ),
)
@@ -457,6 +476,16 @@ def test_fulfillment_return_products_order_lines_custom_amount(
ANY,
amount=amount_to_refund,
channel_slug=order_with_lines.channel.slug,
+ refund_data=RefundData(
+ order_lines_to_refund=[
+ OrderLineInfo(
+ line=line_to_return,
+ quantity=2,
+ variant=line_to_return.variant,
+ )
+ ],
+ refund_amount_is_automatically_calculated=False,
+ ),
)
@@ -578,7 +607,19 @@ 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=RefundData(
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(
+ line=fulfillment_line_to_return,
+ quantity=quantity_to_return,
+ ),
+ ],
+ refund_shipping_costs=True,
+ ),
)
@@ -797,7 +838,16 @@ 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=RefundData(
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(line=fulfillment_line_to_return, quantity=2)
+ ],
+ refund_shipping_costs=True,
+ ),
)
@@ -905,5 +955,17 @@ 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=RefundData(
+ order_lines_to_refund=[
+ OrderLineInfo(
+ line=order_line,
+ quantity=2,
+ variant=variant,
+ )
+ ],
+ ),
)
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index caea833d7f..b343d88252 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -21,6 +21,7 @@ from ..payment import (
TransactionKind,
gateway,
)
+from ..payment.interface import RefundData
from ..payment.models import Payment, Transaction
from ..payment.utils import create_payment
from ..warehouse.management import (
@@ -321,6 +322,7 @@ def fulfillment_tracking_updated(
tracking_number=tracking_number,
fulfillment=fulfillment,
)
+ manager.tracking_number_updated(fulfillment)
manager.order_updated(fulfillment.order)
@@ -1003,7 +1005,6 @@ def create_refund_fulfillment(
refund_shipping_costs=refund_shipping_costs,
manager=manager,
)
-
refunded_fulfillment = Fulfillment.objects.create(
status=FulfillmentStatus.REFUNDED,
order=order,
@@ -1446,6 +1447,12 @@ def _process_refund(
manager: "PluginsManager",
):
lines_to_refund: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]] = dict()
+ refund_data = RefundData(
+ order_lines_to_refund=order_lines_to_refund,
+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,
+ refund_shipping_costs=refund_shipping_costs,
+ refund_amount_is_automatically_calculated=amount is None,
+ )
if amount is None:
amount = _calculate_refund_amount(
order_lines_to_refund, fulfillment_lines_to_refund, lines_to_refund
@@ -1458,7 +1465,11 @@ 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=refund_data,
)
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 c9615b9646..dfb7ce58f2 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
@@ -3,6 +3,7 @@ from unittest.mock import ANY, patch
from prices import Money, TaxedMoney
+from ...payment.interface import RefundData
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
from ...warehouse.models import Allocation, Stock
@@ -108,15 +109,16 @@ def test_create_return_fulfillment_only_order_lines_with_refund(
)
lines_count = order_with_lines.lines.count()
+ order_lines_to_refund = [
+ OrderLineInfo(line=line, quantity=2, replace=False)
+ for line in order_lines_to_return
+ ]
response = create_fulfillments_for_returned_products(
user=staff_user,
app=None,
order=order_with_lines,
payment=payment,
- order_lines=[
- OrderLineInfo(line=line, quantity=2, replace=False)
- for line in order_lines_to_return
- ],
+ order_lines=order_lines_to_refund,
fulfillment_lines=[],
manager=get_plugins_manager(),
refund=True,
@@ -149,6 +151,9 @@ def test_create_return_fulfillment_only_order_lines_with_refund(
ANY,
amount=amount,
channel_slug=order_with_lines.channel.slug,
+ refund_data=RefundData(
+ order_lines_to_refund=order_lines_to_refund,
+ ),
)
assert not replace_order
@@ -180,15 +185,16 @@ def test_create_return_fulfillment_only_order_lines_included_shipping_costs(
)
lines_count = order_with_lines.lines.count()
+ order_lines_to_refund = [
+ OrderLineInfo(line=line, quantity=2, replace=False)
+ for line in order_lines_to_return
+ ]
response = create_fulfillments_for_returned_products(
user=staff_user,
app=None,
order=order_with_lines,
payment=payment,
- order_lines=[
- OrderLineInfo(line=line, quantity=2, replace=False)
- for line in order_lines_to_return
- ],
+ order_lines=order_lines_to_refund,
fulfillment_lines=[],
manager=get_plugins_manager(),
refund=True,
@@ -223,6 +229,10 @@ def test_create_return_fulfillment_only_order_lines_included_shipping_costs(
ANY,
amount=amount,
channel_slug=order_with_lines.channel.slug,
+ refund_data=RefundData(
+ order_lines_to_refund=order_lines_to_refund,
+ refund_shipping_costs=True,
+ ),
)
assert not replace_order
@@ -572,6 +582,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)
@@ -617,6 +628,9 @@ def test_create_return_fulfillment_with_lines_already_refunded(
ANY,
amount=amount,
channel_slug=fulfilled_order.channel.slug,
+ refund_data=RefundData(
+ fulfillment_lines_to_refund=fulfillment_lines_to_process,
+ ),
)
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 f5ea1c0d20..29ceb947d6 100644
--- a/saleor/order/tests/test_order_actions_refund_products.py
+++ b/saleor/order/tests/test_order_actions_refund_products.py
@@ -2,6 +2,7 @@ from decimal import Decimal
from unittest.mock import ANY, patch
from ...payment import ChargeStatus
+from ...payment.interface import RefundData
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
from ...warehouse.models import Allocation
@@ -32,14 +33,15 @@ def test_create_refund_fulfillment_only_order_lines(
)
lines_count = order_with_lines.lines.count()
+ order_refund_lines = [
+ OrderLineInfo(line=line, quantity=2) for line in order_lines_to_refund
+ ]
returned_fulfillemnt = create_refund_fulfillment(
user=None,
app=None,
order=order_with_lines,
payment=payment,
- order_lines_to_refund=[
- OrderLineInfo(line=line, quantity=2) for line in order_lines_to_refund
- ],
+ order_lines_to_refund=order_refund_lines,
fulfillment_lines_to_refund=[],
manager=get_plugins_manager(),
)
@@ -69,7 +71,13 @@ 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=RefundData(
+ order_lines_to_refund=order_refund_lines,
+ ),
)
mocked_order_updated.assert_called_once_with(order_with_lines)
@@ -91,14 +99,15 @@ def test_create_refund_fulfillment_included_shipping_costs(
order_line_ids = order_lines_to_refund.values_list("id", flat=True)
lines_count = order_with_lines.lines.count()
+ order_refund_lines = [
+ OrderLineInfo(line=line, quantity=2) for line in order_lines_to_refund
+ ]
returned_fulfillemnt = create_refund_fulfillment(
user=None,
app=None,
order=order_with_lines,
payment=payment,
- order_lines_to_refund=[
- OrderLineInfo(line=line, quantity=2) for line in order_lines_to_refund
- ],
+ order_lines_to_refund=order_refund_lines,
fulfillment_lines_to_refund=[],
manager=get_plugins_manager(),
refund_shipping_costs=True,
@@ -123,7 +132,14 @@ 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=RefundData(
+ order_lines_to_refund=order_refund_lines,
+ refund_shipping_costs=True,
+ ),
)
mocked_order_updated.assert_called_once_with(order_with_lines)
@@ -143,16 +159,17 @@ def test_create_refund_fulfillment_only_fulfillment_lines(
original_quantity = {line.id: line.quantity for line in fulfillment_lines}
fulfillment_lines_to_refund = fulfillment_lines
+ fulfillment_refund_lines = [
+ FulfillmentLineData(line=line, quantity=2)
+ for line in fulfillment_lines_to_refund
+ ]
returned_fulfillemnt = create_refund_fulfillment(
user=None,
app=None,
order=fulfilled_order,
payment=payment,
order_lines_to_refund=[],
- fulfillment_lines_to_refund=[
- FulfillmentLineData(line=line, quantity=2)
- for line in fulfillment_lines_to_refund
- ],
+ fulfillment_lines_to_refund=fulfillment_refund_lines,
manager=get_plugins_manager(),
)
@@ -170,7 +187,13 @@ 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=RefundData(
+ fulfillment_lines_to_refund=fulfillment_refund_lines,
+ ),
)
mocked_order_updated.assert_called_once_with(fulfilled_order)
@@ -194,16 +217,17 @@ def test_create_refund_fulfillment_custom_amount(
fulfillment_lines_to_refund = fulfillment_lines
amount = Decimal("10.00")
+ fulfillment_refund_lines = [
+ FulfillmentLineData(line=line, quantity=2)
+ for line in fulfillment_lines_to_refund
+ ]
returned_fulfillemnt = create_refund_fulfillment(
user=None,
app=None,
order=fulfilled_order,
payment=payment,
order_lines_to_refund=[],
- fulfillment_lines_to_refund=[
- FulfillmentLineData(line=line, quantity=2)
- for line in fulfillment_lines_to_refund
- ],
+ fulfillment_lines_to_refund=fulfillment_refund_lines,
manager=get_plugins_manager(),
amount=amount,
)
@@ -219,7 +243,14 @@ 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=RefundData(
+ fulfillment_lines_to_refund=fulfillment_refund_lines,
+ refund_amount_is_automatically_calculated=False,
+ ),
)
mocked_order_updated.assert_called_once_with(fulfilled_order)
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index a8d77f2c1a..a4e03c20c4 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, Tuple
from ..core.tracing import traced_atomic_transaction
from . import GatewayError, PaymentError, TransactionKind
@@ -18,7 +18,7 @@ from .utils import (
if TYPE_CHECKING:
# flake8: noqa
- from ..payment.interface import CustomerSource, PaymentGateway
+ from ..payment.interface import CustomerSource, PaymentGateway, RefundData
from ..plugins.manager import PluginsManager
@@ -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,
@@ -191,6 +194,7 @@ def refund(
manager: "PluginsManager",
channel_slug: str,
amount: Decimal = None,
+ refund_data: Optional["RefundData"] = None,
) -> Transaction:
if amount is None:
amount = payment.captured_amount
@@ -202,7 +206,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
@@ -234,7 +242,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
)
@@ -262,7 +272,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..466481010b
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/__init__.py
@@ -0,0 +1,169 @@
+import logging
+import os
+from typing import List
+
+from graphene import Node
+
+from ....order.models import Fulfillment
+from ... import PaymentError, TransactionKind
+from ...interface import GatewayResponse, PaymentData
+from ...models import Payment
+from . import api
+from .api_helpers import get_goods_with_refunds
+from .api_types import ApiConfig, PaymentStatus
+from .const import NP_PLUGIN_ID
+from .utils import (
+ get_fulfillment_for_order,
+ get_shipping_company_code,
+ notify_dashboard,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def parse_errors(errors: List[str]) -> str:
+ # Field error of Transaction db model has max length of 256
+ # Error codes have max length of 11
+ # We are limiting errors to maximum of 11 codes, because:
+ # 11 * 11 + 10 * 2 (max length of linesep) == 141 < 256
+ return os.linesep.join(errors[:11])
+
+
+def process_payment(
+ payment_information: PaymentData, config: ApiConfig
+) -> GatewayResponse:
+ """Create new transaction in NP Atobarai.
+
+ Returns unsuccessful response if payment status from
+ NP response is PENDING or FAILED.
+ """
+ result = api.register_transaction(config, payment_information)
+
+ return GatewayResponse(
+ is_success=result.status == PaymentStatus.SUCCESS,
+ action_required=False,
+ kind=TransactionKind.CAPTURE,
+ amount=payment_information.amount,
+ currency=payment_information.currency,
+ transaction_id=result.psp_reference or "",
+ error=parse_errors(result.errors),
+ raw_response=result.raw_response,
+ psp_reference=result.psp_reference,
+ )
+
+
+def capture(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
+ raise NotImplementedError
+
+
+def void(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
+ raise NotImplementedError
+
+
+def tracking_number_updated(fulfillment: Fulfillment, config: ApiConfig) -> None:
+ """Event callback on updating order tracking number.
+
+ Captures payment in NP Atobarai and sends dashboard notification of the result.
+ """
+ order = fulfillment.order
+ payments = order.payments.filter(gateway=NP_PLUGIN_ID, is_active=True)
+
+ if not payments:
+ logger.warning("No active payments for this order")
+ notify_dashboard(order, "No active payments for this order")
+ return
+
+ results = [
+ (payment.id, *api.report_fulfillment(config, payment, fulfillment))
+ for payment in payments
+ ]
+
+ for payment_id, errors, already_captured in results:
+ payment_graphql_id = Node.to_global_id("Payment", payment_id)
+
+ if already_captured:
+ logger.warning(
+ "Payment with id %s was already captured", payment_graphql_id
+ )
+ msg = f"Error: Payment with id {payment_graphql_id} was already captured"
+ elif errors:
+ error = ", ".join(errors)
+ logger.warning(
+ f"Could not capture payment with id {payment_graphql_id} "
+ f"in NP Atobarai: {error}"
+ )
+ msg = (
+ f"Error: Cannot capture payment with id {payment_graphql_id} ({error})"
+ )
+ else:
+ msg = f"Payment with id {payment_graphql_id} was captured"
+
+ notify_dashboard(order, msg)
+
+
+def refund(payment_information: PaymentData, config: ApiConfig) -> GatewayResponse:
+ """Refund an existing transaction.
+
+ A new psp reference may be issued,
+ which will be saved in payment object.
+ """
+ payment_id = payment_information.payment_id
+ payment = Payment.objects.filter(pk=payment_id).first()
+
+ if not payment:
+ raise PaymentError(f"Payment with id {payment_id} does not exist.")
+
+ goods, billed_amount = get_goods_with_refunds(config, payment, payment_information)
+
+ # in case of refunding less than already captured
+ # and not all lines are being refunded,
+ # the transaction needs to be re-registered in NP Atobarai
+ if payment_information.amount < payment.captured_amount and goods:
+ order = payment.order
+
+ if not order:
+ raise PaymentError(
+ f"Order does not exist for payment with id {payment_id}."
+ )
+
+ result = api.change_transaction(
+ config,
+ payment,
+ payment_information,
+ goods,
+ billed_amount,
+ )
+
+ if result.status == PaymentStatus.FOR_REREGISTRATION:
+ fulfillment = get_fulfillment_for_order(order)
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
+ tracking_number = fulfillment.tracking_number
+ result = api.reregister_transaction_for_partial_return(
+ config,
+ payment,
+ payment_information,
+ shipping_company_code,
+ tracking_number,
+ goods,
+ billed_amount,
+ )
+
+ else:
+ result = api.cancel_transaction(config, payment_information)
+
+ new_psp_reference = result.psp_reference
+ if new_psp_reference and payment.psp_reference != new_psp_reference:
+ payment.psp_reference = new_psp_reference
+ payment.save(update_fields=["psp_reference"])
+
+ return GatewayResponse(
+ is_success=result.status == PaymentStatus.SUCCESS,
+ action_required=False,
+ kind=TransactionKind.REFUND,
+ amount=payment_information.amount,
+ currency=payment_information.currency,
+ transaction_id=result.psp_reference or "",
+ error=parse_errors(result.errors),
+ raw_response=result.raw_response,
+ psp_reference=result.psp_reference,
+ )
diff --git a/saleor/payment/gateways/np_atobarai/api.py b/saleor/payment/gateways/np_atobarai/api.py
new file mode 100644
index 0000000000..5f06a8fb01
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/api.py
@@ -0,0 +1,231 @@
+import logging
+from decimal import Decimal
+from typing import List, Optional, Tuple
+
+from ....order.models import Fulfillment
+from ...interface import PaymentData
+from ...models import Payment
+from .api_helpers import (
+ cancel,
+ format_price,
+ handle_unrecoverable_state,
+ np_request,
+ register,
+ report,
+)
+from .api_types import (
+ ApiConfig,
+ PaymentResult,
+ PaymentStatus,
+ error_payment_result,
+ errors_payment_result,
+)
+from .const import PRE_FULFILLMENT_ERROR_CODE
+from .errors import (
+ FULFILLMENT_REPORT,
+ NO_PSP_REFERENCE,
+ TRANSACTION_CANCELLATION,
+ TRANSACTION_CHANGE,
+ TRANSACTION_REGISTRATION,
+ add_action_to_code,
+ get_error_messages_from_codes,
+)
+from .utils import get_shipping_company_code
+
+logger = logging.getLogger(__name__)
+
+
+def register_transaction(
+ config: ApiConfig, payment_information: "PaymentData"
+) -> PaymentResult:
+ """Create a new transaction in NP Atobarai.
+
+ On pending status from NP the transaction is cancelled and
+ reason for pending is returned as error message.
+ """
+ action = TRANSACTION_REGISTRATION
+ result, error_codes = register(config, payment_information)
+
+ if error_codes:
+ error_messages = get_error_messages_from_codes(action, error_codes=error_codes)
+ return errors_payment_result(error_messages)
+
+ status = result["authori_result"]
+ transaction_id = result["np_transaction_id"]
+ error_messages = []
+
+ if status == PaymentStatus.PENDING:
+ if cancel_error_codes := cancel(config, transaction_id).error_codes:
+ handle_unrecoverable_state(
+ None, "cancel", transaction_id, cancel_error_codes
+ )
+ error_messages = get_error_messages_from_codes(
+ action, error_codes=result["authori_hold"]
+ )
+
+ return PaymentResult(
+ status=status,
+ psp_reference=transaction_id,
+ errors=error_messages,
+ )
+
+
+def cancel_transaction(
+ config: ApiConfig, payment_information: PaymentData
+) -> PaymentResult:
+ action = TRANSACTION_CANCELLATION
+ psp_reference = payment_information.psp_reference
+
+ if not psp_reference:
+ return error_payment_result(
+ add_action_to_code(action, error_code=NO_PSP_REFERENCE)
+ )
+
+ result, error_codes = 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,
+ goods: List[dict],
+ billed_amount: Decimal,
+) -> PaymentResult:
+ """Change transaction.
+
+ If the fulfillment was reported prior to changing given transaction,
+ then no change is applied and payment status is set to FOR_REREGISTRATION.
+ """
+ data = {
+ "transactions": [
+ {
+ "np_transaction_id": payment.psp_reference,
+ "billed_amount": format_price(
+ billed_amount,
+ payment_information.currency,
+ ),
+ "goods": goods,
+ }
+ ]
+ }
+
+ result, error_codes = 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:
+ logger.info(
+ "Fulfillment for payment with id %s was reported",
+ payment_information.graphql_payment_id,
+ )
+ return PaymentResult(status=PaymentStatus.FOR_REREGISTRATION)
+
+ 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],
+ goods: List[dict],
+ billed_amount: Decimal,
+) -> PaymentResult:
+ """Change transaction.
+
+ Use it after capturing the payment, otherwise `change_transaction`
+ is the preferred function.
+ """
+ psp_reference = payment.psp_reference
+ action = TRANSACTION_REGISTRATION
+
+ if not psp_reference:
+ return error_payment_result(
+ add_action_to_code(
+ action,
+ error_code=NO_PSP_REFERENCE,
+ )
+ )
+
+ 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)
+
+ result, error_codes = register(
+ config,
+ payment_information,
+ format_price(billed_amount, payment_information.currency),
+ goods,
+ )
+
+ if not error_codes:
+ new_psp_reference = result["np_transaction_id"]
+
+ result, error_codes = report(
+ config, shipping_company_code, new_psp_reference, tracking_number
+ )
+
+ if error_codes:
+ error_messages = get_error_messages_from_codes(
+ FULFILLMENT_REPORT, error_codes=error_codes
+ )
+ return errors_payment_result(error_messages)
+
+ 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[List[str], bool]:
+ """Report fulfillment.
+
+ After this action, given payment is captured in NP Atobarai.
+ """
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
+
+ result, error_codes = report(
+ config,
+ shipping_company_code,
+ payment.psp_reference,
+ fulfillment.tracking_number,
+ )
+
+ errors = get_error_messages_from_codes(
+ action=FULFILLMENT_REPORT, error_codes=error_codes
+ )
+ already_reported = PRE_FULFILLMENT_ERROR_CODE in error_codes
+
+ return errors, already_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..988bdfba59
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/api_helpers.py
@@ -0,0 +1,341 @@
+import logging
+from decimal import Decimal
+from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
+
+import requests
+from django.utils import timezone
+from posuto import Posuto
+from requests.auth import HTTPBasicAuth
+
+from ....order.models import Order
+from ... import PaymentError
+from ...interface import AddressData, PaymentData, PaymentLineData, RefundData
+from ...models import Payment
+from ...utils import price_to_minor_unit
+from .api_types import NPResponse, error_np_response
+from .const import NP_ATOBARAI, REQUEST_TIMEOUT
+from .errors import (
+ BILLING_ADDRESS_INVALID,
+ NO_BILLING_ADDRESS,
+ NO_PSP_REFERENCE,
+ NO_SHIPPING_ADDRESS,
+ NO_TRACKING_NUMBER,
+ NP_CONNECTION_ERROR,
+ SHIPPING_ADDRESS_INVALID,
+ SHIPPING_COMPANY_CODE_INVALID,
+)
+from .utils import (
+ calculate_manual_refund_amount,
+ create_refunded_lines,
+ 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"{config.url}{path}"
+
+
+def _request(
+ config: "ApiConfig",
+ method: str,
+ path: str = "",
+ json: Optional[dict] = None,
+) -> requests.Response:
+ trace_name = f"np-atobarai.request.{path.lstrip('/')}"
+ with np_atobarai_opentracing_trace(trace_name):
+ 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},
+ )
+ # NP Atobarai returns error codes with http status code 400
+ # Because we want to pass those errors to the end user,
+ # we treat 400 as valid response.
+ if 400 < response.status_code <= 600:
+ raise requests.HTTPError
+ 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}"
+ try:
+ with Posuto() as pp:
+ jap_ad = pp.get(ad.postal_code)
+ except KeyError:
+ logger.warning("Invalid japanese postal code: %s", ad.postal_code)
+ return None
+ else:
+ return (
+ f"{ad.country_area}"
+ f"{jap_ad.city}"
+ f"{jap_ad.neighborhood}"
+ f"{ad.street_address_1}"
+ f"{ad.street_address_2}"
+ )
+
+
+def format_price(price: Decimal, currency: str) -> int:
+ return int(price_to_minor_unit(price, currency))
+
+
+def _get_goods_name(line: PaymentLineData, config: "ApiConfig") -> str:
+ if not config.sku_as_name:
+ return line.product_name
+ elif sku := line.product_sku:
+ return sku
+ return str(line.variant_id)
+
+
+def _get_voucher_and_shipping_goods(
+ config: "ApiConfig",
+ payment_information: PaymentData,
+) -> List[dict]:
+ """Convert voucher and shipping amount into NP Atobarai goods lines."""
+ goods_lines = []
+ voucher_amount = payment_information.lines_data.voucher_amount
+ if voucher_amount:
+ goods_lines.append(
+ {
+ "goods_name": "Voucher",
+ "goods_price": format_price(
+ voucher_amount, payment_information.currency
+ ),
+ "quantity": 1,
+ }
+ )
+ shipping_amount = payment_information.lines_data.shipping_amount
+ if shipping_amount:
+ goods_lines.append(
+ {
+ "goods_name": "Shipping",
+ "goods_price": format_price(
+ shipping_amount, payment_information.currency
+ ),
+ "quantity": 1,
+ }
+ )
+
+ return goods_lines
+
+
+def get_goods_with_refunds(
+ config: "ApiConfig",
+ payment: Payment,
+ payment_information: PaymentData,
+) -> Tuple[List[dict], Decimal]:
+ """Combine PaymentLinesData and RefundData into NP Atobarai's goods list.
+
+ Used for payment updates.
+ Returns current state of order lines after refunds and total order amount.
+ """
+ goods_lines = []
+ refund_data = payment_information.refund_data or RefundData()
+
+ order = payment.order
+ if not order:
+ raise PaymentError("Cannot refund payment without order.")
+
+ refunded_lines = create_refunded_lines(order, refund_data)
+ refunded_manual_amount = calculate_manual_refund_amount(
+ order, payment_information, refund_data
+ )
+
+ billed_amount = Decimal("0.00")
+ for line in payment_information.lines_data.lines:
+ quantity = line.quantity
+ refunded_quantity = refunded_lines.get(line.variant_id)
+ if refunded_quantity:
+ quantity -= refunded_quantity
+
+ if quantity:
+ goods_lines.append(
+ {
+ "goods_name": _get_goods_name(line, config),
+ "goods_price": format_price(
+ line.amount, payment_information.currency
+ ),
+ "quantity": quantity,
+ }
+ )
+ billed_amount += line.amount * quantity
+
+ goods_lines.extend(_get_voucher_and_shipping_goods(config, payment_information))
+ billed_amount += payment_information.lines_data.shipping_amount
+ billed_amount += payment_information.lines_data.voucher_amount
+
+ if refunded_manual_amount:
+ goods_lines.append(
+ {
+ "goods_name": "Discount",
+ "goods_price": format_price(
+ -refunded_manual_amount, payment_information.currency
+ ),
+ "quantity": 1,
+ }
+ )
+ billed_amount -= refunded_manual_amount
+
+ return goods_lines, billed_amount
+
+
+def get_goods(config: "ApiConfig", payment_information: PaymentData) -> List[dict]:
+ """Convert PaymentLinesData into NP Atobarai's goods list.
+
+ Used for initial payment registration only.
+ """
+ return [
+ {
+ "quantity": line.quantity,
+ "goods_name": _get_goods_name(line, config),
+ "goods_price": format_price(line.amount, payment_information.currency),
+ }
+ for line in payment_information.lines_data.lines
+ ] + _get_voucher_and_shipping_goods(config, payment_information)
+
+
+def cancel(config: "ApiConfig", transaction_id: str) -> NPResponse:
+ data = {"transactions": [{"np_transaction_id": transaction_id}]}
+ return np_request(config, "patch", "/transactions/cancel", json=data)
+
+
+def register(
+ config: "ApiConfig",
+ payment_information: "PaymentData",
+ billed_amount: 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": format_name(billing),
+ "company_name": billing.company_name,
+ "zip_code": billing.postal_code,
+ "address": formatted_billing,
+ "tel": billing.phone.replace("+81", "0"),
+ "email": payment_information.customer_email,
+ },
+ "dest_customer": {
+ "customer_name": format_name(shipping),
+ "company_name": shipping.company_name,
+ "zip_code": shipping.postal_code,
+ "address": formatted_shipping,
+ "tel": shipping.phone.replace("+81", "0"),
+ },
+ "goods": goods,
+ },
+ ]
+ }
+
+ return np_request(config, "post", "/transactions", json=data)
+
+
+def report(
+ config: "ApiConfig",
+ shipping_company_code: 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..549dd58a8d
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/api_types.py
@@ -0,0 +1,71 @@
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Dict, List, NamedTuple, Optional
+
+from .const import (
+ FILL_MISSING_ADDRESS,
+ MERCHANT_CODE,
+ NP_TEST_URL,
+ NP_URL,
+ SHIPPING_COMPANY,
+ SKU_AS_NAME,
+ SP_CODE,
+ TERMINAL_ID,
+ USE_SANDBOX,
+)
+
+
+class NPResponse(NamedTuple):
+ result: dict
+ error_codes: List[str]
+
+
+def error_np_response(error_message: str) -> NPResponse:
+ return NPResponse({}, [error_message])
+
+
+@dataclass
+class ApiConfig:
+ url: str
+ fill_missing_address: bool
+ merchant_code: str
+ terminal_id: str
+ sp_code: str
+ shipping_company: str
+ sku_as_name: bool
+
+
+class PaymentStatus(str, Enum):
+ SUCCESS = "00"
+ PENDING = "10"
+ FAILED = "20"
+ FOR_REREGISTRATION = "RE"
+
+
+@dataclass
+class PaymentResult:
+ status: PaymentStatus
+ psp_reference: Optional[str] = None
+ raw_response: Dict[str, str] = field(default_factory=dict)
+ errors: List[str] = field(default_factory=list)
+
+
+def error_payment_result(error_message: str) -> PaymentResult:
+ return PaymentResult(status=PaymentStatus.FAILED, errors=[error_message])
+
+
+def errors_payment_result(errors: List[str]) -> PaymentResult:
+ return PaymentResult(status=PaymentStatus.FAILED, errors=errors)
+
+
+def get_api_config(connection_params: dict) -> ApiConfig:
+ url = NP_TEST_URL if connection_params[USE_SANDBOX] else NP_URL
+ return ApiConfig(
+ url=url,
+ fill_missing_address=connection_params[FILL_MISSING_ADDRESS],
+ merchant_code=connection_params[MERCHANT_CODE],
+ sp_code=connection_params[SP_CODE],
+ terminal_id=connection_params[TERMINAL_ID],
+ shipping_company=connection_params[SHIPPING_COMPANY],
+ sku_as_name=connection_params[SKU_AS_NAME],
+ )
diff --git a/saleor/payment/gateways/np_atobarai/const.py b/saleor/payment/gateways/np_atobarai/const.py
new file mode 100644
index 0000000000..5a8197315a
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/const.py
@@ -0,0 +1,46 @@
+# This integration is currently supporting the settlement type 02 - NP Atobarai
+NP_ATOBARAI = "02"
+NP_ATOBARAI_WIZ = "03"
+
+# NetProtections recommends a timeout of around 30s
+REQUEST_TIMEOUT = 30
+
+NP_PLUGIN_ID = "saleor.payments.np-atobarai"
+
+NP_TEST_URL = "https://ctcp.np-payment-gateway.com/v1"
+NP_URL = "https://cp.np-payment-gateway.com/v1"
+
+MERCHANT_CODE = "merchant_code"
+FILL_MISSING_ADDRESS = "fill_missing_address"
+SP_CODE = "sp_code"
+TERMINAL_ID = "terminal_id"
+USE_SANDBOX = "use_sandbox"
+SHIPPING_COMPANY = "shipping_company"
+SKU_AS_NAME = "sku_in_invoice"
+
+SHIPPING_COMPANY_CODES = [
+ "50000",
+ "59010",
+ "59020",
+ "59030",
+ "59040",
+ "59041",
+ "59042",
+ "59043",
+ "59050",
+ "59060",
+ "59080",
+ "59090",
+ "59110",
+ "59140",
+ "59150",
+ "59100",
+ "59160",
+ "55555",
+]
+
+PRE_FULFILLMENT_ERROR_CODE = "E0100115"
+ALREADY_REREGISTERED_ERROR_CODE = "E0131006"
+EXCEEDED_NUMBER_OF_REREGISTRATIONS_ERROR_CODE = "E0131011"
+
+SHIPPING_COMPANY_CODE_METADATA_KEY = "np-atobarai.pd-company-code"
diff --git a/saleor/payment/gateways/np_atobarai/errors.py b/saleor/payment/gateways/np_atobarai/errors.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..62bd5a05cb
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/plugin.py
@@ -0,0 +1,214 @@
+from typing import TYPE_CHECKING
+
+from django.core.exceptions import ValidationError
+
+from ....order.models import Fulfillment
+from ....plugins.base_plugin import BasePlugin, ConfigurationTypeField
+from ....plugins.error_codes import PluginErrorCode
+from ...interface import GatewayConfig
+from . import capture, process_payment, refund, tracking_number_updated, void
+from .api_helpers import health_check
+from .api_types import get_api_config
+from .const import (
+ FILL_MISSING_ADDRESS,
+ MERCHANT_CODE,
+ NP_PLUGIN_ID,
+ SHIPPING_COMPANY,
+ SHIPPING_COMPANY_CODES,
+ SKU_AS_NAME,
+ SP_CODE,
+ TERMINAL_ID,
+ USE_SANDBOX,
+)
+from .utils import np_atobarai_opentracing_trace
+
+GATEWAY_NAME = "NP後払い"
+
+REQUIRED_FIELDS = (MERCHANT_CODE, SP_CODE, TERMINAL_ID, SHIPPING_COMPANY)
+
+if TYPE_CHECKING:
+ # flake8: noqa
+ from ....plugins.models import PluginConfiguration
+ from . import GatewayResponse, PaymentData
+
+
+class NPAtobaraiGatewayPlugin(BasePlugin):
+ PLUGIN_ID = NP_PLUGIN_ID
+ PLUGIN_NAME = GATEWAY_NAME
+ CONFIGURATION_PER_CHANNEL = True
+ SUPPORTED_CURRENCIES = "JPY"
+
+ DEFAULT_CONFIGURATION = [
+ {"name": MERCHANT_CODE, "value": None},
+ {"name": SP_CODE, "value": None},
+ {"name": TERMINAL_ID, "value": None},
+ {"name": USE_SANDBOX, "value": True},
+ {"name": FILL_MISSING_ADDRESS, "value": True},
+ {"name": SHIPPING_COMPANY, "value": "50000"},
+ {"name": SKU_AS_NAME, "value": False},
+ ]
+
+ CONFIG_STRUCTURE = {
+ MERCHANT_CODE: {
+ "type": ConfigurationTypeField.SECRET,
+ "help_text": "Provide NP後払い Merchant Code.",
+ "label": "Merchant Code",
+ },
+ SP_CODE: {
+ "type": ConfigurationTypeField.SECRET,
+ "help_text": "Provide NP後払い SP Code.",
+ "label": "SP Code",
+ },
+ TERMINAL_ID: {
+ "type": ConfigurationTypeField.SECRET,
+ "help_text": "Provide NP後払い Terminal ID.",
+ "label": "Terminal ID",
+ },
+ USE_SANDBOX: {
+ "type": ConfigurationTypeField.BOOLEAN,
+ "help_text": "Determines if Saleor should use NP後払い sandbox API.",
+ "label": "Use sandbox",
+ },
+ FILL_MISSING_ADDRESS: {
+ "type": ConfigurationTypeField.BOOLEAN,
+ "help_text": (
+ "Determines if Saleor should generate missing "
+ "AddressData.city and AddressData.city_area"
+ ),
+ "label": "Fill missing address",
+ },
+ SHIPPING_COMPANY: {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "Determines shipping company used in fulfillment report.",
+ "label": "Shipping company",
+ },
+ SKU_AS_NAME: {
+ "type": ConfigurationTypeField.BOOLEAN,
+ "help_text": (
+ "Determines whether product sku or variant name will be used in NP."
+ ),
+ "label": "Product SKU as name",
+ },
+ }
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.config = GatewayConfig(
+ gateway_name=GATEWAY_NAME,
+ auto_capture=False,
+ supported_currencies=self.SUPPORTED_CURRENCIES,
+ connection_params={
+ MERCHANT_CODE: configuration[MERCHANT_CODE],
+ SP_CODE: configuration[SP_CODE],
+ TERMINAL_ID: configuration[TERMINAL_ID],
+ USE_SANDBOX: configuration[USE_SANDBOX],
+ FILL_MISSING_ADDRESS: configuration[FILL_MISSING_ADDRESS],
+ SHIPPING_COMPANY: configuration[SHIPPING_COMPANY],
+ SKU_AS_NAME: configuration[SKU_AS_NAME],
+ },
+ )
+
+ def _get_gateway_config(self) -> GatewayConfig:
+ return self.config
+
+ def capture_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ return capture(
+ payment_information,
+ get_api_config(self._get_gateway_config().connection_params),
+ )
+
+ def refund_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ return refund(
+ payment_information,
+ get_api_config(self._get_gateway_config().connection_params),
+ )
+
+ def void_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ return void(
+ payment_information,
+ get_api_config(self._get_gateway_config().connection_params),
+ )
+
+ def process_payment(
+ self, payment_information: "PaymentData", previous_value
+ ) -> "GatewayResponse":
+ return process_payment(
+ payment_information,
+ get_api_config(self._get_gateway_config().connection_params),
+ )
+
+ def tracking_number_updated(self, fulfillment: "Fulfillment", previous_value):
+ tracking_number_updated(
+ fulfillment, get_api_config(self._get_gateway_config().connection_params)
+ )
+
+ def get_supported_currencies(self, previous_value):
+ return self.SUPPORTED_CURRENCIES
+
+ def token_is_required_as_payment_input(self, previous_value):
+ return False
+
+ @classmethod
+ def validate_authentication(cls, plugin_configuration: "PluginConfiguration"):
+ 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", **kwargs
+ ):
+ """Validate if provided configuration is correct."""
+ if not plugin_configuration.active:
+ return
+
+ configuration = plugin_configuration.configuration
+ configuration = {item["name"]: item["value"] for item in configuration}
+ missing_fields = [
+ field for field in REQUIRED_FIELDS if not configuration[field]
+ ]
+
+ if missing_fields:
+ raise ValidationError(
+ {
+ field: ValidationError(
+ 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..aba02930c0
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/conftest.py
@@ -0,0 +1,105 @@
+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, PaymentLinesData
+from ..api_types 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 PaymentLinesData(
+ lines=[
+ PaymentLineData(
+ amount=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)
+ ],
+ shipping_amount=Decimal("120.00"),
+ voucher_amount=Decimal("-10.00"),
+ )
+
+
+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_data=_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..ee8525b57f
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api.py
@@ -0,0 +1,820 @@
+import logging
+from decimal import Decimal
+from unittest.mock import ANY, Mock, patch
+
+import pytest
+import requests
+from graphene import Node
+
+from .... import PaymentError
+from .. import PaymentStatus, api, const
+from ..api_helpers import format_price, get_goods_with_refunds
+from ..api_types import NPResponse, PaymentResult
+from ..errors import (
+ NO_PSP_REFERENCE,
+ NO_TRACKING_NUMBER,
+ NP_CONNECTION_ERROR,
+ SHIPPING_COMPANY_CODE_INVALID,
+)
+from ..plugin import NPAtobaraiGatewayPlugin
+
+
+@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_data.psp_reference = 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):
+ # 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 = PaymentResult(
+ status=PaymentStatus.FOR_REREGISTRATION
+ )
+ new_psp_reference = "new_psp_reference"
+ response = Mock(
+ spec=requests.Response,
+ status_code=200,
+ json=Mock(
+ return_value={
+ "results": [
+ {
+ "base_np_transaction_id": payment_dummy.psp_reference,
+ "np_transaction_id": new_psp_reference,
+ }
+ ]
+ }
+ ),
+ )
+ mocked_request.return_value = response
+
+ # when
+ gateway_response = plugin.refund_payment(payment_data, None)
+
+ # then
+ assert gateway_response.is_success
+ assert gateway_response.psp_reference == new_psp_reference
+
+
+@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
+ payment_graphql_id = Node.to_global_id("Payment", payment_np.id)
+ mocked_notify_dashboard.assert_called_once_with(
+ order, f"Payment with id {payment_graphql_id} was captured"
+ )
+ assert not caplog.record_tuples
+
+
+@patch("saleor.payment.gateways.np_atobarai.notify_dashboard")
+@patch("saleor.payment.gateways.np_atobarai.api.report_fulfillment")
+def test_tracking_number_updated_errors(
+ mocked_report_fulfillment,
+ mocked_notify_dashboard,
+ np_atobarai_plugin,
+ payment_np,
+ fulfillment,
+ caplog,
+):
+ # given
+ errors = ["error1", "error2"]
+ plugin = np_atobarai_plugin()
+ result = (errors, False)
+ mocked_report_fulfillment.return_value = result
+ order = fulfillment.order
+ order.payments.add(payment_np)
+
+ # when
+ plugin.tracking_number_updated(fulfillment, None)
+
+ # then
+ payment_graphql_id = Node.to_global_id("Payment", payment_np.id)
+ error = ", ".join(errors)
+ mocked_notify_dashboard.assert_called_once_with(
+ order, f"Error: Cannot capture payment with id {payment_graphql_id} ({error})"
+ )
+ assert len(caplog.records) == 1
+ assert caplog.records[0].levelno == logging.WARNING
+ assert caplog.records[0].message == (
+ f"Could not capture payment with id {payment_graphql_id} "
+ f"in NP Atobarai: {error}"
+ )
+
+
+@patch("saleor.payment.gateways.np_atobarai.notify_dashboard")
+@patch("saleor.payment.gateways.np_atobarai.api.report_fulfillment")
+def test_tracking_number_updated_already_captured(
+ mocked_report_fulfillment,
+ mocked_notify_dashboard,
+ np_atobarai_plugin,
+ payment_np,
+ fulfillment,
+ caplog,
+):
+ # given
+ plugin = np_atobarai_plugin()
+ result = ([], True)
+ mocked_report_fulfillment.return_value = result
+ order = fulfillment.order
+ order.payments.add(payment_np)
+
+ # when
+ plugin.tracking_number_updated(fulfillment, None)
+
+ # then
+ payment_graphql_id = Node.to_global_id("Payment", payment_np.id)
+ mocked_notify_dashboard.assert_called_once_with(
+ order,
+ f"Error: Payment with id {payment_graphql_id} was already captured",
+ )
+ assert len(caplog.records) == 1
+ assert caplog.records[0].levelno == logging.WARNING
+ assert (
+ caplog.records[0].message
+ == f"Payment with id {payment_graphql_id} was already captured"
+ )
+
+
+@patch("saleor.payment.gateways.np_atobarai.notify_dashboard")
+@patch("saleor.payment.gateways.np_atobarai.api.report_fulfillment")
+def test_tracking_number_updated_no_payments(
+ _mocked_report_fulfillment,
+ mocked_notify_dashboard,
+ np_atobarai_plugin,
+ fulfillment,
+ caplog,
+):
+ # given
+ plugin = np_atobarai_plugin()
+ order = fulfillment.order
+
+ # when
+ plugin.tracking_number_updated(fulfillment, None)
+
+ # then
+ mocked_notify_dashboard.assert_called_once_with(
+ order, "No active payments for this order"
+ )
+ assert len(caplog.records) == 1
+ assert caplog.records[0].levelno == logging.WARNING
+ assert caplog.records[0].message == ("No active payments for this order")
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_change_transaction_success(
+ mocked_request, config, payment_dummy, np_payment_data
+):
+ # given
+ 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, Mock(), Decimal("12.34")
+ )
+
+ # 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
+ 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, Mock(), Decimal("12.34")
+ )
+
+ # 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
+ 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, Mock(), Decimal("12.34")
+ )
+
+ # then
+ assert payment_response.status == PaymentStatus.FOR_REREGISTRATION
+
+
+@patch("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_change_transaction_failed(
+ mocked_request, config, payment_dummy, np_payment_data
+):
+ # given
+ 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, Mock(), Decimal("12.34")
+ )
+
+ # then
+ assert payment_response.status == PaymentStatus.FAILED
+ assert payment_response.errors
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.report")
+@patch("saleor.payment.gateways.np_atobarai.api.register")
+@patch("saleor.payment.gateways.np_atobarai.api.cancel")
+def test_reregister_transaction_success(
+ mocked_cancel,
+ mocked_register,
+ mocked_report,
+ config,
+ payment_dummy,
+ np_payment_data,
+):
+ # given
+ tracking_number = "123"
+ shipping_company_code = "50000"
+ payment_dummy.psp_reference = "123"
+ new_psp_reference = "234"
+ mocked_cancel.return_value = NPResponse(result={}, error_codes=[])
+ mocked_register.return_value = NPResponse(
+ result={
+ "np_transaction_id": new_psp_reference,
+ },
+ error_codes=[],
+ )
+ mocked_report.return_value = NPResponse(result={}, error_codes=[])
+
+ # when
+ goods, billed_amount = get_goods_with_refunds(
+ config, payment_dummy, np_payment_data
+ )
+ payment_response = api.reregister_transaction_for_partial_return(
+ config,
+ payment_dummy,
+ np_payment_data,
+ shipping_company_code,
+ tracking_number,
+ goods,
+ billed_amount,
+ )
+
+ # then
+ mocked_cancel.assert_called_once_with(config, payment_dummy.psp_reference)
+ mocked_register.assert_called_once_with(
+ config,
+ np_payment_data,
+ int(format_price(billed_amount, np_payment_data.currency)),
+ goods,
+ )
+ mocked_report.assert_called_once_with(
+ config, shipping_company_code, new_psp_reference, tracking_number
+ )
+ assert payment_response.status == PaymentStatus.SUCCESS
+ assert payment_response.psp_reference == new_psp_reference
+
+
+def test_reregister_transaction_no_psp_reference(payment_dummy, np_payment_data):
+ # when
+ payment_response = api.reregister_transaction_for_partial_return(
+ Mock(),
+ payment_dummy,
+ np_payment_data,
+ Mock(),
+ Mock(),
+ Mock(),
+ Decimal("12.34"),
+ )
+
+ # then
+ assert payment_response.status == PaymentStatus.FAILED
+ assert payment_response.errors == [f"TR#{NO_PSP_REFERENCE}"]
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.cancel")
+def test_reregister_transaction_cancel_error(
+ mocked_cancel, config, payment_dummy, np_payment_data
+):
+ # given
+ payment_dummy.psp_reference = "123"
+ error_codes = ["1", "2", "3"]
+ mocked_cancel.return_value = NPResponse(result={}, error_codes=error_codes)
+
+ # when
+ payment_response = api.reregister_transaction_for_partial_return(
+ config, payment_dummy, np_payment_data, Mock(), Mock(), Mock(), Decimal("12.34")
+ )
+
+ # then
+ assert payment_response.status == PaymentStatus.FAILED
+ assert payment_response.errors == [f"TC#{code}" for code in error_codes]
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.report")
+@patch("saleor.payment.gateways.np_atobarai.api.register")
+@patch("saleor.payment.gateways.np_atobarai.api.cancel")
+def test_reregister_transaction_report_error(
+ mocked_cancel,
+ mocked_register,
+ mocked_report,
+ config,
+ payment_dummy,
+ np_payment_data,
+):
+ # given
+ tracking_number = "123"
+ shipping_company_code = "50000"
+ payment_dummy.psp_reference = "123"
+ new_psp_reference = "234"
+ error_codes = ["1", "2", "3"]
+ mocked_cancel.return_value = NPResponse(result={}, error_codes=[])
+ mocked_register.return_value = NPResponse(
+ result={
+ "np_transaction_id": new_psp_reference,
+ },
+ error_codes=[],
+ )
+ mocked_report.return_value = NPResponse(result={}, error_codes=error_codes)
+
+ # when
+ payment_response = api.reregister_transaction_for_partial_return(
+ config,
+ payment_dummy,
+ np_payment_data,
+ shipping_company_code,
+ tracking_number,
+ Mock(),
+ Decimal("12.34"),
+ )
+
+ # then
+ assert payment_response.status == PaymentStatus.FAILED
+ assert payment_response.errors == [f"FR#{code}" for code in error_codes]
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.register")
+@patch("saleor.payment.gateways.np_atobarai.api.cancel")
+def test_reregister_transaction_general_error(
+ mocked_cancel,
+ mocked_register,
+ config,
+ payment_dummy,
+ np_payment_data,
+):
+ # given
+ payment_dummy.psp_reference = "123"
+ mocked_cancel.return_value = NPResponse(result={}, error_codes=[])
+ 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(), Decimal("12.34")
+ )
+
+ # then
+ assert payment_response.status == PaymentStatus.FAILED
+ assert payment_response.errors == [f"TR#{code}" for code in error_codes]
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.cancel")
+@patch("saleor.payment.gateways.np_atobarai.api.register")
+def test_register_transaction_pending(
+ mocked_register, mocked_cancel, config, np_payment_data
+):
+ # given
+ transaction_id = "123123123"
+ errors = ["RE009", "RE015"]
+ register_result = {
+ "authori_result": "10",
+ "np_transaction_id": transaction_id,
+ "authori_hold": errors,
+ }
+ mocked_register.return_value = NPResponse(result=register_result, error_codes=[])
+ mocked_cancel.return_value = NPResponse(result={}, error_codes=[])
+
+ # when
+ payment_response = api.register_transaction(config, np_payment_data)
+
+ # then
+ mocked_register.assert_called_once()
+ mocked_cancel.assert_called_once_with(config, transaction_id)
+ assert payment_response.status == PaymentStatus.PENDING
+ assert payment_response.errors == [f"TR#{e}" for e in errors]
+
+
+@patch("saleor.payment.gateways.np_atobarai.api.cancel")
+@patch("saleor.payment.gateways.np_atobarai.api.register")
+def test_register_transaction_pending_unrecoverable(
+ mocked_register, mocked_cancel, config, np_payment_data, caplog
+):
+ # given
+ transaction_id = "123123123"
+ errors = ["RE009", "RE015"]
+ register_result = {
+ "authori_result": "10",
+ "np_transaction_id": transaction_id,
+ "authori_hold": errors,
+ }
+ mocked_register.return_value = NPResponse(result=register_result, error_codes=[])
+ cancel_errors = ["1", "2", "3"]
+ mocked_cancel.return_value = NPResponse(result={}, error_codes=cancel_errors)
+
+ # when
+ payment_response = api.register_transaction(config, np_payment_data)
+
+ # then
+ mocked_register.assert_called_once()
+ mocked_cancel.assert_called_once_with(config, transaction_id)
+ assert payment_response.status == PaymentStatus.PENDING
+ assert payment_response.errors == [f"TR#{e}" for e in errors]
+ assert caplog.record_tuples == [(ANY, logging.ERROR, ANY)]
+
+
+def test_cancel_transaction_no_payment(np_payment_data):
+ # given
+ np_payment_data.psp_reference = ""
+
+ # when
+ payment_response = api.cancel_transaction(Mock(), np_payment_data)
+
+ # then
+ assert payment_response.errors == [f"TC#{NO_PSP_REFERENCE}"]
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py b/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py
new file mode 100644
index 0000000000..feb776f1a1
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_api_helpers.py
@@ -0,0 +1,271 @@
+from dataclasses import fields
+from decimal import Decimal
+from unittest.mock import DEFAULT, Mock, patch, sentinel
+
+import pytest
+from posuto import Posuto
+
+from ....interface import AddressData, RefundData
+from ....utils import price_to_minor_unit
+from .. import api_helpers, errors
+from ..api_helpers import get_goods, get_goods_with_refunds
+
+
+def test_register_no_billing_address(config, np_payment_data):
+ # given
+ np_payment_data.billing = None
+
+ # when
+ np_response = api_helpers.register(config, np_payment_data)
+
+ # then
+ assert not np_response.result
+ assert np_response.error_codes == [f"{errors.NO_BILLING_ADDRESS}"]
+
+
+def test_register_no_shipping_address(config, np_payment_data):
+ # given
+ np_payment_data.shipping = None
+
+ # when
+ np_response = api_helpers.register(config, np_payment_data)
+
+ # then
+ assert not np_response.result
+ assert np_response.error_codes == [f"{errors.NO_SHIPPING_ADDRESS}"]
+
+
+INVALID = sentinel.INVALID
+
+
+def format_address_side_effect(config, address):
+ return None if address is INVALID else DEFAULT
+
+
+@patch(
+ "saleor.payment.gateways.np_atobarai.api_helpers.format_address",
+ new=Mock(side_effect=format_address_side_effect),
+)
+@patch("saleor.payment.gateways.np_atobarai.api_helpers._request", new=Mock())
+def test_register_invalid_billing_address(config, np_payment_data):
+ # given
+ np_payment_data.billing = INVALID
+
+ # when
+ np_response = api_helpers.register(config, np_payment_data)
+
+ # then
+ assert not np_response.result
+ assert np_response.error_codes == [f"{errors.BILLING_ADDRESS_INVALID}"]
+
+
+@patch(
+ "saleor.payment.gateways.np_atobarai.api_helpers.format_address",
+ new=Mock(side_effect=format_address_side_effect),
+)
+@patch("saleor.payment.gateways.np_atobarai.api_helpers._request", new=Mock())
+def test_register_invalid_shipping_address(config, np_payment_data):
+ # given
+ np_payment_data.shipping = INVALID
+
+ # when
+ np_response = api_helpers.register(config, np_payment_data)
+
+ # then
+ assert not np_response.result
+ assert np_response.error_codes == [f"{errors.SHIPPING_ADDRESS_INVALID}"]
+
+
+def test_format_name(np_address_data):
+ # given
+ double_byte_space = "\u3000"
+
+ # when
+ formatted_name = api_helpers.format_name(np_address_data)
+
+ # then
+ assert formatted_name == (
+ f"{np_address_data.last_name}"
+ 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.amount, np_payment_data.currency)
+ ),
+ "quantity": line.quantity,
+ }
+ for line in np_payment_data.lines_data.lines
+ ] + [
+ {
+ "goods_name": "Voucher",
+ "goods_price": int(
+ price_to_minor_unit(
+ np_payment_data.lines_data.voucher_amount, np_payment_data.currency
+ )
+ ),
+ "quantity": 1,
+ },
+ {
+ "goods_name": "Shipping",
+ "goods_price": int(
+ price_to_minor_unit(
+ np_payment_data.lines_data.shipping_amount, np_payment_data.currency
+ )
+ ),
+ "quantity": 1,
+ },
+ ]
+
+
+ "refund_amount, discount_goods",
+ [
+ (None, []),
+ (
+ Decimal("5.00"),
+ [{"goods_name": "Discount", "goods_price": -500, "quantity": 1}],
+ ),
+ ],
+)
[email protected]("sku_as_name", [True, False])
+def test_get_goods_with_refunds(
+ config,
+ payment_dummy,
+ np_payment_data,
+ sku_as_name,
+ refund_amount,
+ discount_goods,
+):
+ # given
+ config.sku_as_name = sku_as_name
+ np_payment_data.amount = refund_amount
+ np_payment_data.refund_data = RefundData(
+ refund_amount_is_automatically_calculated=False
+ )
+
+ # when
+ goods, billed_amount = get_goods_with_refunds(
+ config, payment_dummy, np_payment_data
+ )
+
+ # then
+ assert (
+ goods
+ == [
+ {
+ "goods_name": line.product_sku if sku_as_name else line.product_name,
+ "goods_price": int(
+ price_to_minor_unit(line.amount, np_payment_data.currency)
+ ),
+ "quantity": line.quantity,
+ }
+ for line in np_payment_data.lines_data.lines
+ ]
+ + [
+ {
+ "goods_name": "Voucher",
+ "goods_price": int(
+ price_to_minor_unit(
+ np_payment_data.lines_data.voucher_amount,
+ np_payment_data.currency,
+ )
+ ),
+ "quantity": 1,
+ },
+ {
+ "goods_name": "Shipping",
+ "goods_price": int(
+ price_to_minor_unit(
+ np_payment_data.lines_data.shipping_amount,
+ np_payment_data.currency,
+ )
+ ),
+ "quantity": 1,
+ },
+ ]
+ + discount_goods
+ )
+ manual_refund_amount = refund_amount or Decimal("0.00")
+ assert (
+ billed_amount
+ == sum(line.amount * line.quantity for line in np_payment_data.lines_data.lines)
+ + np_payment_data.lines_data.voucher_amount
+ + np_payment_data.lines_data.shipping_amount
+ - manual_refund_amount
+ )
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..6f56f00289
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_plugin.py
@@ -0,0 +1,111 @@
+import os
+from unittest.mock import Mock, patch
+
+import pytest
+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
+ )
+
+
+def test_capture_payment(np_atobarai_plugin):
+ # given
+ plugin = np_atobarai_plugin()
+
+ # then
+ with pytest.raises(NotImplementedError):
+ # when
+ plugin.capture_payment(Mock(), None)
+
+
+def test_void_payment(np_atobarai_plugin):
+ # given
+ plugin = np_atobarai_plugin()
+
+ # then
+ with pytest.raises(NotImplementedError):
+ # when
+ plugin.void_payment(Mock(), None)
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py b/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
new file mode 100644
index 0000000000..b5fa3be723
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_plugin_configuration.py
@@ -0,0 +1,81 @@
+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
+
+
[email protected]("saleor.payment.gateways.np_atobarai.api_helpers.requests.request")
+def test_validate_plugin_configuration_inactive(mocked_request, np_atobarai_plugin):
+ # given
+ plugin = np_atobarai_plugin(active=False)
+
+ # when
+ NPAtobaraiGatewayPlugin.validate_plugin_configuration(plugin)
+
+ # then
+ mocked_request.assert_not_called()
diff --git a/saleor/payment/gateways/np_atobarai/tests/test_utils.py b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
new file mode 100644
index 0000000000..eec4736263
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/tests/test_utils.py
@@ -0,0 +1,457 @@
+from decimal import Decimal
+from itertools import chain, zip_longest
+from unittest.mock import Mock, patch
+
+import pytest
+
+from .....order import FulfillmentLineData, FulfillmentStatus, OrderEvents
+from .....order.actions import create_refund_fulfillment
+from .....order.fetch import OrderLineInfo
+from .....plugins.manager import get_plugins_manager
+from .... import PaymentError
+from ....interface import RefundData
+from .. import get_fulfillment_for_order, get_shipping_company_code, notify_dashboard
+from ..const import SHIPPING_COMPANY_CODE_METADATA_KEY, SHIPPING_COMPANY_CODES
+from ..utils import calculate_manual_refund_amount, create_refunded_lines
+
+
+def test_notify_dashboard(order):
+ # given
+ message = "message"
+
+ # when
+ notify_dashboard(order, message)
+
+ # then
+ event = order.events.first()
+ assert event.type == OrderEvents.EXTERNAL_SERVICE_NOTIFICATION
+ assert event.parameters["message"] == message
+
+
+def test_get_fulfillment_for_order(order):
+ # given
+ expected_fulfillment = order.fulfillments.create(tracking_number="123")
+
+ # when
+ fulfillment = get_fulfillment_for_order(order)
+
+ # then
+ assert expected_fulfillment == fulfillment
+
+
+def test_get_fulfillment_for_order_multiple_fulfillments_one_valid(order):
+ # then
+ expected_fulfillment = order.fulfillments.create(tracking_number="123")
+ order.fulfillments.create(tracking_number="234", status=FulfillmentStatus.REFUNDED)
+
+ # when
+ fulfillment = get_fulfillment_for_order(order)
+
+ # then
+ assert expected_fulfillment == fulfillment
+
+
+def test_get_fulfillment_for_order_no_fulfillment(order):
+ # then
+ with pytest.raises(PaymentError, match=r".* not exist .*"):
+
+ # when
+ get_fulfillment_for_order(order)
+
+
+def test_get_fulfillment_for_order_no_fulfillment_with_tracking_number(order):
+ # given
+ order.fulfillments.create()
+
+ # then
+ with pytest.raises(PaymentError, match=r".* not exist .*"):
+
+ # when
+ get_fulfillment_for_order(order)
+
+
+def test_get_fulfillment_for_order_no_refundable_fulfillment(order):
+ # given
+ order.fulfillments.create(tracking_number="123", status=FulfillmentStatus.REFUNDED)
+
+ # then
+ with pytest.raises(PaymentError, match=r".* not exist .*"):
+
+ # when
+ get_fulfillment_for_order(order)
+
+
+def test_get_fulfillment_for_order_multiple_fulfillments(order, fulfillment):
+ # given
+ order.fulfillments.create(tracking_number="123")
+ order.fulfillments.create(tracking_number="234")
+
+ # then
+ with pytest.raises(PaymentError, match=r"More than one .* exist .*"):
+
+ # when
+ get_fulfillment_for_order(order)
+
+
+ "config_shipping_company_code",
+ SHIPPING_COMPANY_CODES,
+)
+def test_get_shipping_company_code_no_metadata(
+ config, fulfillment, config_shipping_company_code
+):
+ # given
+ config.shipping_company = config_shipping_company_code
+
+ # when
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
+
+ # then
+ assert shipping_company_code == config_shipping_company_code
+
+
+ ["config_shipping_company_code", "result_shipping_company_code"],
+ zip(SHIPPING_COMPANY_CODES + ["invalid_code"], SHIPPING_COMPANY_CODES + [None]),
+)
+def test_get_shipping_company_code_valid_metadata(
+ config, fulfillment, config_shipping_company_code, result_shipping_company_code
+):
+ # given
+ fulfillment.store_value_in_private_metadata(
+ {SHIPPING_COMPANY_CODE_METADATA_KEY: config_shipping_company_code}
+ )
+ fulfillment.save(update_fields=["private_metadata"])
+
+ # when
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
+
+ # then
+ assert shipping_company_code == result_shipping_company_code
+
+
+ "config_shipping_company_code",
+ SHIPPING_COMPANY_CODES,
+)
+def test_get_shipping_company_code_invalid_metadata(
+ config, fulfillment, config_shipping_company_code
+):
+ # given
+ config.shipping_company = config_shipping_company_code
+ fulfillment.store_value_in_private_metadata({"invalid_metadata_key": "50000"})
+ fulfillment.save(update_fields=["private_metadata"])
+
+ # when
+ shipping_company_code = get_shipping_company_code(config, fulfillment)
+
+ # then
+ assert shipping_company_code == config_shipping_company_code
+
+
+def create_refund_fulfillment_helper(payment_dummy):
+ def factory(
+ order,
+ order_lines=None,
+ fulfillment_lines=None,
+ manual_refund_amount=None,
+ refund_shipping_costs=False,
+ ):
+ if manual_refund_amount:
+ payment_dummy.captured_amount = manual_refund_amount
+ payment_dummy.save(update_fields=["captured_amount"])
+ if refund_shipping_costs:
+ payment_dummy.captured_amount = order.shipping_price_gross_amount
+ payment_dummy.save(update_fields=["captured_amount"])
+
+ 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(),
+ amount=manual_refund_amount,
+ refund_shipping_costs=refund_shipping_costs,
+ )
+
+ return factory
+
+
+def test_create_refund_lines_order_lines(order_with_lines):
+ # given
+ order_lines = order_with_lines.lines.all()
+ order_refund_lines = [
+ OrderLineInfo(line=(line := order_lines[0]), quantity=2, variant=line.variant),
+ OrderLineInfo(line=(line := order_lines[1]), quantity=1, variant=line.variant),
+ ]
+ fulfillment_refund_lines = []
+ refund_data = RefundData(
+ order_lines_to_refund=order_refund_lines,
+ fulfillment_lines_to_refund=fulfillment_refund_lines,
+ )
+
+ # when
+ lines = create_refunded_lines(
+ order_with_lines,
+ refund_data,
+ )
+
+ # then
+ assert lines == {line.line.variant_id: line.quantity for line in order_refund_lines}
+
+
+def test_create_refund_lines_fulfillment_lines(fulfilled_order):
+ # 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,
+ ),
+ ]
+ refund_data = RefundData(
+ order_lines_to_refund=order_refund_lines,
+ fulfillment_lines_to_refund=fulfillment_refund_lines,
+ )
+
+ # when
+ lines = create_refunded_lines(
+ fulfilled_order,
+ refund_data,
+ )
+
+ # then
+ assert lines == {
+ line.line.order_line.variant_id: line.quantity
+ for line in fulfillment_refund_lines
+ }
+
+
+@patch("saleor.order.actions.gateway.refund")
[email protected]("previous_refund_shipping_costs", [True, False])
+def test_create_refund_data_previously_refunded_order_lines(
+ _mocked_refund,
+ order_with_lines,
+ create_refund_fulfillment_helper,
+ previous_refund_shipping_costs,
+):
+ # given
+ order_lines = order_with_lines.lines.all()
+ previous_order_refund_lines = [
+ OrderLineInfo(line=(line := order_lines[0]), quantity=1, variant=line.variant)
+ ]
+ create_refund_fulfillment_helper(
+ order_with_lines,
+ order_lines=previous_order_refund_lines,
+ refund_shipping_costs=previous_refund_shipping_costs,
+ )
+ current_order_refund_lines = [
+ OrderLineInfo(line=(line := order_lines[0]), quantity=1, variant=line.variant),
+ OrderLineInfo(line=(line := order_lines[1]), quantity=1, variant=line.variant),
+ ]
+ fulfillment_refund_lines = []
+ refund_data = RefundData(
+ order_lines_to_refund=current_order_refund_lines,
+ fulfillment_lines_to_refund=fulfillment_refund_lines,
+ )
+
+ # when
+ lines = create_refunded_lines(
+ order_with_lines,
+ refund_data,
+ )
+
+ # then
+ order_refund_lines = [
+ OrderLineInfo(line=cl.line, quantity=pl.quantity + cl.quantity)
+ for pl, cl in zip_longest(
+ previous_order_refund_lines,
+ current_order_refund_lines,
+ fillvalue=Mock(spec=OrderLineInfo, quantity=0),
+ )
+ ]
+ assert lines == {line.line.variant_id: line.quantity for line in order_refund_lines}
+
+
+@patch("saleor.order.actions.gateway.refund")
[email protected]("previous_refund_shipping_costs", [True, False])
+def test_create_refund_data_previously_refunded_fulfillment_lines(
+ _mocked_refund,
+ fulfilled_order,
+ create_refund_fulfillment_helper,
+ previous_refund_shipping_costs,
+):
+ # given
+ fulfillment_lines = list(
+ chain.from_iterable(f.lines.all() for f in fulfilled_order.fulfillments.all())
+ )
+ previous_fulfillment_refund_lines = [
+ FulfillmentLineData(line=fulfillment_lines[0], quantity=1)
+ ]
+ create_refund_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,
+ ),
+ ]
+ refund_data = RefundData(
+ order_lines_to_refund=order_refund_lines,
+ fulfillment_lines_to_refund=current_fulfillment_refund_lines,
+ )
+
+ # when
+ lines = create_refunded_lines(
+ fulfilled_order,
+ refund_data,
+ )
+
+ # then
+ fulfillment_refund_lines = [
+ FulfillmentLineData(line=cl.line, quantity=pl.quantity + cl.quantity)
+ for pl, cl in zip_longest(
+ previous_fulfillment_refund_lines,
+ current_fulfillment_refund_lines,
+ fillvalue=Mock(spec=FulfillmentLineData, quantity=0),
+ )
+ ]
+ assert lines == {
+ line.line.order_line.variant_id: line.quantity
+ for line in fulfillment_refund_lines
+ }
+
+
+ [
+ "current_refund_amount",
+ "shipping_amount",
+ "refund_shipping",
+ "is_manual",
+ "order_lines",
+ "fulfillment_lines",
+ "expected_manual_amount",
+ ],
+ [
+ (None, Decimal("40.00"), False, False, [], [], Decimal("0.00")),
+ (Decimal("12.34"), Decimal("40.00"), False, False, [], [], Decimal("12.34")),
+ (None, Decimal("40.00"), True, True, [], [], Decimal("40.00")),
+ (
+ Decimal("12.34"),
+ Decimal("40.00"),
+ False,
+ False,
+ [Mock()],
+ [],
+ Decimal("0.00"),
+ ),
+ (
+ Decimal("12.34"),
+ Decimal("40.00"),
+ False,
+ False,
+ [],
+ [Mock()],
+ Decimal("0.00"),
+ ),
+ ],
+)
+def test_calculate_refund_amount(
+ order,
+ current_refund_amount,
+ shipping_amount,
+ refund_shipping,
+ is_manual,
+ order_lines,
+ fulfillment_lines,
+ expected_manual_amount,
+):
+ # given
+ payment_information = Mock(
+ amount=current_refund_amount,
+ lines_data=Mock(
+ shipping_amount=shipping_amount,
+ ),
+ )
+ refund_data = Mock(
+ refund_shipping_costs=refund_shipping,
+ refund_is_automatically_calculated=not is_manual,
+ order_lines_to_refund=order_lines,
+ fulfillment_lines_to_refund=fulfillment_lines,
+ )
+
+ # when
+ amount = calculate_manual_refund_amount(order, payment_information, refund_data)
+
+ # then
+ assert amount == expected_manual_amount
+
+
+ [
+ "previous_manual_refund_amount",
+ "current_refund_amount",
+ "refund_shipping",
+ "expected_refund_amount",
+ ],
+ [
+ (None, None, False, Decimal("0.00")),
+ (None, None, True, Decimal("12.30")),
+ (None, Decimal("8.00"), False, Decimal("8.00")),
+ (None, Decimal("8.00"), True, Decimal("20.30")),
+ (Decimal("5.00"), None, False, Decimal("5.00")),
+ (Decimal("5.00"), None, True, Decimal("17.30")),
+ (Decimal("5.00"), Decimal("8.00"), False, Decimal("13.00")),
+ (Decimal("5.00"), Decimal("8.00"), True, Decimal("25.30")),
+ ],
+)
+def test_calculate_manual_refund_amount_previously_refunded(
+ order,
+ create_refund_fulfillment_helper,
+ previous_manual_refund_amount,
+ current_refund_amount,
+ refund_shipping,
+ expected_refund_amount,
+):
+ # given
+ if previous_manual_refund_amount:
+ create_refund_fulfillment_helper(
+ order, manual_refund_amount=previous_manual_refund_amount
+ )
+ if refund_shipping:
+ create_refund_fulfillment_helper(
+ order,
+ refund_shipping_costs=refund_shipping,
+ )
+
+ refund_data = Mock(
+ refund_shipping_costs=False,
+ refund_is_automatically_calculated=False,
+ order_lines_to_refund=[],
+ fulfillment_lines_to_refund=[],
+ )
+ payment_information = Mock(amount=current_refund_amount)
+
+ # when
+ refund_amount = calculate_manual_refund_amount(
+ order, payment_information, refund_data
+ )
+ # then
+ assert refund_amount == expected_refund_amount
diff --git a/saleor/payment/gateways/np_atobarai/utils.py b/saleor/payment/gateways/np_atobarai/utils.py
new file mode 100644
index 0000000000..4ba5fd3060
--- /dev/null
+++ b/saleor/payment/gateways/np_atobarai/utils.py
@@ -0,0 +1,162 @@
+from collections import defaultdict
+from contextlib import contextmanager
+from decimal import Decimal
+from itertools import chain
+from typing import Dict, Optional
+
+from django.db.models import Q, Sum
+
+from ....core.tracing import opentracing_trace
+from ....order import FulfillmentStatus
+from ....order.events import external_notification_event
+from ....order.models import Fulfillment, FulfillmentLine, Order
+from ... import PaymentError
+from ...interface import PaymentData, RefundData
+from .api_types import ApiConfig
+from .const import SHIPPING_COMPANY_CODE_METADATA_KEY, SHIPPING_COMPANY_CODES
+
+
+def notify_dashboard(order: Order, message: str):
+ external_notification_event(
+ order=order, user=None, app=None, message=message, parameters=None
+ )
+
+
+STATUSES_NOT_ALLOWED_TO_REFUND = [
+ FulfillmentStatus.CANCELED,
+ FulfillmentStatus.REFUNDED,
+ FulfillmentStatus.REPLACED,
+ FulfillmentStatus.REFUNDED_AND_RETURNED,
+ FulfillmentStatus.RETURNED,
+]
+
+
+def get_shipping_company_code(
+ config: ApiConfig, fulfillment: Fulfillment
+) -> Optional[str]:
+ code = fulfillment.get_value_from_private_metadata(
+ SHIPPING_COMPANY_CODE_METADATA_KEY, default=config.shipping_company
+ )
+ return None if code not in SHIPPING_COMPANY_CODES else code
+
+
+def get_fulfillment_for_order(order: Order) -> Fulfillment:
+ fulfillments = order.fulfillments.exclude(
+ Q(tracking_number="") | Q(status__in=STATUSES_NOT_ALLOWED_TO_REFUND)
+ )
+
+ if fulfillments.count() == 0:
+ raise PaymentError(
+ "Fulfillment with tracking number does not exist for this order"
+ )
+
+ if fulfillments.count() > 1:
+ raise PaymentError(
+ "More than one fulfillment with tracking number exist for this order"
+ )
+
+ return fulfillments[0]
+
+
+@contextmanager
+def np_atobarai_opentracing_trace(span_name: str):
+ with opentracing_trace(
+ span_name=span_name,
+ component_name="payment",
+ service_name="np-atobarai",
+ ):
+ yield
+
+
+def create_refunded_lines(
+ order: Order,
+ refund_data: RefundData,
+) -> Dict[int, int]:
+ """Return all refunded product variants for specified order.
+
+ Takes into account previous refunds and current refund mutation parameters.
+ :return: Dictionary of variant ids and refunded quantities.
+ """
+ if not refund_data.refund_amount_is_automatically_calculated:
+ order_lines_to_refund = []
+ fulfillment_lines_to_refund = []
+ else:
+ order_lines_to_refund = refund_data.order_lines_to_refund
+ fulfillment_lines_to_refund = refund_data.fulfillment_lines_to_refund
+
+ 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, line1.quantity)
+ for line1 in previous_fulfillment_lines
+ if (p_variant_id := line1.order_line.variant_id)
+ )
+ current_order_refund_lines = (
+ (variant.id, line1.quantity)
+ for line1 in order_lines_to_refund
+ if (variant := line1.variant)
+ )
+ current_fulfillment_refund_lines = (
+ (f_variant_id, line1.quantity)
+ for line1 in fulfillment_lines_to_refund
+ if (f_variant_id := line1.line.order_line.variant_id)
+ )
+
+ refund_lines = chain(
+ previous_refund_lines,
+ current_order_refund_lines,
+ current_fulfillment_refund_lines,
+ )
+ summed_refund_lines: Dict[int, int] = defaultdict(int)
+
+ for variant_id, quantity in refund_lines:
+ summed_refund_lines[variant_id] += quantity
+
+ return dict(summed_refund_lines)
+
+
+def calculate_manual_refund_amount(
+ order: Order,
+ payment_information: PaymentData,
+ refund_data: RefundData,
+) -> Decimal:
+ """Return sum of all manual refunds for specified order.
+
+ Takes into account previous refunds and current refund mutation amount.
+ """
+ if (
+ refund_data.order_lines_to_refund or refund_data.fulfillment_lines_to_refund
+ ) and refund_data.refund_amount_is_automatically_calculated:
+ # automatic line refund
+ manual_amount_to_refund = Decimal("0.00")
+ elif (
+ refund_data.refund_shipping_costs
+ and refund_data.refund_amount_is_automatically_calculated
+ ):
+ # automatic shipping refund
+ manual_amount_to_refund = payment_information.lines_data.shipping_amount
+ else:
+ # manual refund
+ manual_amount_to_refund = payment_information.amount or Decimal("0.00")
+
+ previous_manual_amount_to_refund = (
+ order.fulfillments.filter(
+ status__in=[
+ FulfillmentStatus.REFUNDED,
+ FulfillmentStatus.REFUNDED_AND_RETURNED,
+ ],
+ lines__isnull=True,
+ ).aggregate(manual_amount=Sum("total_refund_amount"))["manual_amount"]
+ or Decimal("0.00")
+ )
+
+ return previous_manual_amount_to_refund + manual_amount_to_refund
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 51f37eb46e..184e483085 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -1,7 +1,11 @@
-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
+
+from ..order import FulfillmentLineData
+from ..order.fetch import OrderLineInfo
JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
@@ -66,6 +70,30 @@ class StorePaymentMethodEnum(str, Enum):
OFF_SESSION = "OFF_SESSION"
+@dataclass
+class PaymentLineData:
+ amount: Decimal
+ variant_id: int
+ product_name: str
+ product_sku: Optional[str]
+ quantity: int
+
+
+@dataclass
+class PaymentLinesData:
+ shipping_amount: Decimal
+ voucher_amount: Decimal
+ lines: List[PaymentLineData]
+
+
+@dataclass
+class RefundData:
+ order_lines_to_refund: List[OrderLineInfo] = field(default_factory=list)
+ fulfillment_lines_to_refund: List[FulfillmentLineData] = field(default_factory=list)
+ refund_shipping_costs: bool = False
+ refund_amount_is_automatically_calculated: bool = True
+
+
@dataclass
class PaymentData:
"""Dataclass for storing all payment information.
@@ -94,6 +122,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[RefundData] = None
+ # Optional, lazy-evaluated gateway arguments
+ _resolve_lines_data: InitVar[Callable[[], PaymentLinesData]] = None
+
+ def __post_init__(self, _resolve_lines_data: Callable[[], PaymentLinesData]):
+ self.__resolve_lines_data = _resolve_lines_data
+
+ # Note: this field does not appear in webhook payloads,
+ # because it's not visible to dataclasses.asdict
+ @cached_property
+ def lines_data(self) -> PaymentLinesData:
+ return self.__resolve_lines_data()
@dataclass
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 9c2cf6f68e..50cab7d7ca 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -1,6 +1,165 @@
+from decimal import Decimal
from unittest.mock import patch
-from ..utils import get_channel_slug_from_payment, try_void_or_refund_inactive_payment
+from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ...plugins.manager import get_plugins_manager
+from ..interface import PaymentLineData, PaymentLinesData
+from ..utils import (
+ create_payment_lines_information,
+ get_channel_slug_from_payment,
+ try_void_or_refund_inactive_payment,
+)
+
+
+def test_create_payment_lines_information_order(payment_dummy):
+ # given
+ manager = get_plugins_manager()
+
+ # when
+ payment_lines_data = create_payment_lines_information(payment_dummy, manager)
+
+ # then
+ order = payment_dummy.order
+ assert payment_lines_data.lines == [
+ PaymentLineData(
+ amount=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()
+ ]
+ assert payment_lines_data.shipping_amount == order.shipping_price_gross_amount
+ assert payment_lines_data.voucher_amount == Decimal("0.00")
+
+
+def test_create_payment_lines_information_order_with_voucher(payment_dummy):
+ # given
+ voucher_amount = Decimal("12.30")
+ order = payment_dummy.order
+ order.undiscounted_total_gross_amount += voucher_amount
+ manager = get_plugins_manager()
+
+ # when
+ payment_lines_data = create_payment_lines_information(payment_dummy, manager)
+
+ # then
+ assert payment_lines_data.lines == [
+ PaymentLineData(
+ amount=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()
+ ]
+ assert payment_lines_data.shipping_amount == order.shipping_price_gross_amount
+ assert payment_lines_data.voucher_amount == -voucher_amount
+
+
+def get_expected_checkout_payment_lines(
+ manager, checkout_info, lines, address, discounts
+):
+ expected_payment_lines = []
+
+ for line_info in lines:
+ unit_gross = manager.calculate_checkout_line_unit_price(
+ checkout_info,
+ lines,
+ line_info,
+ address,
+ discounts,
+ ).undiscounted_price.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(
+ amount=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
+
+ return PaymentLinesData(
+ lines=expected_payment_lines,
+ shipping_amount=shipping_gross,
+ voucher_amount=Decimal("0.00"),
+ )
+
+
+def test_create_payment_lines_information_checkout(payment_dummy, checkout_with_items):
+ # given
+ manager = get_plugins_manager()
+ payment_dummy.order = None
+ payment_dummy.checkout = checkout_with_items
+
+ # when
+ payment_lines = create_payment_lines_information(payment_dummy, manager)
+
+ # then
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ discounts = []
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, discounts, manager)
+ address = checkout_with_items.shipping_address
+ expected_payment_lines = get_expected_checkout_payment_lines(
+ manager, checkout_info, lines, address, discounts
+ )
+
+ assert payment_lines == expected_payment_lines
+
+
+def test_create_payment_lines_information_checkout_with_voucher(
+ payment_dummy, checkout_with_items
+):
+ # given
+ manager = get_plugins_manager()
+ voucher_amount = Decimal("12.30")
+ payment_dummy.order = None
+ checkout_with_items.discount_amount = voucher_amount
+ payment_dummy.checkout = checkout_with_items
+
+ # when
+ payment_lines = create_payment_lines_information(payment_dummy, manager)
+
+ # then
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ discounts = []
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, discounts, manager)
+ address = checkout_with_items.shipping_address
+ expected_payment_lines_data = get_expected_checkout_payment_lines(
+ manager, checkout_info, lines, address, discounts
+ )
+
+ expected_payment_lines_data.voucher_amount = -voucher_amount
+
+ assert payment_lines == expected_payment_lines_data
+
+
+def test_create_payment_lines_information_invalid_payment(payment_dummy):
+ # given
+ manager = get_plugins_manager()
+ payment_dummy.order = None
+
+ # when
+ payment_lines_data = create_payment_lines_information(payment_dummy, manager)
+
+ # then
+ assert not payment_lines_data.lines
+ assert not payment_lines_data.shipping_amount
+ assert not payment_lines_data.voucher_amount
def test_get_channel_slug_from_payment_with_order(payment_dummy):
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index c6e168d0d9..1bdaf6c0e7 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,7 +1,7 @@
import json
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, List, Optional, cast
+from typing import Dict, List, Optional, cast
import graphene
from babel.numbers import get_currency_precision
@@ -9,10 +9,13 @@ from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Q
from ..account.models import User
+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 ..discount.utils import fetch_active_discounts
from ..order.models import Order
+from ..plugins.manager import PluginsManager, get_plugins_manager
from . import (
ChargeStatus,
GatewayError,
@@ -26,27 +29,124 @@ from .interface import (
AddressData,
GatewayResponse,
PaymentData,
+ PaymentLineData,
+ PaymentLinesData,
PaymentMethodInfo,
+ RefundData,
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,
+) -> PaymentLinesData:
+ checkout = payment.checkout
+ order = payment.order
+
+ if checkout:
+ return create_checkout_payment_lines_information(checkout, manager)
+ elif order:
+ return create_order_payment_lines_information(order)
+
+ return PaymentLinesData(
+ shipping_amount=Decimal("0.00"),
+ voucher_amount=Decimal("0.00"),
+ lines=[],
+ )
+
+
+def create_checkout_payment_lines_information(
+ checkout: Checkout, manager: PluginsManager
+) -> PaymentLinesData:
+ line_items = []
+ lines, _ = fetch_checkout_lines(checkout)
+ discounts = fetch_active_discounts()
+ checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)
+ address = checkout_info.shipping_address or checkout_info.billing_address
+
+ for line_info in lines:
+ unit_price = manager.calculate_checkout_line_unit_price(
+ checkout_info,
+ lines,
+ line_info,
+ address,
+ discounts,
+ )
+ unit_gross = unit_price.price_with_sale.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,
+ amount=unit_gross,
+ )
+ )
+ shipping_amount = manager.calculate_checkout_shipping(
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ ).gross.amount
+
+ voucher_amount = -checkout.discount_amount
+
+ return PaymentLinesData(
+ shipping_amount=shipping_amount,
+ voucher_amount=voucher_amount,
+ lines=line_items,
+ )
+
+
+def create_order_payment_lines_information(order: Order) -> PaymentLinesData:
+ line_items = []
+ for order_line in order.lines.all():
+ product_name = f"{order_line.product_name}, {order_line.variant_name}"
+
+ variant_id = order_line.variant_id
+ if variant_id is None:
+ continue
+
+ line_items.append(
+ PaymentLineData(
+ quantity=order_line.quantity,
+ product_name=product_name,
+ product_sku=order_line.product_sku,
+ variant_id=variant_id,
+ amount=order_line.unit_price_gross_amount,
+ )
+ )
+
+ shipping_amount = order.shipping_price_gross_amount
+ voucher_amount = order.total_gross_amount - order.undiscounted_total_gross_amount
+
+ return PaymentLinesData(
+ shipping_amount=shipping_amount,
+ voucher_amount=voucher_amount,
+ lines=line_items,
+ )
+
+
def create_payment_information(
payment: Payment,
payment_token: str = None,
amount: Decimal = None,
customer_id: str = None,
store_source: bool = False,
+ refund_data: Optional[RefundData] = None,
additional_data: Optional[dict] = None,
+ manager: Optional[PluginsManager] = None,
) -> PaymentData:
"""Extract order information along with payment details.
@@ -108,6 +208,10 @@ def create_payment_information(
checkout_metadata=checkout_metadata,
payment_metadata=payment.metadata,
psp_reference=payment.psp_reference,
+ refund_data=refund_data,
+ _resolve_lines_data=lambda: create_payment_lines_information(
+ payment, manager or get_plugins_manager()
+ ),
)
diff --git a/saleor/plugins/admin_email/plugin.py b/saleor/plugins/admin_email/plugin.py
index f3a56be926..4804c1464b 100644
--- a/saleor/plugins/admin_email/plugin.py
+++ b/saleor/plugins/admin_email/plugin.py
@@ -260,7 +260,7 @@ class AdminEmailPlugin(BasePlugin):
return previous_value
if event not in event_map:
- logger.warning(f"Missing handler for event {event}")
+ logger.warning("Missing handler for event %s", event)
return previous_value
template_map = get_admin_template_map(self.templates)
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 7a4fbbbb72..cb753c608e 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -526,6 +526,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 10d758b0bc..a97a5cde7d 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -736,6 +736,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 0dcdba1b0e..78a0cd3745 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -598,6 +598,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",