Skip to content

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

Transaction mutations for new checkout flow (#9564)

Maciej Korycinskidf31433d96cd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 389158c135..bc79b6b3fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,16 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
- Fix for sending incorrect prices to Avatax - #9633 by @korycins
+- PREVIEW_FEATURE: Add mutations for managing a payment transaction attached to order/checkout. - #9564 by @korycins
+ - add fields:
+ - `order.transactions`
+ - `checkout.transactions`
+ - add mutations:
+ - `transactionCreate`
+ - `transactionUpdate`
+ - `transactionRequestAction`
+ - add new webhook event:
+ - `TRANSACTION_ACTION_REQUEST`
# 3.3.1
@@ -20,6 +30,8 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
+- Fix filtering product attributes by date range - #9543 by @IKarbowiak
+- Fix for raising Permission Denied when anonymous user calls `checkout.customer` field - #9573 by @korycins
- Use fulltext search for products (#9344) (4b6f25964) by @patrys
- Precise timestamps for publication dates - #9581 by @IKarbowiak
- Change `publicationDate` fields to `publishedAt` date time fields.
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 02eacf2ce3..b1f75f22c3 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -1055,6 +1055,7 @@ def _create_order_from_checkout(
# payments
checkout_info.checkout.payments.update(order=order, checkout_id=None)
+ checkout_info.checkout.payment_transactions.update(order=order, checkout_id=None)
# order search
order.search_document = prepare_order_search_document_value(order)
diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.py
index 6b15ea7bf9..b053e6992e 100644
--- a/saleor/graphql/checkout/dataloaders.py
+++ b/saleor/graphql/checkout/dataloaders.py
@@ -10,6 +10,7 @@ from ...checkout.fetch import (
update_delivery_method_lists_for_checkout_info,
)
from ...checkout.models import Checkout, CheckoutLine
+from ...payment.models import TransactionItem
from ..account.dataloaders import AddressByIdLoader, UserByUserIdLoader
from ..core.dataloaders import DataLoader
from ..discount.dataloaders import VoucherByCodeLoader
@@ -323,3 +324,16 @@ class CheckoutLinesByCheckoutTokenLoader(DataLoader):
for line in lines.iterator():
line_map[line.checkout_id].append(line)
return [line_map.get(checkout_id, []) for checkout_id in keys]
+
+
+class TransactionItemsByCheckoutIDLoader(DataLoader):
+ context_key = "transaction_items_by_checkout_id"
+
+ def batch_load(self, keys):
+ transactions = TransactionItem.objects.filter(checkout_id__in=keys).order_by(
+ "pk"
+ )
+ transactions_map = defaultdict(list)
+ for transaction in transactions:
+ transactions_map[transaction.checkout_id].append(transaction)
+ return [transactions_map[checkout_id] for checkout_id in keys]
diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
index 3602f47b18..1f993dd89d 100644
--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py
+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
@@ -50,8 +50,12 @@ class OrderCreateFromCheckout(BaseMutation):
)
class Meta:
+ auto_permission_message = False
description = (
- "Create new order from existing checkout." + ADDED_IN_32 + PREVIEW_FEATURE
+ "Create new order from existing checkout. Requires the "
+ "following permissions: AUTHENTICATED_APP and HANDLE_CHECKOUTS."
+ + ADDED_IN_32
+ + PREVIEW_FEATURE
)
object_type = Order
permissions = (CheckoutPermissions.HANDLE_CHECKOUTS,)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 83b4043661..3720022670 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -37,7 +37,7 @@ from ....checkout.utils import (
calculate_checkout_quantity,
)
from ....core.payments import PaymentInterface
-from ....payment import TransactionKind
+from ....payment import TransactionAction, TransactionKind
from ....payment.interface import GatewayResponse
from ....plugins.base_plugin import ExcludedShippingMethod
from ....plugins.manager import get_plugins_manager
@@ -4671,3 +4671,92 @@ def test_get_checkout_with_vatlayer_set(
# then
content = get_graphql_content(response)
assert content["data"]["checkout"]["token"] == str(checkout.token)
+
+
+QUERY_CHECKOUT_TRANSACTIONS = """
+ query getCheckout($token: UUID!) {
+ checkout(token: $token) {
+ transactions {
+ id
+ }
+ }
+ }
+ """
+
+
+def test_checkout_transactions_missing_permission(api_client, checkout):
+ # given
+ checkout.payment_transactions.create(
+ status="Authorized",
+ type="Credit card",
+ reference="123",
+ currency="USD",
+ authorized_value=Decimal("15"),
+ available_actions=[TransactionAction.CAPTURE, TransactionAction.VOID],
+ )
+ query = QUERY_CHECKOUT_TRANSACTIONS
+ variables = {"token": str(checkout.token)}
+
+ # when
+ response = api_client.post_graphql(query, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_checkout_transactions_with_manage_checkouts(
+ staff_api_client, checkout, permission_manage_checkouts
+):
+ # given
+ transaction = checkout.payment_transactions.create(
+ status="Authorized",
+ type="Credit card",
+ reference="123",
+ currency="USD",
+ authorized_value=Decimal("15"),
+ available_actions=[TransactionAction.CAPTURE, TransactionAction.VOID],
+ )
+ query = QUERY_CHECKOUT_TRANSACTIONS
+ variables = {"token": str(checkout.token)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_checkouts]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["checkout"]["transactions"]) == 1
+ transaction_id = content["data"]["checkout"]["transactions"][0]["id"]
+ assert transaction_id == graphene.Node.to_global_id(
+ "TransactionItem", transaction.id
+ )
+
+
+def test_checkout_transactions_with_handle_payments(
+ staff_api_client, checkout, permission_manage_payments
+):
+ # given
+ transaction = checkout.payment_transactions.create(
+ status="Authorized",
+ type="Credit card",
+ reference="123",
+ currency="USD",
+ authorized_value=Decimal("15"),
+ available_actions=[TransactionAction.CAPTURE, TransactionAction.VOID],
+ )
+ query = QUERY_CHECKOUT_TRANSACTIONS
+ variables = {"token": str(checkout.token)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert len(content["data"]["checkout"]["transactions"]) == 1
+ transaction_id = content["data"]["checkout"]["transactions"][0]["id"]
+ assert transaction_id == graphene.Node.to_global_id(
+ "TransactionItem", transaction.id
+ )
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index cd693eb954..ac65158782 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -3,7 +3,11 @@ from promise import Promise
from ...checkout import calculations, models
from ...checkout.utils import get_valid_collection_points_for_checkout
-from ...core.permissions import AccountPermissions
+from ...core.permissions import (
+ AccountPermissions,
+ CheckoutPermissions,
+ PaymentPermissions,
+)
from ...core.taxes import zero_taxed_money
from ...core.tracing import traced_resolver
from ...shipping.interface import ShippingMethodData
@@ -15,14 +19,21 @@ from ..channel import ChannelContext
from ..channel.dataloaders import ChannelByCheckoutLineIDLoader, ChannelByIdLoader
from ..channel.types import Channel
from ..core.connection import CountableConnection
-from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATURE
+from ..core.descriptions import (
+ ADDED_IN_31,
+ ADDED_IN_34,
+ DEPRECATED_IN_3X_FIELD,
+ PREVIEW_FEATURE,
+)
from ..core.enums import LanguageCodeEnum
from ..core.scalars import UUID
from ..core.types import ModelObjectType, Money, NonNullList, TaxedMoney
from ..core.utils import str_to_enum
+from ..decorators import one_of_permissions_required
from ..discount.dataloaders import DiscountsByDateTimeLoader
from ..giftcard.types import GiftCard
from ..meta.types import ObjectWithMetadata
+from ..payment.types import TransactionItem
from ..product.dataloaders import (
ProductTypeByProductIdLoader,
ProductTypeByVariantIdLoader,
@@ -37,6 +48,7 @@ from .dataloaders import (
CheckoutInfoByCheckoutTokenLoader,
CheckoutLinesByCheckoutTokenLoader,
CheckoutLinesInfoByCheckoutTokenLoader,
+ TransactionItemsByCheckoutIDLoader,
)
@@ -285,6 +297,16 @@ class Checkout(ModelObjectType):
LanguageCodeEnum, description="Checkout language code.", required=True
)
+ transactions = NonNullList(
+ TransactionItem,
+ description=(
+ "List of transactions for the checkout. Requires one of the "
+ "following permissions: MANAGE_CHECKOUTS, HANDLE_PAYMENTS."
+ + ADDED_IN_34
+ + PREVIEW_FEATURE
+ ),
+ )
+
class Meta:
description = "Checkout object."
model = models.Checkout
@@ -548,6 +570,13 @@ class Checkout(ModelObjectType):
.then(get_oldest_stock_reservation_expiration_date)
)
+ @staticmethod
+ @one_of_permissions_required(
+ [CheckoutPermissions.MANAGE_CHECKOUTS, PaymentPermissions.HANDLE_PAYMENTS]
+ )
+ def resolve_transactions(root: models.Checkout, info):
+ return TransactionItemsByCheckoutIDLoader(info.context).load(root.pk)
+
class CheckoutCountableConnection(CountableConnection):
class Meta:
diff --git a/saleor/graphql/core/descriptions.py b/saleor/graphql/core/descriptions.py
index ef99f1a1d7..8d5d6bd28e 100644
--- a/saleor/graphql/core/descriptions.py
+++ b/saleor/graphql/core/descriptions.py
@@ -7,9 +7,16 @@ DEPRECATED_IN_3X_FIELD = "This field will be removed in Saleor 4.0."
DEPRECATED_IN_3X_INPUT = "\n\nDEPRECATED: this field will be removed in Saleor 4.0."
+DEPRECATED_IN_3X_MUTATION = (
+ "\n\nDEPRECATED: this mutation will be removed in Saleor 4.0."
+)
+
ADDED_IN_31 = "\n\nAdded in Saleor 3.1."
ADDED_IN_32 = "\n\nAdded in Saleor 3.2."
ADDED_IN_33 = "\n\nAdded in Saleor 3.3."
+ADDED_IN_34 = "\n\nAdded in Saleor 3.4."
+
+
PREVIEW_FEATURE = (
"\n\nNote: this API is currently in Feature Preview and can be subject to "
"changes at later point."
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index b401b36ac9..e856cb0d7c 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -124,6 +124,17 @@ OrderErrorCode = graphene.Enum.from_enum(order_error_codes.OrderErrorCode)
InvoiceErrorCode = graphene.Enum.from_enum(invoice_error_codes.InvoiceErrorCode)
PageErrorCode = graphene.Enum.from_enum(page_error_codes.PageErrorCode)
PaymentErrorCode = graphene.Enum.from_enum(payment_error_codes.PaymentErrorCode)
+
+TransactionCreateErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.TransactionCreateErrorCode
+)
+TransactionUpdateErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.TransactionUpdateErrorCode
+)
+TransactionRequestActionErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.TransactionRequestActionErrorCode
+)
+
PermissionGroupErrorCode = graphene.Enum.from_enum(
account_error_codes.PermissionGroupErrorCode
)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index acf29bf5e9..d54e3710f1 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -35,6 +35,9 @@ from ..enums import (
ShopErrorCode,
StockErrorCode,
TimePeriodTypeEnum,
+ TransactionCreateErrorCode,
+ TransactionRequestActionErrorCode,
+ TransactionUpdateErrorCode,
TranslationErrorCode,
UploadErrorCode,
WarehouseErrorCode,
@@ -331,6 +334,20 @@ class PaymentError(Error):
)
+class TransactionCreateError(Error):
+ code = TransactionCreateErrorCode(description="The error code.", required=True)
+
+
+class TransactionUpdateError(Error):
+ code = TransactionUpdateErrorCode(description="The error code.", required=True)
+
+
+class TransactionRequestActionError(Error):
+ code = TransactionRequestActionErrorCode(
+ description="The error code.", required=True
+ )
+
+
class GiftCardError(Error):
code = GiftCardErrorCode(description="The error code.", required=True)
tags = NonNullList(
diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.py
index e4f3aff69f..8c81ffdb03 100644
--- a/saleor/graphql/meta/permissions.py
+++ b/saleor/graphql/meta/permissions.py
@@ -152,6 +152,7 @@ PUBLIC_META_PERMISSION_MAP = {
"Page": page_permissions,
"PageType": page_type_permissions,
"Payment": public_payment_permissions,
+ "TransactionItem": private_payment_permissions,
"Product": product_permissions,
"ProductType": product_type_permissions,
"ProductVariant": product_permissions,
@@ -180,6 +181,7 @@ PRIVATE_META_PERMISSION_MAP = {
"Page": page_permissions,
"PageType": page_type_permissions,
"Payment": private_payment_permissions,
+ "TransactionItem": private_payment_permissions,
"Product": product_permissions,
"ProductType": product_type_permissions,
"ProductVariant": product_permissions,
diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.py
index fe896836ac..49edfd60b6 100644
--- a/saleor/graphql/meta/resolvers.py
+++ b/saleor/graphql/meta/resolvers.py
@@ -54,6 +54,7 @@ def resolve_object_with_metadata_type(instance):
page_models.Page: page_types.Page,
page_models.PageType: page_types.PageType,
payment_models.Payment: payment_types.Payment,
+ payment_models.TransactionItem: payment_types.TransactionItem,
product_models.Product: product_types.Product,
product_models.ProductType: product_types.ProductType,
product_models.ProductVariant: product_types.ProductVariant,
diff --git a/saleor/graphql/meta/tests/test_meta_mutations.py b/saleor/graphql/meta/tests/test_meta_mutations.py
index b12536e0e6..b665c0a1ef 100644
--- a/saleor/graphql/meta/tests/test_meta_mutations.py
+++ b/saleor/graphql/meta/tests/test_meta_mutations.py
@@ -13,6 +13,7 @@ from ....checkout.models import Checkout
from ....core.error_codes import MetadataErrorCode
from ....core.models import ModelWithMetadata
from ....invoice.models import Invoice
+from ....payment.models import TransactionItem
from ....payment.utils import payment_owned_by_user
from ...tests.utils import assert_no_permission, get_graphql_content
@@ -3645,3 +3646,86 @@ def test_delete_private_metadata_for_voucher(
assert item_without_private_metadata(
response["data"]["deletePrivateMetadata"]["item"], voucher, voucher_id
)
+
+
+def test_add_public_metadata_for_transaction_item(
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ transaction_item = TransactionItem.objects.create()
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction_item.pk)
+
+ # when
+ response = execute_update_public_metadata_for_item(
+ staff_api_client, permission_manage_payments, transaction_id, "TransactionItem"
+ )
+
+ # then
+ assert item_contains_proper_public_metadata(
+ response["data"]["updateMetadata"]["item"], transaction_item, transaction_id
+ )
+
+
+def test_delete_public_metadata_for_transaction_item(
+ staff_api_client, permission_manage_payments
+):
+ # given
+ transaction_item = TransactionItem.objects.create(
+ metadata={PUBLIC_KEY: PUBLIC_VALUE}
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction_item.pk)
+
+ # when
+ response = execute_clear_public_metadata_for_item(
+ staff_api_client, permission_manage_payments, transaction_id, "TransactionItem"
+ )
+
+ # then
+ assert item_without_public_metadata(
+ response["data"]["deleteMetadata"]["item"], transaction_item, transaction_id
+ )
+
+
+def test_add_private_metadata_for_transaction_item(
+ staff_api_client, permission_manage_payments
+):
+ # given
+ transaction_item = TransactionItem.objects.create(
+ private_metadata={PRIVATE_KEY: PRIVATE_VALUE}
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction_item.pk)
+
+ # when
+ response = execute_update_private_metadata_for_item(
+ staff_api_client, permission_manage_payments, transaction_id, "TransactionItem"
+ )
+
+ # then
+ assert item_contains_proper_private_metadata(
+ response["data"]["updatePrivateMetadata"]["item"],
+ transaction_item,
+ transaction_id,
+ )
+
+
+def test_delete_private_metadata_for_transaction_item(
+ staff_api_client, permission_manage_payments, voucher
+):
+ # given
+ transaction_item = TransactionItem.objects.create(
+ private_metadata={PRIVATE_KEY: PRIVATE_VALUE}
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction_item.pk)
+
+ # when
+ response = execute_clear_private_metadata_for_item(
+ staff_api_client, permission_manage_payments, transaction_id, "TransactionItem"
+ )
+
+ # then
+ assert item_without_private_metadata(
+ response["data"]["deletePrivateMetadata"]["item"],
+ transaction_item,
+ transaction_id,
+ )
diff --git a/saleor/graphql/meta/tests/test_meta_queries.py b/saleor/graphql/meta/tests/test_meta_queries.py
index e70555c092..d8292760fd 100644
--- a/saleor/graphql/meta/tests/test_meta_queries.py
+++ b/saleor/graphql/meta/tests/test_meta_queries.py
@@ -5,6 +5,7 @@ from django.contrib.auth.models import Permission
from django.http import HttpResponse
from saleor.core.models import ModelWithMetadata
+from saleor.order.models import Order
from saleor.payment.models import Payment
from saleor.payment.utils import payment_owned_by_user
@@ -1045,6 +1046,118 @@ def test_query_public_meta_for_digital_content_as_app(
assert metadata["value"] == PUBLIC_VALUE
+QUERY_TRANSACTION_ITEM_PUBLIC_META = """
+query transactionItemMeta($id: ID!){
+ order(id: $id){
+ transactions{
+ metadata{
+ key
+ value
+ }
+ }
+ }
+}
+"""
+
+
+def execute_query_public_metadata_for_transaction_item(
+ client: ApiClient, order: Order, permissions: List[Permission] = None
+):
+ return execute_query(
+ QUERY_TRANSACTION_ITEM_PUBLIC_META, client, order, "Order", permissions
+ )
+
+
+def assert_transaction_item_contains_metadata(response):
+ content = get_graphql_content(response)
+ metadata = content["data"]["order"]["transactions"][0]["metadata"][0]
+ assert metadata["key"] == PUBLIC_KEY
+ assert metadata["value"] == PUBLIC_VALUE
+
+
+def test_query_public_meta_for_transaction_item_as_customer(
+ user_api_client, order, permission_manage_orders
+):
+ # given
+ order.payment_transactions.create(metadata={PUBLIC_KEY: PUBLIC_VALUE})
+ order.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ order.save(update_fields=["metadata"])
+
+ # when
+ response = execute_query_public_metadata_for_transaction_item(
+ user_api_client,
+ order,
+ permissions=[],
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_public_meta_for_transaction_item_as_staff_with_permission(
+ staff_api_client,
+ order_with_lines,
+ permission_manage_orders,
+ permission_manage_payments,
+):
+ # given
+ order_with_lines.payment_transactions.create(metadata={PUBLIC_KEY: PUBLIC_VALUE})
+
+ # when
+ response = execute_query_public_metadata_for_transaction_item(
+ staff_api_client,
+ order_with_lines,
+ permissions=[permission_manage_orders, permission_manage_payments],
+ )
+
+ # then
+ assert_transaction_item_contains_metadata(response)
+
+
+def test_query_public_meta_for_transaction_item_as_staff_without_permission(
+ staff_api_client, order
+):
+ # given
+ order.payment_transactions.create(metadata={PUBLIC_KEY: PUBLIC_VALUE})
+
+ # when
+ response = execute_query_public_metadata_for_transaction_item(
+ staff_api_client, order
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_public_meta_for_transaction_item_as_app_with_permission(
+ app_api_client,
+ order,
+ permission_manage_orders,
+ permission_manage_payments,
+):
+ order.payment_transactions.create(metadata={PUBLIC_KEY: PUBLIC_VALUE})
+
+ # when
+ response = execute_query_public_metadata_for_transaction_item(
+ app_api_client,
+ order,
+ permissions=[permission_manage_payments, permission_manage_orders],
+ )
+
+ # then
+ assert_transaction_item_contains_metadata(response)
+
+
+def test_query_public_meta_for_transaction_item_as_app_without_permission(
+ app_api_client, order
+):
+ # when
+ response = execute_query_public_metadata_for_transaction_item(app_api_client, order)
+
+ # then
+ assert_no_permission(response)
+
+
QUERY_PAYMENT_PUBLIC_META = """
query paymentsMeta($id: ID!){
payment(id: $id){
@@ -2652,6 +2765,123 @@ def test_query_private_meta_for_digital_content_as_app(
assert metadata["value"] == PRIVATE_VALUE
+QUERY_TRANSACTION_ITEM_PRIVATE_META = """
+query transactionItemMeta($id: ID!){
+ order(id: $id){
+ transactions{
+ privateMetadata{
+ key
+ value
+ }
+ }
+ }
+}
+"""
+
+
+def execute_query_private_metadata_for_transaction_item(
+ client: ApiClient, order: Order, permissions: List[Permission] = None
+):
+ return execute_query(
+ QUERY_TRANSACTION_ITEM_PRIVATE_META, client, order, "Order", permissions
+ )
+
+
+def assert_transaction_item_contains_private_metadata(response):
+ content = get_graphql_content(response)
+ metadata = content["data"]["order"]["transactions"][0]["privateMetadata"][0]
+ assert metadata["key"] == PRIVATE_KEY
+ assert metadata["value"] == PRIVATE_VALUE
+
+
+def test_query_private_meta_for_transaction_item_as_customer(
+ user_api_client, order, permission_manage_orders
+):
+ # given
+ order.payment_transactions.create(private_metadata={PRIVATE_KEY: PRIVATE_VALUE})
+
+ # when
+ response = execute_query_public_metadata_for_transaction_item(
+ user_api_client,
+ order,
+ permissions=[],
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+#
+
+
+def test_query_private_meta_for_transaction_item_as_staff_with_permission(
+ staff_api_client,
+ order_with_lines,
+ permission_manage_orders,
+ permission_manage_payments,
+):
+ # given
+ order_with_lines.payment_transactions.create(
+ private_metadata={PRIVATE_KEY: PRIVATE_VALUE}
+ )
+
+ # when
+ response = execute_query_private_metadata_for_transaction_item(
+ staff_api_client,
+ order_with_lines,
+ permissions=[permission_manage_orders, permission_manage_payments],
+ )
+
+ # then
+ assert_transaction_item_contains_private_metadata(response)
+
+
+def test_query_private_meta_for_transaction_item_as_staff_without_permission(
+ staff_api_client, order
+):
+ # given
+ order.payment_transactions.create(private_metadata={PRIVATE_KEY: PRIVATE_VALUE})
+
+ # when
+ response = execute_query_private_metadata_for_transaction_item(
+ staff_api_client, order
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_private_meta_for_transaction_item_as_app_with_permission(
+ app_api_client,
+ order,
+ permission_manage_orders,
+ permission_manage_payments,
+):
+ order.payment_transactions.create(private_metadata={PRIVATE_KEY: PRIVATE_VALUE})
+
+ # when
+ response = execute_query_private_metadata_for_transaction_item(
+ app_api_client,
+ order,
+ permissions=[permission_manage_payments, permission_manage_orders],
+ )
+
+ # then
+ assert_transaction_item_contains_private_metadata(response)
+
+
+def test_query_private_meta_for_transaction_item_as_app_without_permission(
+ app_api_client, order
+):
+ # when
+ response = execute_query_private_metadata_for_transaction_item(
+ app_api_client, order
+ )
+
+ # then
+ assert_no_permission(response)
+
+
QUERY_PAYMENT_PRIVATE_META = """
query paymentsMeta($id: ID!){
payment(id: $id){
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index 7fc2e3b30a..282cd5cc5c 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -3,6 +3,7 @@ from collections import defaultdict
from django.db.models import F
from ...order.models import Fulfillment, FulfillmentLine, Order, OrderEvent, OrderLine
+from ...payment.models import TransactionItem
from ...warehouse.models import Allocation
from ..core.dataloaders import DataLoader
@@ -125,3 +126,14 @@ class FulfillmentLinesByIdLoader(DataLoader):
self.database_connection_name
).in_bulk(keys)
return [fulfillment_lines.get(line_id) for line_id in keys]
+
+
+class TransactionItemsByOrderIDLoader(DataLoader):
+ context_key = "transaction_items_by_order_id"
+
+ def batch_load(self, keys):
+ transactions = TransactionItem.objects.filter(order_id__in=keys).order_by("pk")
+ transactions_map = defaultdict(list)
+ for transaction in transactions:
+ transactions_map[transaction.order_id].append(transaction)
+ return [transactions_map.get(order_id, []) for order_id in keys]
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index bbfd3c294a..8b3be179d5 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -1,4 +1,5 @@
from collections import defaultdict
+from typing import Optional
import graphene
from django.core.exceptions import ValidationError
@@ -22,6 +23,8 @@ from ....order.actions import (
from ....order.error_codes import OrderErrorCode
from ....order.fetch import OrderLineInfo
from ....order.notifications import send_fulfillment_update
+from ....payment import PaymentError
+from ....payment.models import TransactionItem
from ...core.descriptions import ADDED_IN_31
from ...core.mutations import BaseMutation
from ...core.scalars import PositiveDecimal
@@ -549,7 +552,9 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
cleaned_input["payment"] = payment
@classmethod
- def clean_amount_to_refund(cls, order, amount_to_refund, payment, cleaned_input):
+ def clean_amount_to_refund(
+ cls, order, amount_to_refund, captured_value, cleaned_input
+ ):
if amount_to_refund is not None:
if order_has_gift_card_lines(order):
raise ValidationError(
@@ -563,7 +568,8 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
)
}
)
- if amount_to_refund > payment.captured_amount:
+
+ if amount_to_refund > captured_value:
raise ValidationError(
{
"amount_to_refund": ValidationError(
@@ -592,6 +598,19 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
}
)
+ @classmethod
+ def raise_error_for_payment_error(cls, transactions: Optional[TransactionItem]):
+ if transactions:
+ code = OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
+ msg = "No app or plugin is configured to handle payment action requests."
+ else:
+ msg = "The refund operation is not available yet."
+ code = OrderErrorCode.CANNOT_REFUND.value
+ raise ValidationError(
+ msg,
+ code=code,
+ )
+
@classmethod
def clean_fulfillment_lines(
cls, fulfillment_lines_data, cleaned_input, whitelisted_statuses
@@ -736,11 +755,25 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
info, order_id, field="order", only_type=Order, qs=qs
)
payment = order.get_last_payment()
- cls.clean_order_payment(payment, cleaned_input)
- cls.clean_amount_to_refund(order, amount_to_refund, payment, cleaned_input)
+ transactions = list(order.payment_transactions.all())
+ if transactions:
+ # For know we handle refunds only for last transaction. We need to add an
+ # interface to process a refund requests on multiple transactions
+ captured_value = transactions[-1].captured_value
+ else:
+ cls.clean_order_payment(payment, cleaned_input)
+ captured_value = payment.captured_amount
+ cls.clean_amount_to_refund(
+ order, amount_to_refund, captured_value, cleaned_input
+ )
cleaned_input.update(
- {"include_shipping_costs": include_shipping_costs, "order": order}
+ {
+ "include_shipping_costs": include_shipping_costs,
+ "order": order,
+ "transactions": transactions,
+ "payment": payment,
+ }
)
order_lines_data = input.get("order_lines", [])
@@ -765,17 +798,21 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
order = cleaned_input["order"]
- refund_fulfillment = create_refund_fulfillment(
- info.context.user,
- info.context.app,
- order,
- cleaned_input["payment"],
- cleaned_input.get("order_lines", []),
- cleaned_input.get("fulfillment_lines", []),
- info.context.plugins,
- cleaned_input["amount_to_refund"],
- cleaned_input["include_shipping_costs"],
- )
+ try:
+ refund_fulfillment = create_refund_fulfillment(
+ info.context.user,
+ info.context.app,
+ order,
+ cleaned_input["payment"],
+ cleaned_input["transactions"],
+ cleaned_input.get("order_lines", []),
+ cleaned_input.get("fulfillment_lines", []),
+ info.context.plugins,
+ cleaned_input["amount_to_refund"],
+ cleaned_input["include_shipping_costs"],
+ )
+ except PaymentError:
+ cls.raise_error_for_payment_error(cleaned_input.get("transactions"))
return cls(order=order, fulfillment=refund_fulfillment)
@@ -876,10 +913,20 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
order = cls.get_node_or_error(
info, order_id, field="order", only_type=Order, qs=qs
)
- payment = order.get_last_payment()
if refund:
- cls.clean_order_payment(payment, cleaned_input)
- cls.clean_amount_to_refund(order, amount_to_refund, payment, cleaned_input)
+ payment = order.get_last_payment()
+ transactions = list(order.payment_transactions.all())
+ if transactions:
+ # For know we handle refunds only for last transaction. We need to add
+ # an interface to process a refund requests on multiple transactions
+ captured_value = transactions[-1].captured_value
+ else:
+ cls.clean_order_payment(payment, cleaned_input)
+ captured_value = payment.captured_amount
+ cls.clean_amount_to_refund(
+ order, amount_to_refund, captured_value, cleaned_input
+ )
+ cleaned_input["transactions"] = transactions
cleaned_input.update(
{
@@ -910,18 +957,23 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
def perform_mutation(cls, _root, info, **data):
cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
order = cleaned_input["order"]
- response = create_fulfillments_for_returned_products(
- info.context.user,
- info.context.app,
- order,
- cleaned_input.get("payment"),
- cleaned_input.get("order_lines", []),
- cleaned_input.get("fulfillment_lines", []),
- info.context.plugins,
- cleaned_input["refund"],
- cleaned_input.get("amount_to_refund"),
- cleaned_input["include_shipping_costs"],
- )
+ try:
+ response = create_fulfillments_for_returned_products(
+ info.context.user,
+ info.context.app,
+ order,
+ cleaned_input.get("payment"),
+ cleaned_input.get("transactions"),
+ cleaned_input.get("order_lines", []),
+ cleaned_input.get("fulfillment_lines", []),
+ info.context.plugins,
+ cleaned_input["refund"],
+ cleaned_input.get("amount_to_refund"),
+ cleaned_input["include_shipping_costs"],
+ )
+ except PaymentError:
+ cls.raise_error_for_payment_error(cleaned_input.get("transactions"))
+
return_fulfillment, replace_fulfillment, replace_order = response
return cls(
order=order,
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index ec6d97f78a..858670d767 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -33,6 +33,11 @@ from ....order.utils import (
update_order_prices,
)
from ....payment import PaymentError, TransactionKind, gateway
+from ....payment.gateway import (
+ request_capture_action,
+ request_refund_action,
+ request_void_action,
+)
from ....plugins.manager import PluginsManager
from ....shipping import models as shipping_models
from ....shipping.interface import ShippingMethodData
@@ -566,33 +571,52 @@ class OrderCapture(BaseMutation):
)
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
- order_info = fetch_order_info(order)
- payment = order_info.payment
- clean_order_capture(payment)
- transaction = try_payment_action(
- order,
- info.context.user,
- info.context.app,
- payment,
- gateway.capture,
- payment,
- info.context.plugins,
- amount=amount,
- channel_slug=order.channel.slug,
- )
- order_info.payment.refresh_from_db()
- # Confirm that we changed the status to capture. Some payment can receive
- # asynchronous webhook with update status
- if transaction.kind == TransactionKind.CAPTURE:
- order_captured(
- order_info,
+ if payment_transactions := list(order.payment_transactions.all()):
+ try:
+ # We use the last transaction as we don't have a possibility to
+ # provide way of handling multiple transaction here
+ payment_transaction = payment_transactions[-1]
+ request_capture_action(
+ transaction=payment_transaction,
+ manager=info.context.plugins,
+ capture_value=amount,
+ channel_slug=order.channel.slug,
+ user=info.context.user,
+ app=info.context.app,
+ )
+ except PaymentError as e:
+ raise ValidationError(
+ str(e),
+ code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
+ )
+ else:
+ order_info = fetch_order_info(order)
+ payment = order_info.payment
+ clean_order_capture(payment)
+ transaction = try_payment_action(
+ order,
info.context.user,
info.context.app,
- amount,
+ payment,
+ gateway.capture,
payment,
info.context.plugins,
+ amount=amount,
+ channel_slug=order.channel.slug,
)
+ order_info.payment.refresh_from_db()
+ # Confirm that we changed the status to capture. Some payment can receive
+ # asynchronous webhook with update status
+ if transaction.kind == TransactionKind.CAPTURE:
+ order_captured(
+ order_info,
+ info.context.user,
+ info.context.app,
+ amount,
+ payment,
+ info.context.plugins,
+ )
return OrderCapture(order=order)
@@ -611,29 +635,46 @@ class OrderVoid(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
- payment = order.get_last_payment()
- clean_void_payment(payment)
- transaction = try_payment_action(
- order,
- info.context.user,
- info.context.app,
- payment,
- gateway.void,
- payment,
- info.context.plugins,
- channel_slug=order.channel.slug,
- )
- # Confirm that we changed the status to void. Some payment can receive
- # asynchronous webhook with update status
- if transaction.kind == TransactionKind.VOID:
- order_voided(
+ if payment_transactions := list(order.payment_transactions.all()):
+ # We use the last transaction as we don't have a possibility to
+ # provide way of handling multiple transaction here
+ try:
+ request_void_action(
+ payment_transactions[-1],
+ info.context.plugins,
+ channel_slug=order.channel.slug,
+ user=info.context.user,
+ app=info.context.app,
+ )
+ except PaymentError as e:
+ raise ValidationError(
+ str(e),
+ code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
+ )
+ else:
+ payment = order.get_last_payment()
+ clean_void_payment(payment)
+ transaction = try_payment_action(
order,
info.context.user,
info.context.app,
payment,
+ gateway.void,
+ payment,
info.context.plugins,
+ channel_slug=order.channel.slug,
)
+ # Confirm that we changed the status to void. Some payment can receive
+ # asynchronous webhook with update status
+ if transaction.kind == TransactionKind.VOID:
+ order_voided(
+ order,
+ info.context.user,
+ info.context.app,
+ payment,
+ info.context.plugins,
+ )
return OrderVoid(order=order)
@@ -667,35 +708,53 @@ class OrderRefund(BaseMutation):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
clean_order_refund(order)
- payment = order.get_last_payment()
- clean_refund_payment(payment)
-
- transaction = try_payment_action(
- order,
- info.context.user,
- info.context.app,
- payment,
- gateway.refund,
- payment,
- info.context.plugins,
- amount=amount,
- channel_slug=order.channel.slug,
- )
- order.fulfillments.create(
- status=FulfillmentStatus.REFUNDED, total_refund_amount=amount
- )
-
- # Confirm that we changed the status to refund. Some payment can receive
- # asynchronous webhook with update status
- if transaction.kind == TransactionKind.REFUND:
- order_refunded(
+ if payment_transactions := list(order.payment_transactions.all()):
+ # We use the last transaction as we don't have a possibility to
+ # provide way of handling multiple transaction here
+ try:
+ request_refund_action(
+ payment_transactions[-1],
+ info.context.plugins,
+ refund_value=amount,
+ channel_slug=order.channel.slug,
+ user=info.context.user,
+ app=info.context.app,
+ )
+ except PaymentError as e:
+ raise ValidationError(
+ str(e),
+ code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
+ )
+ else:
+ payment = order.get_last_payment()
+ clean_payment(payment)
+ clean_refund_payment(payment)
+ transaction = try_payment_action(
order,
info.context.user,
info.context.app,
- amount,
+ payment,
+ gateway.refund,
payment,
info.context.plugins,
+ amount=amount,
+ channel_slug=order.channel.slug,
)
+ # Confirm that we changed the status to refund. Some payment can receive
+ # asynchronous webhook with update status
+ if transaction.kind == TransactionKind.REFUND:
+ order_refunded(
+ order,
+ info.context.user,
+ info.context.app,
+ amount,
+ payment,
+ info.context.plugins,
+ )
+
+ order.fulfillments.create(
+ status=FulfillmentStatus.REFUNDED, total_refund_amount=amount
+ )
return OrderRefund(order=order)
@@ -746,7 +805,25 @@ class OrderConfirm(ModelMutation):
order_info = fetch_order_info(order)
payment = order_info.payment
manager = info.context.plugins
- if payment and payment.is_authorized and payment.can_capture():
+ if payment_transactions := list(order.payment_transactions.all()):
+ try:
+ # We use the last transaction as we don't have a possibility to
+ # provide way of handling multiple transaction here
+ payment_transaction = payment_transactions[-1]
+ request_capture_action(
+ transaction=payment_transaction,
+ manager=info.context.plugins,
+ capture_value=payment_transaction.captured_value,
+ channel_slug=order.channel.slug,
+ user=info.context.user,
+ app=info.context.app,
+ )
+ except PaymentError as e:
+ raise ValidationError(
+ str(e),
+ code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
+ )
+ elif payment and payment.is_authorized and payment.can_capture():
gateway.capture(
payment, info.context.plugins, channel_slug=order.channel.slug
)
diff --git a/saleor/graphql/order/tests/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
index b4208bd477..d48875ff11 100644
--- a/saleor/graphql/order/tests/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
@@ -5,13 +5,15 @@ import graphene
from prices import Money, TaxedMoney
from ....core.prices import quantize_price
-from ....order import FulfillmentLineData
+from ....order import FulfillmentLineData, OrderEvents
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 ....payment import ChargeStatus, PaymentError, TransactionAction
+from ....payment.interface import RefundData, TransactionActionData
+from ....payment.models import TransactionItem
from ....warehouse.models import Allocation, Stock
+from ...core.utils import to_global_id_or_none
from ...tests.utils import get_graphql_content
ORDER_FULFILL_REFUND_MUTATION = """
@@ -45,6 +47,102 @@ mutation OrderFulfillmentRefundProducts(
"""
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_fulfillment_refund_products_with_transaction_action_request(
+ mocked_transaction_action_request,
+ mocked_is_active,
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ captured_value = Decimal("20.0")
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=fulfilled_order.pk,
+ captured_value=captured_value,
+ )
+
+ order_id = to_global_id_or_none(fulfilled_order)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {"amountToRefund": amount_to_refund, "includeShippingCosts": True},
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentRefundProducts"]
+ errors = data["errors"]
+ assert not errors
+
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=amount_to_refund,
+ ),
+ channel_slug=fulfilled_order.channel.slug,
+ )
+ event = fulfilled_order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_REFUND_REQUESTED
+ assert Decimal(event.parameters["amount"]) == amount_to_refund
+ assert event.parameters["reference"] == transaction.reference
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_fulfillment_refund_products_with_missing_payment_action_hook(
+ mocked_is_active,
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ mocked_is_active.return_value = False
+
+ captured_value = Decimal("20.0")
+ TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=fulfilled_order.pk,
+ captured_value=captured_value,
+ )
+
+ order_id = to_global_id_or_none(fulfilled_order)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {"amountToRefund": amount_to_refund, "includeShippingCosts": True},
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentRefundProducts"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == (
+ OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.name
+ )
+ assert mocked_is_active.called
+
+
@patch("saleor.order.actions.gateway.refund")
@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")
def test_fulfillment_refund_products_with_back_in_stock_webhook(
diff --git a/saleor/graphql/order/tests/test_fulfillment_return_products.py b/saleor/graphql/order/tests/test_fulfillment_return_products.py
index b930d2cc25..85426ecf9e 100644
--- a/saleor/graphql/order/tests/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_return_products.py
@@ -5,13 +5,15 @@ import graphene
from prices import Money, TaxedMoney
from ....core.prices import quantize_price
-from ....order import FulfillmentLineData, OrderOrigin, OrderStatus
+from ....order import FulfillmentLineData, OrderEvents, 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 ....payment import ChargeStatus, PaymentError, TransactionAction
+from ....payment.interface import RefundData, TransactionActionData
+from ....payment.models import TransactionItem
from ....warehouse.models import Stock
+from ...core.utils import to_global_id_or_none
from ...tests.utils import get_graphql_content
ORDER_FULFILL_RETURN_MUTATION = """
@@ -66,6 +68,110 @@ mutation OrderFulfillmentReturnProducts(
"""
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_fulfillment_return_products_with_transaction_action_request(
+ mocked_transaction_action_request,
+ mocked_is_active,
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ captured_value = Decimal("20.0")
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=fulfilled_order.pk,
+ captured_value=captured_value,
+ )
+
+ order_id = to_global_id_or_none(fulfilled_order)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "amountToRefund": amount_to_refund,
+ "includeShippingCosts": True,
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ errors = data["errors"]
+ assert not errors
+
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=amount_to_refund,
+ ),
+ channel_slug=fulfilled_order.channel.slug,
+ )
+ event = fulfilled_order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_REFUND_REQUESTED
+ assert Decimal(event.parameters["amount"]) == amount_to_refund
+ assert event.parameters["reference"] == transaction.reference
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_fulfillment_return_products_with_missing_payment_action_hook(
+ mocked_is_active,
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ mocked_is_active.return_value = False
+
+ captured_value = Decimal("20.0")
+ TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=fulfilled_order.pk,
+ captured_value=captured_value,
+ )
+
+ order_id = to_global_id_or_none(fulfilled_order)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "amountToRefund": amount_to_refund,
+ "includeShippingCosts": True,
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == (
+ OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.name
+ )
+ assert mocked_is_active.called
+
+
def test_fulfillment_return_products_order_without_payment(
staff_api_client, permission_manage_orders, fulfilled_order
):
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index eb7b2e676a..932907fd20 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -25,7 +25,7 @@ from ....core.taxes import TaxError, zero_taxed_money
from ....discount.models import OrderDiscount
from ....giftcard import GiftCardEvents
from ....giftcard.events import gift_cards_bought_event, gift_cards_used_in_order_event
-from ....order import FulfillmentStatus, OrderOrigin, OrderStatus
+from ....order import FulfillmentStatus, OrderEvents, OrderOrigin, OrderStatus
from ....order import events as order_events
from ....order.error_codes import OrderErrorCode
from ....order.events import order_replacement_created
@@ -35,8 +35,9 @@ from ....order.search import (
prepare_order_search_document_value,
update_order_search_document,
)
-from ....payment import ChargeStatus, PaymentError
-from ....payment.models import Payment
+from ....payment import ChargeStatus, PaymentError, TransactionAction, TransactionStatus
+from ....payment.interface import TransactionActionData
+from ....payment.models import Payment, TransactionEvent, TransactionItem
from ....plugins.base_plugin import ExcludedShippingMethod
from ....plugins.manager import PluginsManager, get_plugins_manager
from ....product.models import ProductVariant, ProductVariantChannelListing
@@ -50,6 +51,7 @@ from ...order.mutations.orders import (
clean_refund_payment,
try_payment_action,
)
+from ...payment.enums import TransactionStatusEnum
from ...payment.types import PaymentChargeStatusEnum
from ...tests.utils import (
assert_no_permission,
@@ -288,6 +290,19 @@ query OrdersQuery {
paymentStatusDisplay
userEmail
isPaid
+ actions
+ totalAuthorized{
+ amount
+ currency
+ }
+ totalCaptured{
+ amount
+ currency
+ }
+ totalBalance{
+ amount
+ currency
+ }
shippingPrice {
gross {
amount
@@ -324,6 +339,40 @@ query OrdersQuery {
}
payments{
id
+ actions
+ total{
+ currency
+ amount
+ }
+ }
+ transactions{
+ reference
+ type
+ status
+ modifiedAt
+ createdAt
+ authorizedAmount{
+ amount
+ currency
+ }
+ voidedAmount{
+ currency
+ amount
+ }
+ capturedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ events{
+ status
+ reference
+ name
+ createdAt
+ }
}
subtotal {
net {
@@ -527,6 +576,106 @@ def test_order_query(
assert order_data["deliveryMethod"]["id"] == order_data["shippingMethod"]["id"]
+def test_order_query_with_transactions_details(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+ shipping_zone,
+):
+ # given
+ order = fulfilled_order
+ net = Money(amount=Decimal("100"), currency="USD")
+ gross = Money(amount=net.amount * Decimal(1.23), currency="USD").quantize()
+ shipping_price = TaxedMoney(net=net, gross=gross)
+ order.shipping_price = shipping_price
+ shipping_tax_rate = Decimal("0.23")
+ order.shipping_tax_rate = shipping_tax_rate
+ private_value = "abc123"
+ public_value = "123abc"
+ order.shipping_method.store_value_in_metadata({"test": public_value})
+ order.shipping_method.store_value_in_private_metadata({"test": private_value})
+ order.shipping_method.save()
+ order.save()
+ transactions = TransactionItem.objects.bulk_create(
+ [
+ TransactionItem(
+ order_id=order.id,
+ status="Authorized",
+ type="Credit card",
+ reference="123",
+ currency="USD",
+ authorized_value=Decimal("15"),
+ available_actions=[TransactionAction.CAPTURE, TransactionAction.VOID],
+ ),
+ TransactionItem(
+ order_id=order.id,
+ status="Authorized second credit card",
+ type="Credit card",
+ reference="321",
+ currency="USD",
+ authorized_value=Decimal("10"),
+ available_actions=[TransactionAction.CAPTURE, TransactionAction.VOID],
+ ),
+ TransactionItem(
+ order_id=order.id,
+ status="Captured",
+ type="Credit card",
+ reference="321",
+ currency="USD",
+ captured_value=Decimal("15"),
+ available_actions=[TransactionAction.REFUND],
+ ),
+ ]
+ )
+
+ event_status = TransactionStatus.FAILURE
+ event_reference = "PSP-ref"
+ event_name = "Failed authorization"
+ TransactionEvent.objects.bulk_create(
+ [
+ TransactionEvent(
+ name=event_name,
+ status=event_status,
+ reference=event_reference,
+ transaction=transaction,
+ )
+ for transaction in transactions
+ ]
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+
+ payment_charge_status = PaymentChargeStatusEnum.PARTIALLY_CHARGED
+ assert order_data["paymentStatus"] == payment_charge_status.name
+ assert (
+ order_data["paymentStatusDisplay"]
+ == dict(ChargeStatus.CHOICES)[payment_charge_status.value]
+ )
+ assert order_data["isPaid"] == order.is_fully_paid()
+
+ assert len(order_data["payments"]) == order.payments.count()
+ assert Decimal(order_data["totalAuthorized"]["amount"]) == Decimal("25")
+ assert Decimal(order_data["totalCaptured"]["amount"]) == Decimal("15")
+
+ assert Decimal(str(order_data["totalBalance"]["amount"])) == Decimal("-83.4")
+
+ for transaction in order_data["transactions"]:
+ assert len(transaction["events"]) == 1
+ event = transaction["events"][0]
+ assert event["name"] == event_name
+ assert event["status"] == TransactionStatusEnum.FAILURE.name
+ assert event["reference"] == event_reference
+
+
def test_order_query_shipping_method_channel_listing_does_not_exist(
staff_api_client,
permission_manage_orders,
@@ -5382,17 +5531,7 @@ def test_order_cancel_with_bought_gift_cards(
assert gift_card.events.filter(type=GiftCardEvents.DEACTIVATED)
[email protected]("saleor.plugins.manager.PluginsManager.notify")
-def test_order_capture(
- mocked_notify,
- channel_USD,
- staff_api_client,
- permission_manage_orders,
- payment_txn_preauth,
- staff_user,
-):
- order = payment_txn_preauth.order
- query = """
+ORDER_CAPTURE_MUTATION = """
mutation captureOrder($id: ID!, $amount: PositiveDecimal!) {
orderCapture(id: $id, amount: $amount) {
order {
@@ -5403,14 +5542,31 @@ def test_order_capture(
amount
}
}
+ errors{
+ field
+ message
+ code
+ }
}
}
- """
+"""
+
+
[email protected]("saleor.plugins.manager.PluginsManager.notify")
+def test_order_capture(
+ mocked_notify,
+ channel_USD,
+ staff_api_client,
+ permission_manage_orders,
+ payment_txn_preauth,
+ staff_user,
+):
+ order = payment_txn_preauth.order
order_id = graphene.Node.to_global_id("Order", order.id)
amount = float(payment_txn_preauth.total)
variables = {"id": order_id, "amount": amount}
response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
+ ORDER_CAPTURE_MUTATION, variables, permissions=[permission_manage_orders]
)
content = get_graphql_content(response)
data = content["data"]["orderCapture"]["order"]
@@ -5457,6 +5613,97 @@ def test_order_capture(
)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_order_capture_with_transaction_action_request(
+ mocked_transaction_action_request,
+ mocked_is_active,
+ staff_api_client,
+ permission_manage_orders,
+ order,
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ capture_value = Decimal(5.0)
+ mocked_is_active.return_value = True
+ order_id = to_global_id_or_none(order)
+
+ variables = {"id": order_id, "amount": capture_value}
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_CAPTURE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCapture"]
+ assert not data["errors"]
+
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CAPTURE,
+ action_value=capture_value,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED
+ assert Decimal(event.parameters["amount"]) == capture_value
+ assert event.parameters["reference"] == transaction.reference
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_order_capture_with_transaction_action_request_missing_event(
+ mocked_is_active, staff_api_client, permission_manage_orders, order
+):
+ # given
+ authorization_value = Decimal("10")
+ TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=authorization_value,
+ )
+ mocked_is_active.return_value = False
+
+ order_id = to_global_id_or_none(order)
+
+ variables = {"id": order_id, "amount": authorization_value}
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_CAPTURE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCapture"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["message"] == (
+ "No app or plugin is configured to handle payment action requests."
+ )
+ assert data["errors"][0]["code"] == (
+ OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.name
+ )
+
+ assert mocked_is_active.called
+
+
MUTATION_MARK_ORDER_AS_PAID = """
mutation markPaid($id: ID!, $transaction: String) {
orderMarkAsPaid(id: $id, transactionReference: $transaction) {
@@ -5633,6 +5880,95 @@ def test_order_void_payment_error(
mock_void_payment.assert_called_once()
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_order_void_with_transaction_action_request(
+ mocked_transaction_action_request,
+ mocked_is_active,
+ staff_api_client,
+ permission_manage_orders,
+ order,
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+
+ mocked_is_active.return_value = True
+
+ order_id = to_global_id_or_none(order)
+
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_VOID, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderVoid"]
+ assert not data["errors"]
+
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.VOID,
+ action_value=None,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_VOID_REQUESTED
+ assert event.parameters["reference"] == transaction.reference
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_order_void_with_transaction_action_request_missing_event(
+ mocked_is_active, staff_api_client, permission_manage_orders, order
+):
+ # given
+ TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10.0"),
+ )
+ mocked_is_active.return_value = False
+
+ order_id = to_global_id_or_none(order)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_VOID, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderVoid"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["message"] == (
+ "No app or plugin is configured to handle payment action requests."
+ )
+ assert data["errors"][0]["code"] == (
+ OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.name
+ )
+
+ assert mocked_is_active.called
+
+
ORDER_REFUND_MUTATION = """
mutation refundOrder($id: ID!, $amount: PositiveDecimal!) {
orderRefund(id: $id, amount: $amount) {
@@ -5701,6 +6037,93 @@ def test_order_refund_with_gift_card_lines(
assert data["errors"][0]["field"] == "id"
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_order_refund_with_transaction_action_request(
+ mocked_transaction_action_request,
+ mocked_is_active,
+ staff_api_client,
+ permission_manage_orders,
+ order,
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ refund_value = Decimal(5.0)
+ mocked_is_active.return_value = True
+
+ order_id = to_global_id_or_none(order)
+ variables = {"id": order_id, "amount": refund_value}
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_REFUND_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderRefund"]
+ assert not data["errors"]
+
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=refund_value,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_REFUND_REQUESTED
+ assert Decimal(event.parameters["amount"]) == refund_value
+ assert event.parameters["reference"] == transaction.reference
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_order_refund_with_transaction_action_request_missing_event(
+ mocked_is_active, staff_api_client, permission_manage_orders, order
+):
+ # given
+ captured_value = Decimal("10")
+ TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=captured_value,
+ )
+ mocked_is_active.return_value = False
+
+ order_id = to_global_id_or_none(order)
+ variables = {"id": order_id, "amount": captured_value}
+
+ # when
+ response = staff_api_client.post_graphql(
+ ORDER_REFUND_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderRefund"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == (
+ OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.name
+ )
+
+ assert mocked_is_active.called
+
+
@pytest.mark.parametrize(
"requires_amount, mutation_name",
((True, "orderRefund"), (False, "orderVoid"), (True, "orderCapture")),
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 3dd502719b..74cdc0e57f 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -17,9 +17,11 @@ from ...core.permissions import (
AppPermission,
AuthorizationFilters,
OrderPermissions,
+ PaymentPermissions,
ProductPermissions,
has_one_of_permissions,
)
+from ...core.prices import quantize_price
from ...core.tracing import traced_resolver
from ...discount import OrderDiscountType
from ...graphql.checkout.types import DeliveryMethod
@@ -57,7 +59,12 @@ from ..channel import ChannelContext
from ..channel.dataloaders import ChannelByIdLoader, ChannelByOrderLineIdLoader
from ..channel.types import Channel
from ..core.connection import CountableConnection
-from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATURE
+from ..core.descriptions import (
+ ADDED_IN_31,
+ ADDED_IN_34,
+ DEPRECATED_IN_3X_FIELD,
+ PREVIEW_FEATURE,
+)
from ..core.enums import LanguageCodeEnum
from ..core.fields import PermissionsField
from ..core.mutations import validation_error_to_error_type
@@ -72,13 +79,15 @@ from ..core.types import (
Weight,
)
from ..core.utils import str_to_enum
+from ..decorators import one_of_permissions_required
from ..discount.dataloaders import OrderDiscountsByOrderIDLoader, VoucherByIdLoader
from ..discount.enums import DiscountValueTypeEnum
from ..discount.types import Voucher
from ..giftcard.types import GiftCard
from ..invoice.types import Invoice
from ..meta.types import ObjectWithMetadata
-from ..payment.types import OrderAction, Payment, PaymentChargeStatusEnum
+from ..payment.enums import OrderAction, TransactionStatusEnum
+from ..payment.types import Payment, PaymentChargeStatusEnum, TransactionItem
from ..product.dataloaders import (
MediaByProductVariantIdLoader,
ProductByVariantIdLoader,
@@ -102,6 +111,7 @@ from .dataloaders import (
OrderEventsByOrderIdLoader,
OrderLineByIdLoader,
OrderLinesByOrderIdLoader,
+ TransactionItemsByOrderIDLoader,
)
from .enums import (
FulfillmentStatusEnum,
@@ -136,6 +146,25 @@ def get_order_discount_event(discount_obj: dict):
)
+def get_payment_status_for_order(order, transactions):
+ status = ChargeStatus.NOT_CHARGED
+ captured_money = prices.Money(Decimal(0), order.currency)
+ refunded_money = prices.Money(Decimal(0), order.currency)
+ for transaction in transactions:
+ captured_money += transaction.amount_captured
+ refunded_money += transaction.amount_refunded
+
+ if captured_money >= order.total.gross:
+ status = ChargeStatus.FULLY_CHARGED
+ elif captured_money and captured_money < order.total.gross:
+ status = ChargeStatus.PARTIALLY_CHARGED
+ if refunded_money >= order.total.gross:
+ status = ChargeStatus.FULLY_REFUNDED
+ elif refunded_money and refunded_money < order.total.gross:
+ status = ChargeStatus.PARTIALLY_REFUNDED
+ return status
+
+
class OrderDiscount(graphene.ObjectType):
value_type = graphene.Field(
DiscountValueTypeEnum,
@@ -197,7 +226,9 @@ class OrderEvent(ModelObjectType):
description="Type of an email sent to the customer."
)
amount = graphene.Float(description="Amount of money.")
- payment_id = graphene.String(description="The payment ID from the payment gateway.")
+ payment_id = graphene.String(
+ description="The payment reference from the payment provider."
+ )
payment_gateway = graphene.String(description="The payment gateway of the payment.")
quantity = graphene.Int(description="Number of items.")
composed_id = graphene.String(description="Composed ID of the Fulfillment.")
@@ -227,6 +258,10 @@ class OrderEvent(ModelObjectType):
discount = graphene.Field(
OrderEventDiscountObject, description="The discount applied to the order."
)
+ status = graphene.Field(
+ TransactionStatusEnum, description="The status of payment's transaction."
+ )
+ reference = graphene.String(description="The reference of payment's transaction.")
class Meta:
description = "History log of the order."
@@ -389,6 +424,14 @@ class OrderEvent(ModelObjectType):
return None
return get_order_discount_event(discount_obj)
+ @staticmethod
+ def resolve_status(root: models.OrderEvent, _info):
+ return root.parameters.get("status")
+
+ @staticmethod
+ def resolve_reference(root: models.OrderEvent, _info):
+ return root.parameters.get("reference")
+
class OrderEventCountableConnection(CountableConnection):
class Meta:
@@ -739,6 +782,16 @@ class Order(ModelObjectType):
payment_status_display = graphene.String(
description="User-friendly payment status.", required=True
)
+ transactions = NonNullList(
+ TransactionItem,
+ description=(
+ "List of transactions for the order. Requires one of the "
+ "following permissions: MANAGE_ORDERS, HANDLE_PAYMENTS."
+ + ADDED_IN_34
+ + PREVIEW_FEATURE
+ ),
+ required=True,
+ )
payments = NonNullList(
Payment, description="List of payments for the order.", required=True
)
@@ -1041,22 +1094,52 @@ class Order(ModelObjectType):
@staticmethod
def resolve_total_authorized(root: models.Order, info):
- def _resolve_total_get_total_authorized(payments):
+ def _resolve_total_get_total_authorized(data):
+ transactions, payments = data
+ if transactions:
+ authorized_money = prices.Money(Decimal(0), root.currency)
+ for transaction in transactions:
+ authorized_money += transaction.amount_authorized
+ return quantize_price(authorized_money, root.currency)
return get_total_authorized(payments, root.currency)
+ transactions = TransactionItemsByOrderIDLoader(info.context).load(root.id)
+ payments = PaymentsByOrderIdLoader(info.context).load(root.id)
+ return Promise.all([transactions, payments]).then(
+ _resolve_total_get_total_authorized
+ )
+
+ @staticmethod
+ def resolve_total_captured(root: models.Order, info):
+ def _resolve_total_captured(transactions):
+ if transactions:
+ captured_money = prices.Money(Decimal(0), root.currency)
+ for transaction in transactions:
+ captured_money += transaction.amount_captured
+ return quantize_price(captured_money, root.currency)
+ return root.total_paid
+
return (
- PaymentsByOrderIdLoader(info.context)
+ TransactionItemsByOrderIDLoader(info.context)
.load(root.id)
- .then(_resolve_total_get_total_authorized)
+ .then(_resolve_total_captured)
)
@staticmethod
- def resolve_total_captured(root: models.Order, _info):
- return root.total_paid
+ def resolve_total_balance(root: models.Order, info):
+ def _resolve_total_balance(transactions):
+ if transactions:
+ captured_money = prices.Money(Decimal(0), root.currency)
+ for transaction in transactions:
+ captured_money += transaction.amount_captured
+ return quantize_price(captured_money - root.total.gross, root.currency)
+ return root.total_balance
- @staticmethod
- def resolve_total_balance(root: models.Order, _info):
- return root.total_balance
+ return (
+ TransactionItemsByOrderIDLoader(info.context)
+ .load(root.id)
+ .then(_resolve_total_balance)
+ )
@staticmethod
def resolve_fulfillments(root: models.Order, info):
@@ -1084,8 +1167,20 @@ class Order(ModelObjectType):
return OrderEventsByOrderIdLoader(_info.context).load(root.id)
@staticmethod
- def resolve_is_paid(root: models.Order, _info):
- return root.is_fully_paid()
+ def resolve_is_paid(root: models.Order, info):
+ def _resolve_is_paid(transactions):
+ if transactions:
+ captured_money = prices.Money(Decimal(0), root.currency)
+ for transaction in transactions:
+ captured_money += transaction.amount_captured
+ return captured_money >= root.total.gross
+ return root.is_fully_paid()
+
+ return (
+ TransactionItemsByOrderIDLoader(info.context)
+ .load(root.id)
+ .then(_resolve_is_paid)
+ )
@staticmethod
def resolve_number(root: models.Order, _info):
@@ -1094,34 +1189,46 @@ class Order(ModelObjectType):
@staticmethod
@traced_resolver
def resolve_payment_status(root: models.Order, info):
- def _resolve_payment_status(payments):
- if last_payment := get_last_payment(payments):
- return last_payment.charge_status
- return ChargeStatus.NOT_CHARGED
+ def _resolve_payment_status(data):
+ transactions, payments = data
+ if transactions:
+ return get_payment_status_for_order(root, transactions)
+ last_payment = get_last_payment(payments)
+ if not last_payment:
+ return ChargeStatus.NOT_CHARGED
+ return last_payment.charge_status
- return (
- PaymentsByOrderIdLoader(info.context)
- .load(root.id)
- .then(_resolve_payment_status)
- )
+ transactions = TransactionItemsByOrderIDLoader(info.context).load(root.id)
+ payments = PaymentsByOrderIdLoader(info.context).load(root.id)
+ return Promise.all([transactions, payments]).then(_resolve_payment_status)
@staticmethod
def resolve_payment_status_display(root: models.Order, info):
- def _resolve_payment_status(payments):
- if last_payment := get_last_payment(payments):
- return last_payment.get_charge_status_display()
- return dict(ChargeStatus.CHOICES).get(ChargeStatus.NOT_CHARGED)
+ def _resolve_payment_status(data):
+ transactions, payments = data
+ if transactions:
+ status = get_payment_status_for_order(root, transactions)
+ return dict(ChargeStatus.CHOICES).get(status)
+ last_payment = get_last_payment(payments)
+ if not last_payment:
+ return dict(ChargeStatus.CHOICES).get(ChargeStatus.NOT_CHARGED)
+ return last_payment.get_charge_status_display()
- return (
- PaymentsByOrderIdLoader(info.context)
- .load(root.id)
- .then(_resolve_payment_status)
- )
+ transactions = TransactionItemsByOrderIDLoader(info.context).load(root.id)
+ payments = PaymentsByOrderIdLoader(info.context).load(root.id)
+ return Promise.all([transactions, payments]).then(_resolve_payment_status)
@staticmethod
def resolve_payments(root: models.Order, _info):
return root.payments.all()
+ @staticmethod
+ @one_of_permissions_required(
+ [OrderPermissions.MANAGE_ORDERS, PaymentPermissions.HANDLE_PAYMENTS]
+ )
+ def resolve_transactions(root: models.Order, info):
+ return TransactionItemsByOrderIDLoader(info.context).load(root.id)
+
@staticmethod
def resolve_status_display(root: models.Order, _info):
return root.get_status_display()
diff --git a/saleor/graphql/payment/dataloaders.py b/saleor/graphql/payment/dataloaders.py
new file mode 100644
index 0000000000..87158d7aa2
--- /dev/null
+++ b/saleor/graphql/payment/dataloaders.py
@@ -0,0 +1,19 @@
+from collections import defaultdict
+
+from ...payment.models import TransactionEvent
+from ..core.dataloaders import DataLoader
+
+
+class TransactionEventByTransactionIdLoader(DataLoader):
+ context_key = "transaction_event_by_transaction_id"
+
+ def batch_load(self, keys):
+ events = (
+ TransactionEvent.objects.using(self.database_connection_name)
+ .filter(transaction_id__in=keys)
+ .order_by("pk")
+ )
+ event_map = defaultdict(list)
+ for event in events:
+ event_map[event.transaction_id].append(event)
+ return [event_map.get(transaction_id, []) for transaction_id in keys]
diff --git a/saleor/graphql/payment/enums.py b/saleor/graphql/payment/enums.py
index 14f1f9358a..a30ebc1044 100644
--- a/saleor/graphql/payment/enums.py
+++ b/saleor/graphql/payment/enums.py
@@ -1,10 +1,21 @@
import graphene
from ...graphql.core.enums import to_enum
-from ...payment import ChargeStatus, TransactionKind
+from ...payment import (
+ ChargeStatus,
+ TransactionAction,
+ TransactionKind,
+ TransactionStatus,
+)
TransactionKindEnum = to_enum(TransactionKind, type_name="TransactionKind")
PaymentChargeStatusEnum = to_enum(ChargeStatus, type_name="PaymentChargeStatusEnum")
+TransactionActionEnum = to_enum(
+ TransactionAction,
+ type_name="TransactionActionEnum",
+ description=TransactionAction.__doc__,
+)
+TransactionStatusEnum = to_enum(TransactionStatus, type_name="TransactionStatus")
class OrderAction(graphene.Enum):
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 0a7906ae11..23d9063a10 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,25 +1,45 @@
-from typing import TYPE_CHECKING, List
+from decimal import Decimal
+from typing import List, Optional, Union
import graphene
from django.core.exceptions import ValidationError
from ...channel.models import Channel
+from ...checkout import models as checkout_models
from ...checkout.calculations import calculate_checkout_total_with_gift_cards
from ...checkout.checkout_cleaner import clean_billing_address, clean_checkout_shipping
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...checkout.utils import cancel_active_payments
from ...core.error_codes import MetadataErrorCode
-from ...core.permissions import OrderPermissions
+from ...core.permissions import OrderPermissions, PaymentPermissions
from ...core.utils import get_client_ip
from ...core.utils.url import validate_storefront_url
-from ...payment import PaymentError, StorePaymentMethod, gateway
-from ...payment.error_codes import PaymentErrorCode
+from ...order import models as order_models
+from ...order.events import transaction_event
+from ...payment import PaymentError, StorePaymentMethod, TransactionAction, gateway
+from ...payment import models as payment_models
+from ...payment.error_codes import (
+ PaymentErrorCode,
+ TransactionCreateErrorCode,
+ TransactionRequestActionErrorCode,
+ TransactionUpdateErrorCode,
+)
+from ...payment.gateway import (
+ request_capture_action,
+ request_refund_action,
+ request_void_action,
+)
from ...payment.utils import create_payment, is_currency_supported
from ..account.i18n import I18nMixin
from ..channel.utils import validate_channel
from ..checkout.mutations.utils import get_checkout_by_token
from ..checkout.types import Checkout
-from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_INPUT
+from ..core.descriptions import (
+ ADDED_IN_31,
+ ADDED_IN_34,
+ DEPRECATED_IN_3X_INPUT,
+ PREVIEW_FEATURE,
+)
from ..core.enums import to_enum
from ..core.fields import JSONString
from ..core.mutations import BaseMutation
@@ -27,12 +47,11 @@ from ..core.scalars import UUID, PositiveDecimal
from ..core.types import common as common_types
from ..core.validators import validate_one_of_args_is_in_mutation
from ..meta.mutations import MetadataInput
-from .types import Payment, PaymentInitialized
+from ..utils import get_user_or_app_from_context
+from .enums import TransactionActionEnum, TransactionStatusEnum
+from .types import Payment, PaymentInitialized, TransactionItem
from .utils import metadata_contains_empty_key
-if TYPE_CHECKING:
- from ...checkout import models as checkout_models
-
def description(enum):
if enum is None:
@@ -328,11 +347,14 @@ class PaymentCapture(BaseMutation):
)
try:
gateway.capture(
- payment, info.context.plugins, amount=amount, channel_slug=channel_slug
+ payment,
+ info.context.plugins,
+ amount=amount,
+ channel_slug=channel_slug,
)
payment.refresh_from_db()
except PaymentError as e:
- raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
+ raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR.value)
return PaymentCapture(payment=payment)
@@ -355,11 +377,14 @@ class PaymentRefund(PaymentCapture):
)
try:
gateway.refund(
- payment, info.context.plugins, amount=amount, channel_slug=channel_slug
+ payment,
+ info.context.plugins,
+ amount=amount,
+ channel_slug=channel_slug,
)
payment.refresh_from_db()
except PaymentError as e:
- raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
+ raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR.value)
return PaymentRefund(payment=payment)
@@ -389,7 +414,7 @@ class PaymentVoid(BaseMutation):
gateway.void(payment, info.context.plugins, channel_slug=channel_slug)
payment.refresh_from_db()
except PaymentError as e:
- raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
+ raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR.value)
return PaymentVoid(payment=payment)
@@ -549,3 +574,393 @@ class PaymentCheckBalance(BaseMutation):
)
}
)
+
+
+class TransactionUpdateInput(graphene.InputObjectType):
+ status = graphene.String(
+ description="Status of the transaction.",
+ )
+ type = graphene.String(
+ description="Payment type used for this transaction.",
+ )
+ reference = graphene.String(description="Reference of the transaction.")
+ available_actions = graphene.List(
+ graphene.NonNull(TransactionActionEnum),
+ description="List of all possible actions for the transaction",
+ )
+ amount_authorized = MoneyInput(description="Amount authorized by this transaction.")
+ amount_captured = MoneyInput(description="Amount captured by this transaction.")
+ amount_refunded = MoneyInput(description="Amount refunded by this transaction.")
+ amount_voided = MoneyInput(description="Amount voided by this transaction.")
+
+ metadata = graphene.List(
+ graphene.NonNull(MetadataInput),
+ description="Payment public metadata.",
+ required=False,
+ )
+ private_metadata = graphene.List(
+ graphene.NonNull(MetadataInput),
+ description="Payment private metadata.",
+ required=False,
+ )
+
+
+class TransactionCreateInput(TransactionUpdateInput):
+ status = graphene.String(description="Status of the transaction.", required=True)
+ type = graphene.String(
+ description="Payment type used for this transaction.", required=True
+ )
+
+
+class TransactionEventInput(graphene.InputObjectType):
+ status = graphene.Field(
+ TransactionStatusEnum,
+ required=True,
+ description="Current status of the payment transaction.",
+ )
+ reference = graphene.String(description="Reference of the transaction.")
+ name = graphene.String(description="Name of the transaction.")
+
+
+class TransactionCreate(BaseMutation):
+ transaction = graphene.Field(TransactionItem)
+
+ class Arguments:
+ id = graphene.ID(
+ description="The ID of the checkout or order.",
+ required=True,
+ )
+ transaction = TransactionCreateInput(
+ required=True,
+ description="Input data required to create a new transaction object.",
+ )
+ transaction_event = TransactionEventInput(
+ description="Data that defines a transaction event."
+ )
+
+ class Meta:
+ auto_permission_message = False
+ description = (
+ "Create transaction for checkout or order. Requires the "
+ "following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS."
+ + ADDED_IN_34
+ + PREVIEW_FEATURE
+ )
+ error_type_class = common_types.TransactionCreateError
+ permissions = (PaymentPermissions.HANDLE_PAYMENTS,)
+
+ @classmethod
+ def check_permissions(cls, context, permissions=None):
+ """Determine whether app has rights to perform this mutation."""
+ permissions = permissions or cls._meta.permissions
+ if app := getattr(context, "app", None):
+ return app.has_perms(permissions)
+ return False
+
+ @classmethod
+ def validate_metadata_keys(cls, metadata_list: List[dict], field_name, error_code):
+ if metadata_contains_empty_key(metadata_list):
+ raise ValidationError(
+ {
+ "transaction": ValidationError(
+ {
+ field_name: ValidationError(
+ "Metadata key cannot be empty.",
+ code=error_code,
+ )
+ }
+ )
+ }
+ )
+
+ @classmethod
+ def cleanup_money_data(cls, cleaned_data: dict):
+ if amount_authorized := cleaned_data.pop("amount_authorized", None):
+ cleaned_data["authorized_value"] = amount_authorized["amount"]
+ if amount_captured := cleaned_data.pop("amount_captured", None):
+ cleaned_data["captured_value"] = amount_captured["amount"]
+ if amount_refunded := cleaned_data.pop("amount_refunded", None):
+ cleaned_data["refunded_value"] = amount_refunded["amount"]
+ if amount_voided := cleaned_data.pop("amount_voided", None):
+ cleaned_data["voided_value"] = amount_voided["amount"]
+
+ @classmethod
+ def cleanup_metadata_data(cls, cleaned_data: dict):
+ if metadata := cleaned_data.pop("metadata", None):
+ cleaned_data["metadata"] = {data.key: data.value for data in metadata}
+ if private_metadata := cleaned_data.pop("private_metadata", None):
+ cleaned_data["private_metadata"] = {
+ data.key: data.value for data in private_metadata
+ }
+
+ @classmethod
+ def validate_instance(
+ cls, instance: Union[checkout_models.Checkout, order_models.Order], instance_id
+ ):
+ """Validate if provided instance is an order or checkout type."""
+ if not isinstance(instance, (checkout_models.Checkout, order_models.Order)):
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ f"Couldn't resolve to Checkout or Order: {instance_id}",
+ code=TransactionCreateErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+
+ @classmethod
+ def validate_money_input(
+ cls, transaction_data: dict, currency: str, error_code: str
+ ):
+ if not transaction_data:
+ return
+ money_input_fields = [
+ "amount_authorized",
+ "amount_captured",
+ "amount_refunded",
+ "amount_voided",
+ ]
+ errors = {}
+ for money_field_name in money_input_fields:
+ field = transaction_data.get(money_field_name)
+ if not field:
+ continue
+ if field["currency"] != currency:
+ errors[money_field_name] = ValidationError(
+ f"Currency needs to be the same as for order: {currency}",
+ code=error_code,
+ )
+ if errors:
+ raise ValidationError(errors)
+
+ @classmethod
+ def validate_input(
+ cls, instance: Union[checkout_models.Checkout, order_models.Order], input_data
+ ):
+ cls.validate_instance(instance, input_data.get("id"))
+ currency = instance.currency
+ transaction_data = input_data["transaction"]
+
+ cls.validate_money_input(
+ input_data["transaction"],
+ currency,
+ TransactionCreateErrorCode.INCORRECT_CURRENCY.value,
+ )
+ cls.validate_metadata_keys(
+ transaction_data.get("metadata", []),
+ field_name="metadata",
+ error_code=TransactionCreateErrorCode.METADATA_KEY_REQUIRED.value,
+ )
+ cls.validate_metadata_keys(
+ transaction_data.get("private_metadata", []),
+ field_name="privateMetadata",
+ error_code=TransactionCreateErrorCode.METADATA_KEY_REQUIRED.value,
+ )
+
+ @classmethod
+ def create_transaction(
+ cls, transaction_input: dict
+ ) -> payment_models.TransactionItem:
+ cls.cleanup_money_data(transaction_input)
+ cls.cleanup_metadata_data(transaction_input)
+ return payment_models.TransactionItem.objects.create(
+ **transaction_input,
+ )
+
+ @classmethod
+ def create_transaction_event(
+ cls, transaction_event_input: dict, transaction: payment_models.TransactionItem
+ ) -> payment_models.TransactionEvent:
+ return transaction.events.create(
+ status=transaction_event_input["status"],
+ reference=transaction_event_input.get("reference", ""),
+ name=transaction_event_input.get("name", ""),
+ transaction=transaction,
+ )
+
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ instance_id = data.get("id")
+ order_or_checkout_instance = cls.get_node_or_error(info, instance_id)
+
+ cls.validate_input(order_or_checkout_instance, data)
+ transaction_data = {**data["transaction"]}
+ transaction_data["currency"] = order_or_checkout_instance.currency
+ transaction_event_data = data.get("transaction_event")
+ if isinstance(order_or_checkout_instance, checkout_models.Checkout):
+ transaction_data["checkout_id"] = order_or_checkout_instance.pk
+ else:
+ transaction_data["order_id"] = order_or_checkout_instance.pk
+ if transaction_event_data:
+ transaction_event(
+ order=order_or_checkout_instance,
+ user=info.context.user,
+ app=info.context.app,
+ reference=transaction_event_data.get("reference", ""),
+ status=transaction_event_data["status"],
+ name=transaction_event_data.get("name", ""),
+ )
+ transaction = cls.create_transaction(transaction_data)
+ if transaction_event_data:
+ cls.create_transaction_event(transaction_event_data, transaction)
+ return TransactionCreate(transaction=transaction)
+
+
+class TransactionUpdate(TransactionCreate):
+ transaction = graphene.Field(TransactionItem)
+
+ class Arguments:
+ id = graphene.ID(
+ description="The ID of the transaction.",
+ required=True,
+ )
+ transaction = TransactionUpdateInput(
+ description="Input data required to create a new transaction object.",
+ )
+ transaction_event = TransactionEventInput(
+ description="Data that defines a transaction transaction."
+ )
+
+ class Meta:
+ auto_permission_message = False
+ description = (
+ "Create transaction for checkout or order. Requires the "
+ "following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS."
+ + ADDED_IN_34
+ + PREVIEW_FEATURE
+ )
+ error_type_class = common_types.TransactionUpdateError
+ permissions = (PaymentPermissions.HANDLE_PAYMENTS,)
+ object_type = TransactionItem
+
+ @classmethod
+ def validate_transaction_input(
+ cls, instance: payment_models.TransactionItem, transaction_data
+ ):
+ currency = instance.currency
+ cls.validate_money_input(
+ transaction_data,
+ currency,
+ TransactionUpdateErrorCode.INCORRECT_CURRENCY.value,
+ )
+ cls.validate_metadata_keys(
+ transaction_data.get("metadata", []),
+ field_name="metadata",
+ error_code=TransactionUpdateErrorCode.METADATA_KEY_REQUIRED.value,
+ )
+ cls.validate_metadata_keys(
+ transaction_data.get("private_metadata", []),
+ field_name="privateMetadata",
+ error_code=TransactionUpdateErrorCode.METADATA_KEY_REQUIRED.value,
+ )
+
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ instance_id = data.get("id")
+ instance = cls.get_node_or_error(info, instance_id, only_type=TransactionItem)
+ transaction_data = data.get("transaction")
+ if transaction_data:
+ cls.validate_transaction_input(instance, transaction_data)
+ cls.cleanup_money_data(transaction_data)
+ cls.cleanup_metadata_data(transaction_data)
+ instance = cls.construct_instance(instance, transaction_data)
+ instance.save()
+
+ if transaction_event_data := data.get("transaction_event"):
+ cls.create_transaction_event(transaction_event_data, instance)
+ if instance.order_id:
+ transaction_event(
+ order=instance.order,
+ user=info.context.user,
+ app=info.context.app,
+ reference=transaction_event_data.get("reference", ""),
+ status=transaction_event_data["status"],
+ name=transaction_event_data.get("name", ""),
+ )
+ return TransactionUpdate(transaction=instance)
+
+
+class TransactionRequestAction(BaseMutation):
+ transaction = graphene.Field(TransactionItem)
+
+ class Arguments:
+ id = graphene.ID(
+ description="The ID of the transaction.",
+ required=True,
+ )
+ action_type = graphene.Argument(
+ TransactionActionEnum,
+ required=True,
+ description="Determines the action type.",
+ )
+ amount = PositiveDecimal(
+ description=(
+ "Transaction request amount. If empty for refund or capture, maximal "
+ "possible amount will be used."
+ )
+ )
+
+ class Meta:
+ description = (
+ "Request an action for payment transaction." + ADDED_IN_34 + PREVIEW_FEATURE
+ )
+ error_type_class = common_types.TransactionRequestActionError
+ permissions = (
+ PaymentPermissions.HANDLE_PAYMENTS,
+ OrderPermissions.MANAGE_ORDERS,
+ )
+
+ @classmethod
+ def check_permissions(cls, context, permissions=None):
+ required_permissions = permissions or cls._meta.permissions
+ requestor = get_user_or_app_from_context(context)
+ for required_permission in required_permissions:
+ # We want to allow to call this mutation for requestor with one of following
+ # permission: manage_orders, handle_payments
+ if requestor.has_perm(required_permission):
+ return True
+ return False
+
+ @classmethod
+ def handle_transaction_action(
+ cls, action, action_kwargs, action_value: Optional[Decimal]
+ ):
+ if action == TransactionAction.VOID:
+ request_void_action(**action_kwargs)
+ elif action == TransactionAction.CAPTURE:
+ transaction = action_kwargs["transaction"]
+ action_value = action_value or transaction.authorized_value
+ action_value = min(action_value, transaction.authorized_value)
+ request_capture_action(**action_kwargs, capture_value=action_value)
+ elif action == TransactionAction.REFUND:
+ transaction = action_kwargs["transaction"]
+ action_value = action_value or transaction.captured_value
+ action_value = min(action_value, transaction.captured_value)
+ request_refund_action(**action_kwargs, refund_value=action_value)
+
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ id = data["id"]
+ action_type = data["action_type"]
+ action_value = data.get("amount")
+ transaction = cls.get_node_or_error(info, id, only_type=TransactionItem)
+ channel_slug = (
+ transaction.order.channel.slug
+ if transaction.order_id
+ else transaction.checkout.channel.slug
+ )
+ action_kwargs = {
+ "channel_slug": channel_slug,
+ "user": info.context.user,
+ "app": info.context.app,
+ "transaction": transaction,
+ "manager": info.context.plugins,
+ }
+
+ try:
+ cls.handle_transaction_action(action_type, action_kwargs, action_value)
+ except PaymentError as e:
+ error_enum = TransactionRequestActionErrorCode
+ code = error_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
+ raise ValidationError(str(e), code=code)
+ return TransactionRequestAction(transaction=transaction)
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index 4fd440a924..600e5c083f 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -11,6 +11,9 @@ from .mutations import (
PaymentInitialize,
PaymentRefund,
PaymentVoid,
+ TransactionCreate,
+ TransactionRequestAction,
+ TransactionUpdate,
)
from .resolvers import resolve_payment_by_id, resolve_payments
from .types import Payment, PaymentCountableConnection
@@ -52,3 +55,7 @@ class PaymentMutations(graphene.ObjectType):
payment_void = PaymentVoid.Field()
payment_initialize = PaymentInitialize.Field()
payment_check_balance = PaymentCheckBalance.Field()
+
+ transaction_create = TransactionCreate.Field()
+ transaction_update = TransactionUpdate.Field()
+ transaction_request_action = TransactionRequestAction.Field()
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_create.py b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
similarity index 100%
rename from saleor/graphql/payment/tests/mutations/test_payment_create.py
rename to saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_capture.py b/saleor/graphql/payment/tests/mutations/test_payment_capture.py
index 2b4a5b6348..362fc78ccc 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_capture.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_capture.py
@@ -11,7 +11,7 @@ from .....payment.models import ChargeStatus
from ....tests.utils import get_graphql_content
CAPTURE_QUERY = """
- mutation PaymentCapture($paymentId: ID!, $amount: PositiveDecimal!) {
+ mutation PaymentCapture($paymentId: ID!, $amount: PositiveDecimal) {
paymentCapture(paymentId: $paymentId, amount: $amount) {
payment {
id,
@@ -20,6 +20,7 @@ CAPTURE_QUERY = """
errors {
field
message
+ code
}
}
}
@@ -81,7 +82,11 @@ def test_payment_capture_with_payment_non_authorized_yet(
content = get_graphql_content(response)
data = content["data"]["paymentCapture"]
assert data["errors"] == [
- {"field": None, "message": "Cannot find successful auth transaction."}
+ {
+ "field": None,
+ "message": "Cannot find successful auth transaction.",
+ "code": "PAYMENT_ERROR",
+ }
]
@@ -104,7 +109,9 @@ def test_payment_capture_gateway_error(
# then
content = get_graphql_content(response)
data = content["data"]["paymentCapture"]
- assert data["errors"] == [{"field": None, "message": "Unable to process capture"}]
+ assert data["errors"] == [
+ {"field": None, "message": "Unable to process capture", "code": "PAYMENT_ERROR"}
+ ]
payment_txn_preauth.refresh_from_db()
assert payment.charge_status == ChargeStatus.NOT_CHARGED
@@ -149,7 +156,9 @@ def test_payment_capture_gateway_dummy_credit_card_error(
# then
content = get_graphql_content(response)
data = content["data"]["paymentCapture"]
- assert data["errors"] == [{"field": None, "message": error}]
+ assert data["errors"] == [
+ {"field": None, "message": error, "code": "PAYMENT_ERROR"}
+ ]
payment_txn_preauth.refresh_from_db()
assert payment.charge_status == ChargeStatus.NOT_CHARGED
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_refund.py b/saleor/graphql/payment/tests/mutations/test_payment_refund.py
index 69616e38ba..80f72cee62 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_refund.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_refund.py
@@ -1,11 +1,12 @@
import graphene
-from saleor.graphql.tests.utils import get_graphql_content
-from saleor.payment import TransactionKind
-from saleor.payment.models import ChargeStatus
+from .....payment import TransactionKind
+from .....payment.models import ChargeStatus
+from ....core.enums import PaymentErrorCode
+from ....tests.utils import get_graphql_content
REFUND_QUERY = """
- mutation PaymentRefund($paymentId: ID!, $amount: PositiveDecimal!) {
+ mutation PaymentRefund($paymentId: ID!, $amount: PositiveDecimal) {
paymentRefund(paymentId: $paymentId, amount: $amount) {
payment {
id,
@@ -14,6 +15,7 @@ REFUND_QUERY = """
errors {
field
message
+ code
}
}
}
@@ -78,7 +80,13 @@ def test_payment_refund_error(
content = get_graphql_content(response)
data = content["data"]["paymentRefund"]
- assert data["errors"] == [{"field": None, "message": "Unable to process refund"}]
+ assert data["errors"] == [
+ {
+ "field": None,
+ "message": "Unable to process refund",
+ "code": PaymentErrorCode.PAYMENT_ERROR.name,
+ }
+ ]
payment.refresh_from_db()
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
assert payment.transactions.count() == 2
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_void.py b/saleor/graphql/payment/tests/mutations/test_payment_void.py
index 00a344df85..f8ff2389d8 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_void.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_void.py
@@ -13,6 +13,7 @@ VOID_QUERY = """
errors {
field
message
+ code
}
}
}
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
new file mode 100644
index 0000000000..b2d62d784b
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -0,0 +1,586 @@
+from decimal import Decimal
+
+import graphene
+import pytest
+
+from .....order import OrderEvents
+from .....payment import TransactionStatus
+from .....payment.error_codes import TransactionCreateErrorCode
+from .....payment.models import TransactionItem
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import TransactionActionEnum, TransactionStatusEnum
+
+MUTATION_TRANSACTION_CREATE = """
+mutation TransactionCreate(
+ $id: ID!,
+ $transaction_event: TransactionEventInput,
+ $transaction: TransactionCreateInput!
+ ){
+ transactionCreate(
+ id: $id,
+ transactionEvent: $transaction_event,
+ transaction: $transaction
+ ){
+ transaction{
+ id
+ actions
+ reference
+ type
+ status
+ modifiedAt
+ createdAt
+ authorizedAmount{
+ amount
+ currency
+ }
+ voidedAmount{
+ currency
+ amount
+ }
+ capturedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ events{
+ status
+ reference
+ name
+ createdAt
+ }
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
+def test_transaction_create_for_order(
+ order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CAPTURE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction = order_with_lines.payment_transactions.first()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionCreate"]["transaction"]
+ assert data["actions"] == available_actions
+ assert data["status"] == status
+ assert data["reference"] == reference
+ assert data["authorizedAmount"]["amount"] == authorized_value
+
+ assert available_actions == list(map(str.upper, transaction.available_actions))
+ assert status == transaction.status
+ assert reference == transaction.reference
+ assert authorized_value == transaction.authorized_value
+ assert transaction.metadata == {metadata["key"]: metadata["value"]}
+ assert transaction.private_metadata == {
+ private_metadata["key"]: private_metadata["value"]
+ }
+
+
+def test_transaction_create_for_checkout(
+ checkout_with_items, permission_manage_payments, app_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CAPTURE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout_with_items.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction = checkout_with_items.payment_transactions.first()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionCreate"]["transaction"]
+ assert data["actions"] == available_actions
+ assert data["status"] == status
+ assert data["reference"] == reference
+ assert data["authorizedAmount"]["amount"] == authorized_value
+
+ assert available_actions == list(map(str.upper, transaction.available_actions))
+ assert status == transaction.status
+ assert reference == transaction.reference
+ assert authorized_value == transaction.authorized_value
+ assert transaction.metadata == {metadata["key"]: metadata["value"]}
+ assert transaction.private_metadata == {
+ private_metadata["key"]: private_metadata["value"]
+ }
+
+
+ "amount_field_name, amount_db_field",
+ [
+ ("amountAuthorized", "authorized_value"),
+ ("amountCaptured", "captured_value"),
+ ("amountVoided", "voided_value"),
+ ("amountRefunded", "refunded_value"),
+ ],
+)
+def test_transaction_create_calculate_amount(
+ amount_field_name,
+ amount_db_field,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ expected_value = Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": [],
+ amount_field_name: {
+ "amount": expected_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction = TransactionItem.objects.first()
+ get_graphql_content(response)
+
+ assert getattr(transaction, amount_db_field) == expected_value
+
+
+def test_transaction_create_multiple_amounts_provided(
+ order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CAPTURE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ captured_value = Decimal("11")
+ refunded_value = Decimal("12")
+ voided_value = Decimal("13")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "amountCaptured": {
+ "amount": captured_value,
+ "currency": "USD",
+ },
+ "amountRefunded": {
+ "amount": refunded_value,
+ "currency": "USD",
+ },
+ "amountVoided": {
+ "amount": voided_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction = TransactionItem.objects.first()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionCreate"]["transaction"]
+ assert data["actions"] == available_actions
+ assert data["status"] == status
+ assert data["reference"] == reference
+ assert data["authorizedAmount"]["amount"] == authorized_value
+ assert data["capturedAmount"]["amount"] == captured_value
+ assert data["refundedAmount"]["amount"] == refunded_value
+ assert data["voidedAmount"]["amount"] == voided_value
+
+ assert transaction.authorized_value == authorized_value
+ assert transaction.captured_value == captured_value
+ assert transaction.voided_value == voided_value
+ assert transaction.refunded_value == refunded_value
+
+
+def test_transaction_create_create_event_for_order(
+ order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CAPTURE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ transaction_status = "PENDING"
+ transaction_reference = "transaction reference"
+ transaction_name = "Processing transaction"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ },
+ "transaction_event": {
+ "status": transaction_status,
+ "reference": transaction_reference,
+ "name": transaction_name,
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ event = order_with_lines.events.first()
+
+ assert event.type == OrderEvents.TRANSACTION_EVENT
+ assert event.parameters == {
+ "message": transaction_name,
+ "reference": transaction_reference,
+ "status": transaction_status.lower(),
+ }
+
+
+def test_transaction_create_permission_denied_for_staff(
+ order_with_lines, staff_api_client, permission_manage_payments
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CAPTURE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_transaction_create_missing_app_permission(order_with_lines, app_api_client):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CAPTURE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(MUTATION_TRANSACTION_CREATE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+ "amount_field_name, amount_db_field",
+ [
+ ("amountAuthorized", "authorized_value"),
+ ("amountCaptured", "captured_value"),
+ ("amountVoided", "voided_value"),
+ ("amountRefunded", "refunded_value"),
+ ],
+)
+def test_transaction_create_incorrect_currency(
+ amount_field_name,
+ amount_db_field,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ expected_value = Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": [],
+ amount_field_name: {
+ "amount": expected_value,
+ "currency": "PLN",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionCreate"]
+ assert data["errors"][0]["field"] == amount_field_name
+ assert (
+ data["errors"][0]["code"] == TransactionCreateErrorCode.INCORRECT_CURRENCY.name
+ )
+
+
+def test_creates_transaction_event_for_order(
+ order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ status = "Failed authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ available_actions = []
+ authorized_value = Decimal("0")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ event_status = TransactionStatus.FAILURE
+ event_reference = "PSP-ref"
+ event_name = "Failed authorization"
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ "transaction_event": {
+ "status": TransactionStatusEnum.FAILURE.name,
+ "reference": event_reference,
+ "name": event_name,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction = order_with_lines.payment_transactions.first()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionCreate"]["transaction"]
+
+ events_data = data["events"]
+ assert len(events_data) == 1
+ event_data = events_data[0]
+ assert event_data["name"] == event_name
+ assert event_data["status"] == TransactionStatusEnum.FAILURE.name
+ assert event_data["reference"] == event_reference
+
+ assert transaction.events.count() == 1
+ event = transaction.events.first()
+ assert event.name == event_name
+ assert event.status == event_status
+ assert event.reference == event_reference
+
+
+def test_creates_transaction_event_for_checkout(
+ checkout_with_items, permission_manage_payments, app_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CAPTURE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ event_status = TransactionStatus.FAILURE
+ event_reference = "PSP-ref"
+ event_name = "Failed authorization"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout_with_items.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ "transaction_event": {
+ "status": TransactionStatusEnum.FAILURE.name,
+ "reference": event_reference,
+ "name": event_name,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction = checkout_with_items.payment_transactions.first()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionCreate"]["transaction"]
+
+ events_data = data["events"]
+ assert len(events_data) == 1
+ event_data = events_data[0]
+ assert event_data["name"] == event_name
+ assert event_data["status"] == TransactionStatusEnum.FAILURE.name
+ assert event_data["reference"] == event_reference
+
+ assert transaction.events.count() == 1
+ event = transaction.events.first()
+ assert event.name == event_name
+ assert event.status == event_status
+ assert event.reference == event_reference
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
new file mode 100644
index 0000000000..99834bfeb7
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -0,0 +1,574 @@
+from decimal import Decimal
+
+import graphene
+import pytest
+from mock import patch
+
+from .....order import OrderEvents
+from .....payment import TransactionAction
+from .....payment.interface import TransactionActionData
+from .....payment.models import TransactionItem
+from ....core.enums import TransactionRequestActionErrorCode
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import TransactionActionEnum
+
+MUTATION_TRANSACTION_REQUEST_ACTION = """
+mutation TransactionRequestAction(
+ $id: ID!,
+ $action_type: TransactionActionEnum!,
+ $amount: PositiveDecimal
+ ){
+ transactionRequestAction(
+ id: $id,
+ actionType: $action_type,
+ amount: $amount
+ ){
+ transaction{
+ id
+ actions
+ reference
+ type
+ status
+ modifiedAt
+ createdAt
+ authorizedAmount{
+ amount
+ currency
+ }
+ voidedAmount{
+ currency
+ amount
+ }
+ capturedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
+ "capture_amount, expected_called_capture_amount",
+ [
+ (Decimal("8.00"), Decimal("8.00")),
+ (None, Decimal("10.00")),
+ (Decimal("100"), Decimal("10.00")),
+ ],
+)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_transaction_request_capture_action_for_order(
+ mocked_payment_action_request,
+ mocked_is_active,
+ capture_amount,
+ expected_called_capture_amount,
+ order_with_lines,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ authorized_value=Decimal("10"),
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.CAPTURE.name,
+ "amount": capture_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CAPTURE,
+ action_value=expected_called_capture_amount,
+ ),
+ channel_slug=order_with_lines.channel.slug,
+ )
+
+ event = order_with_lines.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED
+ assert Decimal(event.parameters["amount"]) == expected_called_capture_amount
+ assert event.parameters["reference"] == transaction.reference
+
+
+ "refund_amount, expected_called_refund_amount",
+ [
+ (Decimal("8.00"), Decimal("8.00")),
+ (None, Decimal("10.00")),
+ (Decimal("100"), Decimal("10.00")),
+ ],
+)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_transaction_request_refund_action_for_order(
+ mocked_payment_action_request,
+ mocked_is_active,
+ refund_amount,
+ expected_called_refund_amount,
+ order_with_lines,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ captured_value=Decimal("10"),
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "amount": refund_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=expected_called_refund_amount,
+ ),
+ channel_slug=order_with_lines.channel.slug,
+ )
+
+ event = order_with_lines.events.first()
+ assert event.type == OrderEvents.TRANSACTION_REFUND_REQUESTED
+ assert Decimal(event.parameters["amount"]) == expected_called_refund_amount
+ assert event.parameters["reference"] == transaction.reference
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_transaction_request_void_action_for_order(
+ mocked_payment_action_request,
+ mocked_is_active,
+ order_with_lines,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ authorized_value=Decimal("10"),
+ )
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.VOID.name,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.VOID,
+ action_value=None,
+ ),
+ channel_slug=order_with_lines.channel.slug,
+ )
+
+ event = order_with_lines.events.first()
+ assert event.type == OrderEvents.TRANSACTION_VOID_REQUESTED
+ assert event.parameters["reference"] == transaction.reference
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_transaction_request_void_action_for_checkout(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ authorized_value=Decimal("10"),
+ )
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.VOID.name,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.VOID,
+ action_value=None,
+ ),
+ channel_slug=checkout.channel.slug,
+ )
+
+
+ "capture_amount, expected_called_capture_amount",
+ [
+ (Decimal("8.00"), Decimal("8.00")),
+ (None, Decimal("10.00")),
+ (Decimal("100"), Decimal("10.00")),
+ ],
+)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_transaction_request_capture_action_for_checkout(
+ mocked_payment_action_request,
+ mocked_is_active,
+ capture_amount,
+ expected_called_capture_amount,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ authorized_value=Decimal("10"),
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.CAPTURE.name,
+ "amount": capture_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CAPTURE,
+ action_value=expected_called_capture_amount,
+ ),
+ channel_slug=checkout.channel.slug,
+ )
+
+
+ "refund_amount, expected_called_refund_amount",
+ [
+ (Decimal("8.00"), Decimal("8.00")),
+ (None, Decimal("10.00")),
+ (Decimal("100"), Decimal("10.00")),
+ ],
+)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_transaction_request_refund_action_for_checkout(
+ mocked_payment_action_request,
+ mocked_is_active,
+ refund_amount,
+ expected_called_refund_amount,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ captured_value=Decimal("10"),
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "amount": refund_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=expected_called_refund_amount,
+ ),
+ channel_slug=checkout.channel.slug,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_transaction_request_uses_handle_payment_permission(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ captured_value=Decimal("10"),
+ )
+ refund_amount = Decimal("1")
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "amount": refund_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=refund_amount,
+ ),
+ channel_slug=checkout.channel.slug,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_transaction_request_uses_manage_orders_permission(
+ mocked_payment_action_request,
+ mocked_is_active,
+ order,
+ app_api_client,
+ permission_manage_orders,
+):
+ # given
+ mocked_is_active.return_value = True
+
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ captured_value=Decimal("10"),
+ )
+ refund_amount = Decimal("1")
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "amount": refund_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_orders],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=refund_amount,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+
+def test_transaction_request_action_missing_permission(
+ app_api_client, order_with_lines
+):
+ # given
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ authorized_value=Decimal("10"),
+ )
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.VOID.name,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION, variables, permissions=[]
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_transaction_request_action_missing_event(
+ mocked_is_active, staff_api_client, permission_manage_payments, order
+):
+ # given
+ authorization_value = Decimal("10")
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=authorization_value,
+ )
+ mocked_is_active.return_value = False
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.VOID.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[
+ permission_manage_payments,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionRequestAction"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["message"] == (
+ "No app or plugin is configured to handle payment action requests."
+ )
+ code_enum = TransactionRequestActionErrorCode
+ assert data["errors"][0]["code"] == (
+ code_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.name
+ )
+
+ assert mocked_is_active.called
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
new file mode 100644
index 0000000000..50c6ab38d5
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -0,0 +1,432 @@
+from decimal import Decimal
+
+import graphene
+import pytest
+
+from .....order import OrderEvents
+from .....payment import TransactionStatus
+from .....payment.error_codes import TransactionUpdateErrorCode
+from .....payment.models import TransactionItem
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import TransactionActionEnum, TransactionStatusEnum
+
+MUTATION_TRANSACTION_UPDATE = """
+mutation TransactionUpdate(
+ $id: ID!,
+ $transaction_event: TransactionEventInput,
+ $transaction: TransactionUpdateInput
+ ){
+ transactionUpdate(
+ id: $id,
+ transactionEvent: $transaction_event,
+ transaction: $transaction
+ ){
+ transaction{
+ id
+ actions
+ reference
+ type
+ status
+ modifiedAt
+ createdAt
+ authorizedAmount{
+ amount
+ currency
+ }
+ voidedAmount{
+ currency
+ amount
+ }
+ capturedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ events{
+ status
+ reference
+ name
+ createdAt
+ }
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
+def transaction(order_with_lines):
+ return TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ authorized_value=Decimal("10"),
+ )
+
+
+def test_transaction_update_status(
+ transaction, permission_manage_payments, app_api_client
+):
+ # given
+ status = "Captured for 10$"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "status": status,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["status"] == status
+ assert transaction.status == status
+
+
+def test_transaction_update_type(
+ transaction, permission_manage_payments, app_api_client
+):
+ # given
+ type = "New credit card"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "type": type,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["type"] == type
+ assert transaction.type == type
+
+
+def test_transaction_update_reference(
+ transaction, permission_manage_payments, app_api_client
+):
+ # given
+ reference = "PSP:123AAA"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "reference": reference,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["reference"] == reference
+ assert transaction.reference == reference
+
+
+def test_transaction_update_available_actions(
+ transaction, permission_manage_payments, app_api_client
+):
+ # given
+ available_actions = [TransactionActionEnum.REFUND.name]
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "availableActions": available_actions,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["actions"] == available_actions
+ assert transaction.available_actions == ["refund"]
+
+
+ "field_name, response_field, db_field_name, value",
+ [
+ ("amountAuthorized", "authorizedAmount", "authorized_value", Decimal("12")),
+ ("amountCaptured", "capturedAmount", "captured_value", Decimal("13")),
+ ("amountVoided", "voidedAmount", "voided_value", Decimal("14")),
+ ("amountRefunded", "refundedAmount", "refunded_value", Decimal("15")),
+ ],
+)
+def test_transaction_update_amounts(
+ field_name,
+ response_field,
+ db_field_name,
+ value,
+ transaction,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {field_name: {"amount": value, "currency": "USD"}},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data[response_field]["amount"] == value
+ assert getattr(transaction, db_field_name) == value
+
+
+def test_transaction_update_multiple_amounts_provided(
+ transaction, permission_manage_payments, app_api_client
+):
+ # given
+ authorized_value = Decimal("10")
+ captured_value = Decimal("11")
+ refunded_value = Decimal("12")
+ voided_value = Decimal("13")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "amountCaptured": {
+ "amount": captured_value,
+ "currency": "USD",
+ },
+ "amountRefunded": {
+ "amount": refunded_value,
+ "currency": "USD",
+ },
+ "amountVoided": {
+ "amount": voided_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction = TransactionItem.objects.first()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["authorizedAmount"]["amount"] == authorized_value
+ assert data["capturedAmount"]["amount"] == captured_value
+ assert data["refundedAmount"]["amount"] == refunded_value
+ assert data["voidedAmount"]["amount"] == voided_value
+
+ assert transaction.authorized_value == authorized_value
+ assert transaction.captured_value == captured_value
+ assert transaction.voided_value == voided_value
+ assert transaction.refunded_value == refunded_value
+
+
+def test_transaction_update_permission_denied_for_staff(
+ transaction, staff_api_client, permission_manage_payments
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_transaction_update_for_order_missing_app_permission(
+ transaction, app_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(MUTATION_TRANSACTION_UPDATE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+ "amount_field_name, amount_db_field",
+ [
+ ("amountAuthorized", "authorized_value"),
+ ("amountCaptured", "captured_value"),
+ ("amountVoided", "voided_value"),
+ ("amountRefunded", "refunded_value"),
+ ],
+)
+def test_transaction_update_incorrect_currency(
+ amount_field_name,
+ amount_db_field,
+ transaction,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ expected_value = Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ amount_field_name: {
+ "amount": expected_value,
+ "currency": "PLN",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]
+ assert data["errors"][0]["field"] == amount_field_name
+ assert (
+ data["errors"][0]["code"] == TransactionUpdateErrorCode.INCORRECT_CURRENCY.name
+ )
+
+
+def test_transaction_update_adds_transaction_event_to_order(
+ transaction, order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ transaction_status = "PENDING"
+ transaction_reference = "transaction reference"
+ transaction_name = "Processing transaction"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction_event": {
+ "status": transaction_status,
+ "reference": transaction_reference,
+ "name": transaction_name,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+ # then
+ event = order_with_lines.events.first()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]
+
+ assert not data["errors"]
+ assert event.type == OrderEvents.TRANSACTION_EVENT
+ assert event.parameters == {
+ "message": transaction_name,
+ "reference": transaction_reference,
+ "status": transaction_status.lower(),
+ }
+
+
+def test_creates_transaction_event_for_order(
+ transaction, order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = order_with_lines.payment_transactions.first()
+ event_status = TransactionStatus.FAILURE
+ event_reference = "PSP-ref"
+ event_name = "Failed authorization"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction_event": {
+ "status": TransactionStatusEnum.FAILURE.name,
+ "reference": event_reference,
+ "name": event_name,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+
+ events_data = data["events"]
+ assert len(events_data) == 1
+ event_data = events_data[0]
+ assert event_data["name"] == event_name
+ assert event_data["status"] == TransactionStatusEnum.FAILURE.name
+ assert event_data["reference"] == event_reference
+
+ assert transaction.events.count() == 1
+ event = transaction.events.first()
+ assert event.name == event_name
+ assert event.status == event_status
+ assert event.reference == event_reference
diff --git a/saleor/graphql/payment/tests/queries/test_payments_query.py b/saleor/graphql/payment/tests/queries/test_payments_query.py
index ee95442ea2..ea28cdef2f 100644
--- a/saleor/graphql/payment/tests/queries/test_payments_query.py
+++ b/saleor/graphql/payment/tests/queries/test_payments_query.py
@@ -4,7 +4,7 @@ from decimal import Decimal
import graphene
from ....tests.utils import get_graphql_content, get_graphql_content_from_response
-from ...enums import OrderAction, PaymentChargeStatusEnum
+from ...enums import PaymentChargeStatusEnum, TransactionActionEnum
PAYMENT_QUERY = """ query Payments($filter: PaymentFilterInput){
payments(first: 20, filter: $filter) {
@@ -12,10 +12,6 @@ PAYMENT_QUERY = """ query Payments($filter: PaymentFilterInput){
node {
id
gateway
- capturedAmount {
- amount
- currency
- }
total {
amount
currency
@@ -30,6 +26,10 @@ PAYMENT_QUERY = """ query Payments($filter: PaymentFilterInput){
amount
}
}
+ capturedAmount{
+ currency
+ amount
+ }
}
}
}
@@ -54,7 +54,7 @@ def test_payments_query(
assert Decimal(total) == pay.total
assert data["total"]["currency"] == pay.currency
assert data["chargeStatus"] == PaymentChargeStatusEnum.FULLY_CHARGED.name
- assert data["actions"] == [OrderAction.REFUND.name]
+ assert data["actions"] == [TransactionActionEnum.REFUND.name]
txn = pay.transactions.get()
assert data["transactions"] == [
{
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index 11c2f18098..869840ca8a 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -7,14 +7,21 @@ from ...core.tracing import traced_resolver
from ...payment import models
from ..checkout.dataloaders import CheckoutByTokenLoader
from ..core.connection import CountableConnection
-from ..core.descriptions import ADDED_IN_31
+from ..core.descriptions import ADDED_IN_31, ADDED_IN_34, PREVIEW_FEATURE
from ..core.fields import JSONString, PermissionsField
from ..core.types import ModelObjectType, Money, NonNullList
from ..meta.permissions import public_payment_permissions
from ..meta.resolvers import resolve_metadata
from ..meta.types import MetadataItem, ObjectWithMetadata
from ..utils import get_user_or_app_from_context
-from .enums import OrderAction, PaymentChargeStatusEnum, TransactionKindEnum
+from .dataloaders import TransactionEventByTransactionIdLoader
+from .enums import (
+ OrderAction,
+ PaymentChargeStatusEnum,
+ TransactionActionEnum,
+ TransactionKindEnum,
+ TransactionStatusEnum,
+)
class Transaction(ModelObjectType):
@@ -232,3 +239,82 @@ class PaymentInitialized(graphene.ObjectType):
gateway = graphene.String(description="ID of a payment gateway.", required=True)
name = graphene.String(description="Payment gateway name.", required=True)
data = JSONString(description="Initialized data by gateway.", required=False)
+
+
+class TransactionEvent(ModelObjectType):
+ created_at = graphene.DateTime(required=True)
+ status = graphene.Field(
+ TransactionStatusEnum,
+ description="Status of transaction's event.",
+ required=True,
+ )
+ reference = graphene.String(
+ description="Reference of transaction's event.", required=True
+ )
+ name = graphene.String(description="Name of the transaction's event.")
+
+ class Meta:
+ description = "Represents transaction's event."
+ interfaces = [relay.Node]
+ model = models.TransactionEvent
+
+
+class TransactionItem(ModelObjectType):
+ created_at = graphene.DateTime(required=True)
+ modified_at = graphene.DateTime(required=True)
+ actions = NonNullList(
+ TransactionActionEnum,
+ description=(
+ "List of actions that can be performed in the current state of a payment."
+ ),
+ required=True,
+ )
+ authorized_amount = graphene.Field(
+ Money, required=True, description="Total amount authorized for this payment."
+ )
+ refunded_amount = graphene.Field(
+ Money, required=True, description="Total amount refunded for this payment."
+ )
+ voided_amount = graphene.Field(
+ Money, required=True, description="Total amount voided for this payment."
+ )
+ captured_amount = graphene.Field(
+ Money, description="Total amount captured for this payment.", required=True
+ )
+ status = graphene.String(description="Status of transaction.", required=True)
+ type = graphene.String(description="Type of transaction.", required=True)
+ reference = graphene.String(description="Reference of transaction.", required=True)
+ events = NonNullList(
+ TransactionEvent, required=True, description="List of all transaction's events."
+ )
+
+ class Meta:
+ description = (
+ "Represents a payment transaction." + ADDED_IN_34 + PREVIEW_FEATURE
+ )
+ interfaces = [relay.Node, ObjectWithMetadata]
+ model = models.TransactionItem
+
+ @staticmethod
+ def resolve_actions(root: models.TransactionItem, _info):
+ return root.available_actions
+
+ @staticmethod
+ def resolve_captured_amount(root: models.TransactionItem, _info):
+ return root.amount_captured
+
+ @staticmethod
+ def resolve_authorized_amount(root: models.TransactionItem, _info):
+ return root.amount_authorized
+
+ @staticmethod
+ def resolve_voided_amount(root: models.TransactionItem, _info):
+ return root.amount_voided
+
+ @staticmethod
+ def resolve_refunded_amount(root: models.TransactionItem, _info):
+ return root.amount_refunded
+
+ @staticmethod
+ def resolve_events(root: models.TransactionItem, info):
+ return TransactionEventByTransactionIdLoader(info.context).load(root.id)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index ad480628c2..b63a407f92 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1466,6 +1466,7 @@ enum WebhookEventTypeEnum {
"""A shipping zone is deleted."""
SHIPPING_ZONE_DELETED
+ TRANSACTION_ACTION_REQUEST
TRANSLATION_CREATED
TRANSLATION_UPDATED
PAYMENT_AUTHORIZE
@@ -1665,6 +1666,7 @@ enum WebhookEventTypeAsyncEnum {
"""A shipping zone is deleted."""
SHIPPING_ZONE_DELETED
+ TRANSACTION_ACTION_REQUEST
TRANSLATION_CREATED
TRANSLATION_UPDATED
}
@@ -2173,6 +2175,7 @@ enum WebhookSampleEventTypeEnum {
SHIPPING_ZONE_CREATED
SHIPPING_ZONE_UPDATED
SHIPPING_ZONE_DELETED
+ TRANSACTION_ACTION_REQUEST
TRANSLATION_CREATED
TRANSLATION_UPDATED
}
@@ -7094,6 +7097,15 @@ type Checkout implements Node & ObjectWithMetadata {
"""Checkout language code."""
languageCode: LanguageCodeEnum!
+
+ """
+ List of transactions for the checkout. Requires one of the following permissions: MANAGE_CHECKOUTS, HANDLE_PAYMENTS.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ transactions: [TransactionItem!]
}
"""
@@ -7390,6 +7402,132 @@ Note: this API is currently in Feature Preview and can be subject to changes at
"""
union DeliveryMethod = Warehouse | ShippingMethod
+"""
+Represents a payment transaction.
+
+Added in Saleor 3.4.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionItem implements Node & ObjectWithMetadata {
+ """The ID of the object."""
+ id: ID!
+
+ """List of private metadata items. Requires staff permissions to access."""
+ privateMetadata: [MetadataItem!]!
+
+ """
+ A single key from private metadata. Requires staff permissions to access.
+
+ Tip: Use GraphQL aliases to fetch multiple keys.
+
+ Added in Saleor 3.3.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ privateMetafield(key: String!): String
+
+ """
+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.
+
+ Added in Saleor 3.3.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ privateMetafields(keys: [String!]): Metadata
+
+ """List of public metadata items. Can be accessed without permissions."""
+ metadata: [MetadataItem!]!
+
+ """
+ A single key from public metadata.
+
+ Tip: Use GraphQL aliases to fetch multiple keys.
+
+ Added in Saleor 3.3.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ metafield(key: String!): String
+
+ """
+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.
+
+ Added in Saleor 3.3.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ metafields(keys: [String!]): Metadata
+ createdAt: DateTime!
+ modifiedAt: DateTime!
+
+ """
+ List of actions that can be performed in the current state of a payment.
+ """
+ actions: [TransactionActionEnum!]!
+
+ """Total amount authorized for this payment."""
+ authorizedAmount: Money!
+
+ """Total amount refunded for this payment."""
+ refundedAmount: Money!
+
+ """Total amount voided for this payment."""
+ voidedAmount: Money!
+
+ """Total amount captured for this payment."""
+ capturedAmount: Money!
+
+ """Status of transaction."""
+ status: String!
+
+ """Type of transaction."""
+ type: String!
+
+ """Reference of transaction."""
+ reference: String!
+
+ """List of all transaction's events."""
+ events: [TransactionEvent!]!
+}
+
+"""
+Represents possible actions on payment transaction.
+
+ The following actions are possible:
+ CAPTURE - Represents the capture action.
+ REFUND - Represents a refund action.
+ VOID - Represents a void action.
+"""
+enum TransactionActionEnum {
+ CAPTURE
+ REFUND
+ VOID
+}
+
+"""Represents transaction's event."""
+type TransactionEvent implements Node {
+ """The ID of the object."""
+ id: ID!
+ createdAt: DateTime!
+
+ """Status of transaction's event."""
+ status: TransactionStatus!
+
+ """Reference of transaction's event."""
+ reference: String!
+
+ """Name of the transaction's event."""
+ name: String
+}
+
+"""An enumeration."""
+enum TransactionStatus {
+ PENDING
+ SUCCESS
+ FAILURE
+}
+
type GiftCardCountableConnection {
"""Pagination data for this connection."""
pageInfo: PageInfo!
@@ -7545,6 +7683,15 @@ type Order implements Node & ObjectWithMetadata {
"""User-friendly payment status."""
paymentStatusDisplay: String!
+ """
+ List of transactions for the order. Requires one of the following permissions: MANAGE_ORDERS, HANDLE_PAYMENTS.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ transactions: [TransactionItem!]!
+
"""List of payments for the order."""
payments: [Payment!]!
@@ -8120,7 +8267,7 @@ type OrderEvent implements Node {
"""Amount of money."""
amount: Float
- """The payment ID from the payment gateway."""
+ """The payment reference from the payment provider."""
paymentId: String
"""The payment gateway of the payment."""
@@ -8161,6 +8308,12 @@ type OrderEvent implements Node {
"""The discount applied to the order."""
discount: OrderEventDiscountObject
+
+ """The status of payment's transaction."""
+ status: TransactionStatus
+
+ """The reference of payment's transaction."""
+ reference: String
}
"""An enumeration."""
@@ -8193,6 +8346,10 @@ enum OrderEventsEnum {
PAYMENT_REFUNDED
PAYMENT_VOIDED
PAYMENT_FAILED
+ TRANSACTION_EVENT
+ TRANSACTION_CAPTURE_REQUESTED
+ TRANSACTION_REFUND_REQUESTED
+ TRANSACTION_VOID_REQUESTED
INVOICE_REQUESTED
INVOICE_GENERATED
INVOICE_UPDATED
@@ -8347,6 +8504,7 @@ enum OrderErrorCode {
DUPLICATED_INPUT_ITEM
NOT_AVAILABLE_IN_CHANNEL
CHANNEL_INACTIVE
+ MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK
}
"""An enumeration."""
@@ -10734,6 +10892,64 @@ type Mutation {
input: PaymentCheckBalanceInput!
): PaymentCheckBalance
+ """
+ Create transaction for checkout or order. Requires the following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ transactionCreate(
+ """The ID of the checkout or order."""
+ id: ID!
+
+ """Input data required to create a new transaction object."""
+ transaction: TransactionCreateInput!
+
+ """Data that defines a transaction event."""
+ transactionEvent: TransactionEventInput
+ ): TransactionCreate
+
+ """
+ Create transaction for checkout or order. Requires the following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ transactionUpdate(
+ """The ID of the transaction."""
+ id: ID!
+
+ """Input data required to create a new transaction object."""
+ transaction: TransactionUpdateInput
+
+ """Data that defines a transaction transaction."""
+ transactionEvent: TransactionEventInput
+ ): TransactionUpdate
+
+ """
+ Request an action for payment transaction.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: HANDLE_PAYMENTS, MANAGE_ORDERS.
+ """
+ transactionRequestAction(
+ """Determines the action type."""
+ actionType: TransactionActionEnum!
+
+ """
+ Transaction request amount. If empty for refund or capture, maximal possible amount will be used.
+ """
+ amount: PositiveDecimal
+
+ """The ID of the transaction."""
+ id: ID!
+ ): TransactionRequestAction
+
"""
Creates a new page.
@@ -12193,13 +12409,11 @@ type Mutation {
): CheckoutLanguageCodeUpdate
"""
- Create new order from existing checkout.
+ Create new order from existing checkout. Requires the following permissions: AUTHENTICATED_APP and HANDLE_CHECKOUTS.
Added in Saleor 3.2.
- Note: this API is currently in Feature Preview and can be subject to changes at later point.
-
- Requires one of the following permissions: HANDLE_CHECKOUTS.
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
orderCreateFromCheckout(
"""ID of a checkout that will be converted to an order."""
@@ -15451,6 +15665,192 @@ input MoneyInput {
amount: PositiveDecimal!
}
+"""
+Create transaction for checkout or order. Requires the following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS.
+
+Added in Saleor 3.4.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionCreate {
+ transaction: TransactionItem
+ errors: [TransactionCreateError!]!
+}
+
+type TransactionCreateError {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: TransactionCreateErrorCode!
+}
+
+"""An enumeration."""
+enum TransactionCreateErrorCode {
+ INVALID
+ GRAPHQL_ERROR
+ NOT_FOUND
+ INCORRECT_CURRENCY
+ METADATA_KEY_REQUIRED
+}
+
+input TransactionCreateInput {
+ """Status of the transaction."""
+ status: String!
+
+ """Payment type used for this transaction."""
+ type: String!
+
+ """Reference of the transaction."""
+ reference: String
+
+ """List of all possible actions for the transaction"""
+ availableActions: [TransactionActionEnum!]
+
+ """Amount authorized by this transaction."""
+ amountAuthorized: MoneyInput
+
+ """Amount captured by this transaction."""
+ amountCaptured: MoneyInput
+
+ """Amount refunded by this transaction."""
+ amountRefunded: MoneyInput
+
+ """Amount voided by this transaction."""
+ amountVoided: MoneyInput
+
+ """Payment public metadata."""
+ metadata: [MetadataInput!]
+
+ """Payment private metadata."""
+ privateMetadata: [MetadataInput!]
+}
+
+input MetadataInput {
+ """Key of a metadata item."""
+ key: String!
+
+ """Value of a metadata item."""
+ value: String!
+}
+
+input TransactionEventInput {
+ """Current status of the payment transaction."""
+ status: TransactionStatus!
+
+ """Reference of the transaction."""
+ reference: String
+
+ """Name of the transaction."""
+ name: String
+}
+
+"""
+Create transaction for checkout or order. Requires the following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS.
+
+Added in Saleor 3.4.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionUpdate {
+ transaction: TransactionItem
+ errors: [TransactionUpdateError!]!
+}
+
+type TransactionUpdateError {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: TransactionUpdateErrorCode!
+}
+
+"""An enumeration."""
+enum TransactionUpdateErrorCode {
+ INVALID
+ GRAPHQL_ERROR
+ NOT_FOUND
+ INCORRECT_CURRENCY
+ METADATA_KEY_REQUIRED
+}
+
+input TransactionUpdateInput {
+ """Status of the transaction."""
+ status: String
+
+ """Payment type used for this transaction."""
+ type: String
+
+ """Reference of the transaction."""
+ reference: String
+
+ """List of all possible actions for the transaction"""
+ availableActions: [TransactionActionEnum!]
+
+ """Amount authorized by this transaction."""
+ amountAuthorized: MoneyInput
+
+ """Amount captured by this transaction."""
+ amountCaptured: MoneyInput
+
+ """Amount refunded by this transaction."""
+ amountRefunded: MoneyInput
+
+ """Amount voided by this transaction."""
+ amountVoided: MoneyInput
+
+ """Payment public metadata."""
+ metadata: [MetadataInput!]
+
+ """Payment private metadata."""
+ privateMetadata: [MetadataInput!]
+}
+
+"""
+Request an action for payment transaction.
+
+Added in Saleor 3.4.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+Requires one of the following permissions: HANDLE_PAYMENTS, MANAGE_ORDERS.
+"""
+type TransactionRequestAction {
+ transaction: TransactionItem
+ errors: [TransactionRequestActionError!]!
+}
+
+type TransactionRequestActionError {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: TransactionRequestActionErrorCode!
+}
+
+"""An enumeration."""
+enum TransactionRequestActionErrorCode {
+ INVALID
+ GRAPHQL_ERROR
+ NOT_FOUND
+ MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK
+}
+
"""
Creates a new page.
@@ -16424,14 +16824,6 @@ type UpdateMetadata {
item: ObjectWithMetadata
}
-input MetadataInput {
- """Key of a metadata item."""
- key: String!
-
- """Value of a metadata item."""
- value: String!
-}
-
"""
Updates private metadata of an object. To use it, you need to be an authenticated staff user or an app and have access to the modified object.
"""
@@ -18067,13 +18459,11 @@ type CheckoutLanguageCodeUpdate {
}
"""
-Create new order from existing checkout.
+Create new order from existing checkout. Requires the following permissions: AUTHENTICATED_APP and HANDLE_CHECKOUTS.
Added in Saleor 3.2.
-Note: this API is currently in Feature Preview and can be subject to changes at later point.
-
-Requires one of the following permissions: HANDLE_CHECKOUTS.
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
type OrderCreateFromCheckout {
"""Placed order."""
@@ -19556,7 +19946,7 @@ type Subscription {
event: Event
}
-union Event = CategoryCreated | CategoryUpdated | CategoryDeleted | ChannelCreated | ChannelUpdated | ChannelDeleted | ChannelStatusChanged | GiftCardCreated | GiftCardUpdated | GiftCardDeleted | GiftCardStatusChanged | OrderCreated | OrderUpdated | OrderConfirmed | OrderFullyPaid | OrderCancelled | OrderFulfilled | DraftOrderCreated | DraftOrderUpdated | DraftOrderDeleted | ProductCreated | ProductUpdated | ProductDeleted | ProductVariantCreated | ProductVariantUpdated | ProductVariantOutOfStock | ProductVariantBackInStock | ProductVariantDeleted | SaleCreated | SaleUpdated | SaleDeleted | InvoiceRequested | InvoiceDeleted | InvoiceSent | FulfillmentCreated | FulfillmentCanceled | CustomerCreated | CustomerUpdated | CollectionCreated | CollectionUpdated | CollectionDeleted | CheckoutCreated | CheckoutUpdated | PageCreated | PageUpdated | PageDeleted | ShippingPriceCreated | ShippingPriceUpdated | ShippingPriceDeleted | ShippingZoneCreated | ShippingZoneUpdated | ShippingZoneDeleted | TranslationCreated | TranslationUpdated
+union Event = CategoryCreated | CategoryUpdated | CategoryDeleted | ChannelCreated | ChannelUpdated | ChannelDeleted | ChannelStatusChanged | GiftCardCreated | GiftCardUpdated | GiftCardDeleted | GiftCardStatusChanged | OrderCreated | OrderUpdated | OrderConfirmed | OrderFullyPaid | OrderCancelled | OrderFulfilled | DraftOrderCreated | DraftOrderUpdated | DraftOrderDeleted | ProductCreated | ProductUpdated | ProductDeleted | ProductVariantCreated | ProductVariantUpdated | ProductVariantOutOfStock | ProductVariantBackInStock | ProductVariantDeleted | SaleCreated | SaleUpdated | SaleDeleted | InvoiceRequested | InvoiceDeleted | InvoiceSent | FulfillmentCreated | FulfillmentCanceled | CustomerCreated | CustomerUpdated | CollectionCreated | CollectionUpdated | CollectionDeleted | CheckoutCreated | CheckoutUpdated | PageCreated | PageUpdated | PageDeleted | ShippingPriceCreated | ShippingPriceUpdated | ShippingPriceDeleted | ShippingZoneCreated | ShippingZoneUpdated | ShippingZoneDeleted | TransactionActionRequest | TranslationCreated | TranslationUpdated
type CategoryCreated {
"""
@@ -20271,6 +20661,34 @@ type ShippingZoneDeleted {
): ShippingZone
}
+type TransactionActionRequest {
+ """
+ Look up a transaction.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ transaction: TransactionItem
+
+ """
+ Requested action data.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ action: TransactionAction!
+}
+
+type TransactionAction {
+ """Determines the action type."""
+ actionType: TransactionActionEnum!
+
+ """Transaction request amount. Null when action type is VOID."""
+ amount: PositiveDecimal
+}
+
type TranslationCreated {
"""
Look up a translation.
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 2a42dc4265..f6061771c2 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -3,9 +3,11 @@ from graphene import AbstractType, ObjectType, Union
from rx import Observable
from ...attribute.models import AttributeTranslation, AttributeValueTranslation
+from ...core.prices import quantize_price
from ...discount.models import SaleTranslation, VoucherTranslation
from ...menu.models import MenuItemTranslation
from ...page.models import PageTranslation
+from ...payment.interface import TransactionActionData
from ...product.models import (
CategoryTranslation,
CollectionTranslation,
@@ -15,7 +17,10 @@ from ...product.models import (
from ...shipping.models import ShippingMethodTranslation
from ...webhook.event_types import WebhookEventAsyncType
from ..channel import ChannelContext
-from ..core.descriptions import ADDED_IN_32, PREVIEW_FEATURE
+from ..core.descriptions import ADDED_IN_32, ADDED_IN_34, PREVIEW_FEATURE
+from ..core.scalars import PositiveDecimal
+from ..payment.enums import TransactionActionEnum
+from ..payment.types import TransactionItem
from ..translations import types as translation_types
TRANSLATIONS_TYPES_MAP = {
@@ -488,6 +493,47 @@ class ShippingZoneDeleted(ObjectType, ShippingZoneBase):
...
+class TransactionAction(ObjectType):
+ action_type = graphene.Field(
+ TransactionActionEnum,
+ required=True,
+ description="Determines the action type.",
+ )
+ amount = PositiveDecimal(
+ description="Transaction request amount. Null when action type is VOID.",
+ )
+
+ @staticmethod
+ def resolve_amount(root: TransactionActionData, _info):
+ if root.action_value:
+ return quantize_price(root.action_value, root.transaction.currency)
+ return None
+
+
+class TransactionActionRequest(ObjectType):
+ transaction = graphene.Field(
+ TransactionItem,
+ description="Look up a transaction." + ADDED_IN_34 + PREVIEW_FEATURE,
+ )
+ action = graphene.Field(
+ TransactionAction,
+ required=True,
+ description="Requested action data." + ADDED_IN_34 + PREVIEW_FEATURE,
+ )
+
+ @staticmethod
+ def resolve_transaction(root, _info):
+ _, transaction_action_data = root
+ transaction_action_data: TransactionActionData
+ return transaction_action_data.transaction
+
+ @staticmethod
+ def resolve_action(root, _info):
+ _, transaction_action_data = root
+ transaction_action_data: TransactionActionData
+ return transaction_action_data
+
+
class TranslationTypes(Union):
class Meta:
types = tuple(TRANSLATIONS_TYPES_MAP.values())
@@ -576,6 +622,7 @@ class Event(Union):
ShippingZoneCreated,
ShippingZoneUpdated,
ShippingZoneDeleted,
+ TransactionActionRequest,
TranslationCreated,
TranslationUpdated,
)
@@ -639,6 +686,7 @@ class Event(Union):
WebhookEventAsyncType.SHIPPING_ZONE_CREATED: ShippingZoneCreated,
WebhookEventAsyncType.SHIPPING_ZONE_UPDATED: ShippingZoneUpdated,
WebhookEventAsyncType.SHIPPING_ZONE_DELETED: ShippingZoneDeleted,
+ WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST: TransactionActionRequest,
WebhookEventAsyncType.TRANSLATION_CREATED: TranslationCreated,
WebhookEventAsyncType.TRANSLATION_UPDATED: TranslationUpdated,
}
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 84f627a229..28530c37c5 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -109,6 +109,12 @@ class OrderEvents:
PAYMENT_REFUNDED = "payment_refunded"
PAYMENT_VOIDED = "payment_voided"
PAYMENT_FAILED = "payment_failed"
+
+ TRANSACTION_EVENT = "transaction_event"
+ TRANSACTION_CAPTURE_REQUESTED = "transaction_capture_requested"
+ TRANSACTION_REFUND_REQUESTED = "transaction_refund_requested"
+ TRANSACTION_VOID_REQUESTED = "transaction_void_requested"
+
EXTERNAL_SERVICE_NOTIFICATION = "external_service_notification"
INVOICE_REQUESTED = "invoice_requested"
@@ -161,6 +167,10 @@ class OrderEvents:
(PAYMENT_REFUNDED, "The payment was refunded"),
(PAYMENT_VOIDED, "The payment was voided"),
(PAYMENT_FAILED, "The payment was failed"),
+ (TRANSACTION_EVENT, "The transaction event"),
+ (TRANSACTION_CAPTURE_REQUESTED, "The capture on transaction requested"),
+ (TRANSACTION_REFUND_REQUESTED, "The refund on transaction requested"),
+ (TRANSACTION_VOID_REQUESTED, "The void on transaction requested"),
(INVOICE_REQUESTED, "An invoice was requested"),
(INVOICE_GENERATED, "An invoice was generated"),
(INVOICE_UPDATED, "An invoice was updated"),
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index ab28fb9ba2..8374244556 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -5,7 +5,6 @@ from decimal import Decimal
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple
from django.contrib.sites.models import Site
-from django.core.exceptions import ValidationError
from django.db import transaction
from ..account.models import User
@@ -21,8 +20,9 @@ from ..payment import (
TransactionKind,
gateway,
)
+from ..payment.gateway import request_refund_action
from ..payment.interface import RefundData
-from ..payment.models import Payment, Transaction
+from ..payment.models import Payment, Transaction, TransactionItem
from ..payment.utils import create_payment
from ..warehouse.management import (
deallocate_stock,
@@ -39,7 +39,6 @@ from . import (
events,
utils,
)
-from .error_codes import OrderErrorCode
from .events import (
draft_order_created_from_replace_event,
fulfillment_refunded_event,
@@ -975,6 +974,7 @@ def create_refund_fulfillment(
app: Optional["App"],
order,
payment,
+ transactions: List[TransactionItem],
order_lines_to_refund: List[OrderLineInfo],
fulfillment_lines_to_refund: List[FulfillmentLineData],
manager: "PluginsManager",
@@ -999,6 +999,7 @@ def create_refund_fulfillment(
app=app,
order=order,
payment=payment,
+ transactions=transactions,
order_lines_to_refund=order_lines_to_refund,
fulfillment_lines_to_refund=fulfillment_lines_to_refund,
amount=amount,
@@ -1316,6 +1317,7 @@ def create_fulfillments_for_returned_products(
app: Optional["App"],
order: "Order",
payment: Optional[Payment],
+ transactions: Optional[List[TransactionItem]],
order_lines: List[OrderLineInfo],
fulfillment_lines: List[FulfillmentLineData],
manager: "PluginsManager",
@@ -1352,12 +1354,13 @@ def create_fulfillments_for_returned_products(
)
total_refund_amount = None
with traced_atomic_transaction():
- if refund and payment:
+ if refund and (payment or transactions):
total_refund_amount = _process_refund(
user=user,
app=app,
order=order,
payment=payment,
+ transactions=transactions,
order_lines_to_refund=return_order_lines,
fulfillment_lines_to_refund=return_fulfillment_lines,
amount=amount,
@@ -1439,7 +1442,8 @@ def _process_refund(
user: Optional["User"],
app: Optional["App"],
order: "Order",
- payment: Payment,
+ payment: Optional[Payment],
+ transactions: Optional[List[TransactionItem]],
order_lines_to_refund: List[OrderLineInfo],
fulfillment_lines_to_refund: List[FulfillmentLineData],
amount: Optional[Decimal],
@@ -1462,8 +1466,22 @@ def _process_refund(
if refund_shipping_costs:
amount += order.shipping_price_gross_amount
if amount:
- amount = min(payment.captured_amount, amount)
- try:
+ if transactions:
+ # With current mutation's inputs, we are able to process only single
+ # transaction. This can be changed when we will provide an interface
+ # to provide list of transactions.
+ transaction_item = transactions[-1]
+ amount = min(transaction_item.captured_value, amount)
+ request_refund_action(
+ transaction_item,
+ manager,
+ refund_value=amount,
+ channel_slug=order.channel.slug,
+ user=user,
+ app=app,
+ )
+ elif payment:
+ amount = min(payment.captured_amount, amount)
gateway.refund(
payment,
manager,
@@ -1471,25 +1489,21 @@ def _process_refund(
channel_slug=order.channel.slug,
refund_data=refund_data,
)
- except PaymentError:
- raise ValidationError(
- "The refund operation is not available yet.",
- code=OrderErrorCode.CANNOT_REFUND.value,
- )
- transaction.on_commit(
- lambda: events.payment_refunded_event(
- order=order,
- user=user,
- app=app,
- amount=amount, # type: ignore
- payment=payment,
+
+ transaction.on_commit(
+ lambda: events.payment_refunded_event(
+ order=order,
+ user=user,
+ app=app,
+ amount=amount, # type: ignore
+ payment=payment, # type: ignore
+ )
)
- )
- transaction.on_commit(
- lambda: send_order_refunded_confirmation(
- order, user, app, amount, payment.currency, manager # type: ignore
+ transaction.on_commit(
+ lambda: send_order_refunded_confirmation(
+ order, user, app, amount, payment.currency, manager # type: ignore
+ )
)
- )
transaction.on_commit(
lambda: fulfillment_refunded_event(
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 14c6615630..c9e30d57e0 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -33,3 +33,6 @@ class OrderErrorCode(Enum):
DUPLICATED_INPUT_ITEM = "duplicated_input_item"
NOT_AVAILABLE_IN_CHANNEL = "not_available_in_channel"
CHANNEL_INACTIVE = "channel_inactive"
+ MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK = (
+ "missing_transaction_action_request_webhook"
+ )
diff --git a/saleor/order/events.py b/saleor/order/events.py
index cd4d024775..eb59ca0c6f 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -40,6 +40,56 @@ def _get_payment_data(amount: Optional[Decimal], payment: Payment) -> Dict:
}
+def event_transaction_capture_requested(
+ order_id: "UUID", reference: str, amount: Decimal, user: UserType, app: AppType
+):
+ if not user_is_valid(user):
+ user = None
+ return OrderEvent.objects.create(
+ order_id=order_id,
+ type=OrderEvents.TRANSACTION_CAPTURE_REQUESTED,
+ user=user,
+ app=app,
+ parameters={
+ "amount": amount,
+ "reference": reference,
+ },
+ )
+
+
+def event_transaction_refund_requested(
+ order_id: "UUID", reference: str, amount: Decimal, user: UserType, app: AppType
+):
+ if not user_is_valid(user):
+ user = None
+ return OrderEvent.objects.create(
+ order_id=order_id,
+ type=OrderEvents.TRANSACTION_REFUND_REQUESTED,
+ user=user,
+ app=app,
+ parameters={
+ "amount": amount,
+ "reference": reference,
+ },
+ )
+
+
+def event_transaction_void_requested(
+ order_id: "UUID", reference: str, user: UserType, app: AppType
+):
+ if not user_is_valid(user):
+ user = None
+ return OrderEvent.objects.create(
+ order_id=order_id,
+ type=OrderEvents.TRANSACTION_VOID_REQUESTED,
+ user=user,
+ app=app,
+ parameters={
+ "reference": reference,
+ },
+ )
+
+
def event_order_refunded_notification(
order_id: "UUID", user_id: Optional[int], app_id: Optional[int], customer_email: str
):
@@ -432,6 +482,29 @@ def payment_failed_event(
)
+def transaction_event(
+ *,
+ order: Order,
+ user: UserType,
+ app: AppType,
+ reference: str,
+ status: str,
+ name: str
+) -> OrderEvent:
+
+ if not user_is_valid(user):
+ user = None
+
+ parameters = {"message": name, "reference": reference, "status": status}
+ return OrderEvent.objects.create(
+ order=order,
+ type=OrderEvents.TRANSACTION_EVENT,
+ user=user,
+ app=app,
+ parameters=parameters,
+ )
+
+
def external_notification_event(
*,
order: Order,
diff --git a/saleor/order/migrations/0137_alter_orderevent_type.py b/saleor/order/migrations/0137_alter_orderevent_type.py
new file mode 100644
index 0000000000..2400550e75
--- /dev/null
+++ b/saleor/order/migrations/0137_alter_orderevent_type.py
@@ -0,0 +1,71 @@
+# Generated by Django 3.2.12 on 2022-04-21 06:15
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0136_auto_20220414_1025"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="orderevent",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("DRAFT_CREATED", "draft_created"),
+ ("DRAFT_CREATED_FROM_REPLACE", "draft_created_from_replace"),
+ ("ADDED_PRODUCTS", "added_products"),
+ ("REMOVED_PRODUCTS", "removed_products"),
+ ("PLACED", "placed"),
+ ("PLACED_FROM_DRAFT", "placed_from_draft"),
+ ("OVERSOLD_ITEMS", "oversold_items"),
+ ("CANCELED", "canceled"),
+ ("ORDER_MARKED_AS_PAID", "order_marked_as_paid"),
+ ("ORDER_FULLY_PAID", "order_fully_paid"),
+ ("ORDER_REPLACEMENT_CREATED", "order_replacement_created"),
+ ("ORDER_DISCOUNT_ADDED", "order_discount_added"),
+ (
+ "ORDER_DISCOUNT_AUTOMATICALLY_UPDATED",
+ "order_discount_automatically_updated",
+ ),
+ ("ORDER_DISCOUNT_UPDATED", "order_discount_updated"),
+ ("ORDER_DISCOUNT_DELETED", "order_discount_deleted"),
+ ("ORDER_LINE_DISCOUNT_UPDATED", "order_line_discount_updated"),
+ ("ORDER_LINE_DISCOUNT_REMOVED", "order_line_discount_removed"),
+ ("ORDER_LINE_PRODUCT_DELETED", "order_line_product_deleted"),
+ ("ORDER_LINE_VARIANT_DELETED", "order_line_variant_deleted"),
+ ("UPDATED_ADDRESS", "updated_address"),
+ ("EMAIL_SENT", "email_sent"),
+ ("CONFIRMED", "confirmed"),
+ ("PAYMENT_AUTHORIZED", "payment_authorized"),
+ ("PAYMENT_CAPTURED", "payment_captured"),
+ ("EXTERNAL_SERVICE_NOTIFICATION", "external_service_notification"),
+ ("PAYMENT_REFUNDED", "payment_refunded"),
+ ("PAYMENT_VOIDED", "payment_voided"),
+ ("PAYMENT_FAILED", "payment_failed"),
+ ("TRANSACTION_EVENT", "transaction_event"),
+ ("TRANSACTION_CAPTURE_REQUESTED", "transaction_capture_requested"),
+ ("TRANSACTION_REFUND_REQUESTED", "transaction_refund_requested"),
+ ("TRANSACTION_VOID_REQUESTED", "transaction_void_requested"),
+ ("INVOICE_REQUESTED", "invoice_requested"),
+ ("INVOICE_GENERATED", "invoice_generated"),
+ ("INVOICE_UPDATED", "invoice_updated"),
+ ("INVOICE_SENT", "invoice_sent"),
+ ("FULFILLMENT_CANCELED", "fulfillment_canceled"),
+ ("FULFILLMENT_RESTOCKED_ITEMS", "fulfillment_restocked_items"),
+ ("FULFILLMENT_FULFILLED_ITEMS", "fulfillment_fulfilled_items"),
+ ("FULFILLMENT_REFUNDED", "fulfillment_refunded"),
+ ("FULFILLMENT_RETURNED", "fulfillment_returned"),
+ ("FULFILLMENT_REPLACED", "fulfillment_replaced"),
+ ("FULFILLMENT_AWAITS_APPROVAL", "fulfillment_awaits_approval"),
+ ("TRACKING_UPDATED", "tracking_updated"),
+ ("NOTE_ADDED", "note_added"),
+ ("OTHER", "other"),
+ ],
+ max_length=255,
+ ),
+ ),
+ ]
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 dfb7ce58f2..5b407e38e3 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
@@ -40,6 +40,7 @@ def test_create_return_fulfillment_only_order_lines(
app=None,
order=order_with_lines,
payment=payment,
+ transactions=[],
order_lines=[
OrderLineInfo(line=line, quantity=2, replace=False)
for line in order_lines_to_return
@@ -118,6 +119,7 @@ def test_create_return_fulfillment_only_order_lines_with_refund(
app=None,
order=order_with_lines,
payment=payment,
+ transactions=[],
order_lines=order_lines_to_refund,
fulfillment_lines=[],
manager=get_plugins_manager(),
@@ -194,6 +196,7 @@ def test_create_return_fulfillment_only_order_lines_included_shipping_costs(
app=None,
order=order_with_lines,
payment=payment,
+ transactions=[],
order_lines=order_lines_to_refund,
fulfillment_lines=[],
manager=get_plugins_manager(),
@@ -286,6 +289,7 @@ def test_create_return_fulfillment_only_order_lines_with_replace_request(
app=None,
order=order_with_lines,
payment=payment,
+ transactions=[],
order_lines=order_lines_data,
fulfillment_lines=[],
manager=get_plugins_manager(),
@@ -396,6 +400,7 @@ def test_create_return_fulfillment_only_fulfillment_lines(
app=None,
order=fulfilled_order,
payment=payment,
+ transactions=[],
order_lines=[],
fulfillment_lines=[
FulfillmentLineData(line=line, quantity=2, replace=False)
@@ -454,6 +459,7 @@ def test_create_return_fulfillment_only_fulfillment_lines_replace_order(
app=None,
order=fulfilled_order,
payment=payment,
+ transactions=[],
order_lines=[],
fulfillment_lines=fulfillment_lines_to_return,
manager=get_plugins_manager(),
@@ -596,6 +602,7 @@ def test_create_return_fulfillment_with_lines_already_refunded(
app=None,
order=fulfilled_order,
payment=payment,
+ transactions=[],
order_lines=[],
fulfillment_lines=fulfillment_lines_to_process,
manager=get_plugins_manager(),
diff --git a/saleor/order/tests/test_order_actions_refund_products.py b/saleor/order/tests/test_order_actions_refund_products.py
index 29ceb947d6..63b0f87920 100644
--- a/saleor/order/tests/test_order_actions_refund_products.py
+++ b/saleor/order/tests/test_order_actions_refund_products.py
@@ -41,6 +41,7 @@ def test_create_refund_fulfillment_only_order_lines(
app=None,
order=order_with_lines,
payment=payment,
+ transactions=[],
order_lines_to_refund=order_refund_lines,
fulfillment_lines_to_refund=[],
manager=get_plugins_manager(),
@@ -107,6 +108,7 @@ def test_create_refund_fulfillment_included_shipping_costs(
app=None,
order=order_with_lines,
payment=payment,
+ transactions=[],
order_lines_to_refund=order_refund_lines,
fulfillment_lines_to_refund=[],
manager=get_plugins_manager(),
@@ -168,6 +170,7 @@ def test_create_refund_fulfillment_only_fulfillment_lines(
app=None,
order=fulfilled_order,
payment=payment,
+ transactions=[],
order_lines_to_refund=[],
fulfillment_lines_to_refund=fulfillment_refund_lines,
manager=get_plugins_manager(),
@@ -226,6 +229,7 @@ def test_create_refund_fulfillment_custom_amount(
app=None,
order=fulfilled_order,
payment=payment,
+ transactions=[],
order_lines_to_refund=[],
fulfillment_lines_to_refund=fulfillment_refund_lines,
manager=get_plugins_manager(),
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 9b54756874..d4c5121307 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -141,3 +141,31 @@ class StorePaymentMethod:
(OFF_SESSION, "Off session"),
(NONE, "None"),
]
+
+
+class TransactionAction:
+ """Represents possible actions on payment transaction.
+
+ The following actions are possible:
+ CAPTURE - Represents the capture action.
+ REFUND - Represents a refund action.
+ VOID - Represents a void action.
+ """
+
+ CAPTURE = "capture"
+ REFUND = "refund"
+ VOID = "void"
+
+ CHOICES = [
+ (CAPTURE, "Capture payment"),
+ (REFUND, "Refund payment"),
+ (VOID, "Void payment"),
+ ]
+
+
+class TransactionStatus:
+ PENDING = "pending"
+ SUCCESS = "success"
+ FAILURE = "failure"
+
+ CHOICES = [(PENDING, "Pending"), (SUCCESS, "Success"), (FAILURE, "Failure")]
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index bf2831d6fa..5697f14a5d 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -19,3 +19,28 @@ class PaymentErrorCode(Enum):
CHECKOUT_EMAIL_NOT_SET = "checkout_email_not_set"
UNAVAILABLE_VARIANT_IN_CHANNEL = "unavailable_variant_in_channel"
NO_CHECKOUT_LINES = "no_checkout_lines"
+
+
+class TransactionCreateErrorCode(Enum):
+ INVALID = "invalid"
+ GRAPHQL_ERROR = "graphql_error"
+ NOT_FOUND = "not_found"
+ INCORRECT_CURRENCY = "incorrect_currency"
+ METADATA_KEY_REQUIRED = "metadata_key_required"
+
+
+class TransactionUpdateErrorCode(Enum):
+ INVALID = "invalid"
+ GRAPHQL_ERROR = "graphql_error"
+ NOT_FOUND = "not_found"
+ INCORRECT_CURRENCY = "incorrect_currency"
+ METADATA_KEY_REQUIRED = "metadata_key_required"
+
+
+class TransactionRequestActionErrorCode(Enum):
+ INVALID = "invalid"
+ GRAPHQL_ERROR = "graphql_error"
+ NOT_FOUND = "not_found"
+ MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK = (
+ "missing_transaction_action_request_webhook"
+ )
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 42d1a94369..5d18941656 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -1,10 +1,26 @@
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple
+from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple, Union
+from django.contrib.auth.models import AnonymousUser
+
+from ..account.models import User
+from ..app.models import App
+from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
-from . import GatewayError, PaymentError, TransactionKind
-from .models import Payment, Transaction
+from ..order.events import (
+ event_transaction_capture_requested,
+ event_transaction_refund_requested,
+ event_transaction_void_requested,
+)
+from ..payment.interface import (
+ CustomerSource,
+ PaymentGateway,
+ RefundData,
+ TransactionActionData,
+)
+from . import GatewayError, PaymentError, TransactionAction, TransactionKind
+from .models import Payment, Transaction, TransactionItem
from .utils import (
clean_authorize,
clean_capture,
@@ -18,9 +34,10 @@ from .utils import (
if TYPE_CHECKING:
# flake8: noqa
- from ..payment.interface import CustomerSource, PaymentGateway, RefundData
from ..plugins.manager import PluginsManager
+UserType = Optional[User]
+AppType = Optional[App]
logger = logging.getLogger(__name__)
ERROR_MSG = "Oops! Something went wrong."
@@ -66,6 +83,103 @@ def with_locked_payment(fn: Callable) -> Callable:
return wrapped
+def request_capture_action(
+ transaction: TransactionItem,
+ manager: "PluginsManager",
+ capture_value: Optional[Decimal],
+ channel_slug: str,
+ user: UserType,
+ app: AppType,
+):
+
+ if capture_value is None:
+ capture_value = transaction.authorized_value
+
+ _request_payment_action(
+ transaction=transaction,
+ manager=manager,
+ action_type=TransactionAction.CAPTURE,
+ action_value=capture_value,
+ channel_slug=channel_slug,
+ )
+ if order_id := transaction.order_id:
+ event_transaction_capture_requested(
+ order_id=order_id,
+ reference=transaction.reference,
+ amount=quantize_price(capture_value, transaction.currency),
+ user=user,
+ app=app,
+ )
+
+
+def request_refund_action(
+ transaction: TransactionItem,
+ manager: "PluginsManager",
+ refund_value: Optional[Decimal],
+ channel_slug: str,
+ user: UserType,
+ app: AppType,
+):
+ if refund_value is None:
+ refund_value = transaction.captured_value
+
+ _request_payment_action(
+ transaction=transaction,
+ manager=manager,
+ action_type=TransactionAction.REFUND,
+ action_value=refund_value,
+ channel_slug=channel_slug,
+ )
+ if order_id := transaction.order_id:
+ event_transaction_refund_requested(
+ order_id=order_id,
+ reference=transaction.reference,
+ amount=quantize_price(refund_value, transaction.currency),
+ user=user,
+ app=app,
+ )
+
+
+def request_void_action(
+ transaction: TransactionItem,
+ manager: "PluginsManager",
+ channel_slug: str,
+ user: UserType,
+ app: AppType,
+):
+ _request_payment_action(
+ transaction=transaction,
+ manager=manager,
+ action_type=TransactionAction.VOID,
+ action_value=None,
+ channel_slug=channel_slug,
+ )
+ if order_id := transaction.order_id:
+ event_transaction_void_requested(
+ order_id=order_id, reference=transaction.reference, user=user, app=app
+ )
+
+
+def _request_payment_action(
+ transaction: TransactionItem,
+ manager: "PluginsManager",
+ action_type: str,
+ action_value: Optional[Decimal],
+ channel_slug: str,
+):
+ payment_data = TransactionActionData(
+ transaction=transaction, action_type=action_type, action_value=action_value
+ )
+ event_active = manager.is_event_active_for_any_plugin(
+ "transaction_action_request", channel_slug=channel_slug
+ )
+ if not event_active:
+ raise PaymentError(
+ "No app or plugin is configured to handle payment action requests."
+ )
+ manager.transaction_action_request(payment_data, channel_slug=channel_slug)
+
+
@raise_payment_error
@require_active_payment
@with_locked_payment
diff --git a/saleor/payment/gateways/np_atobarai/tests/conftest.py b/saleor/payment/gateways/np_atobarai/tests/conftest.py
index 53daf4ac16..d837a1f828 100644
--- a/saleor/payment/gateways/np_atobarai/tests/conftest.py
+++ b/saleor/payment/gateways/np_atobarai/tests/conftest.py
@@ -160,6 +160,7 @@ def create_refund(payment_dummy):
app=None,
order=order,
payment=payment_dummy,
+ transactions=[],
order_lines_to_refund=order_lines or [],
fulfillment_lines_to_refund=fulfillment_lines or [],
manager=get_plugins_manager(),
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 184e483085..69b4183997 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -6,11 +6,19 @@ from typing import Any, Callable, Dict, List, Optional, Union
from ..order import FulfillmentLineData
from ..order.fetch import OrderLineInfo
+from ..payment.models import TransactionItem
JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
+@dataclass
+class TransactionActionData:
+ action_type: str
+ transaction: TransactionItem
+ action_value: Optional[Decimal] = None
+
+
@dataclass
class PaymentMethodInfo:
"""Uniform way to represent payment method information."""
diff --git a/saleor/payment/migrations/0035_auto_20220421_0615.py b/saleor/payment/migrations/0035_auto_20220421_0615.py
new file mode 100644
index 0000000000..3ddfc50b19
--- /dev/null
+++ b/saleor/payment/migrations/0035_auto_20220421_0615.py
@@ -0,0 +1,176 @@
+# Generated by Django 3.2.12 on 2022-04-21 06:15
+
+from decimal import Decimal
+import django.contrib.postgres.fields
+import django.contrib.postgres.indexes
+from django.db import migrations, models
+import django.db.models.deletion
+import saleor.core.utils.json_serializer
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0137_alter_orderevent_type"),
+ ("checkout", "0042_rename_created_checkout_created_at"),
+ ("payment", "0034_auto_20220414_1051"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="TransactionItem",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "private_metadata",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ (
+ "metadata",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("modified_at", models.DateTimeField(auto_now=True)),
+ ("status", models.CharField(blank=True, default="", max_length=512)),
+ ("type", models.CharField(blank=True, default="", max_length=512)),
+ ("reference", models.CharField(blank=True, default="", max_length=512)),
+ (
+ "available_actions",
+ django.contrib.postgres.fields.ArrayField(
+ base_field=models.CharField(
+ choices=[
+ ("capture", "Capture payment"),
+ ("refund", "Refund payment"),
+ ("void", "Void payment"),
+ ],
+ max_length=128,
+ ),
+ default=list,
+ size=None,
+ ),
+ ),
+ ("currency", models.CharField(max_length=3)),
+ (
+ "captured_value",
+ models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ (
+ "authorized_value",
+ models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ (
+ "refunded_value",
+ models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ (
+ "voided_value",
+ models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ (
+ "checkout",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="payment_transactions",
+ to="checkout.checkout",
+ ),
+ ),
+ (
+ "order",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.PROTECT,
+ related_name="payment_transactions",
+ to="order.order",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("pk",),
+ },
+ ),
+ migrations.CreateModel(
+ name="TransactionEvent",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("success", "Success"),
+ ("failure", "Failure"),
+ ],
+ default="success",
+ max_length=128,
+ ),
+ ),
+ ("reference", models.CharField(blank=True, default="", max_length=512)),
+ ("name", models.CharField(blank=True, default="", max_length=512)),
+ (
+ "transaction",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="events",
+ to="payment.transactionitem",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("pk",),
+ },
+ ),
+ migrations.AddIndex(
+ model_name="transactionitem",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["private_metadata"], name="transactionitem_p_meta_idx"
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="transactionitem",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["metadata"], name="transactionitem_meta_idx"
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="transactionitem",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["order_id", "status"], name="payment_tra_order_i_e783c4_gin"
+ ),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 49f290cda4..22df6c9ac7 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -2,18 +2,111 @@ from decimal import Decimal
from operator import attrgetter
from django.conf import settings
+from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.core.serializers.json import DjangoJSONEncoder
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models import JSONField # type: ignore
+from django_prices.models import MoneyField
from prices import Money
from ..checkout.models import Checkout
from ..core.models import ModelWithMetadata
from ..core.permissions import PaymentPermissions
from ..core.taxes import zero_money
-from . import ChargeStatus, CustomPaymentChoices, StorePaymentMethod, TransactionKind
+from . import (
+ ChargeStatus,
+ CustomPaymentChoices,
+ StorePaymentMethod,
+ TransactionAction,
+ TransactionKind,
+ TransactionStatus,
+)
+
+
+class TransactionItem(ModelWithMetadata):
+ created_at = models.DateTimeField(auto_now_add=True)
+ modified_at = models.DateTimeField(auto_now=True)
+ status = models.CharField(max_length=512, blank=True, default="")
+ type = models.CharField(max_length=512, blank=True, default="")
+ reference = models.CharField(max_length=512, blank=True, default="")
+ available_actions = ArrayField(
+ models.CharField(max_length=128, choices=TransactionAction.CHOICES),
+ default=list,
+ )
+
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH)
+
+ amount_captured = MoneyField(
+ amount_field="captured_value", currency_field="currency"
+ )
+ captured_value = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal("0"),
+ )
+ amount_authorized = MoneyField(
+ amount_field="authorized_value", currency_field="currency"
+ )
+ authorized_value = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal("0"),
+ )
+ amount_refunded = MoneyField(
+ amount_field="refunded_value", currency_field="currency"
+ )
+ refunded_value = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal("0"),
+ )
+ amount_voided = MoneyField(amount_field="voided_value", currency_field="currency")
+ voided_value = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal("0"),
+ )
+
+ checkout = models.ForeignKey(
+ Checkout,
+ null=True,
+ related_name="payment_transactions",
+ on_delete=models.SET_NULL,
+ )
+ order = models.ForeignKey(
+ "order.Order",
+ related_name="payment_transactions",
+ null=True,
+ on_delete=models.PROTECT,
+ )
+
+ class Meta:
+ ordering = ("pk",)
+ indexes = [
+ *ModelWithMetadata.Meta.indexes,
+ # Orders filtering by status index
+ GinIndex(fields=["order_id", "status"]),
+ ]
+
+
+class TransactionEvent(models.Model):
+ created_at = models.DateTimeField(auto_now_add=True)
+ status = models.CharField(
+ max_length=128,
+ choices=TransactionStatus.CHOICES,
+ default=TransactionStatus.SUCCESS,
+ )
+ reference = models.CharField(max_length=512, blank=True, default="")
+ name = models.CharField(max_length=512, blank=True, default="")
+
+ transaction = models.ForeignKey(
+ TransactionItem, related_name="events", on_delete=models.CASCADE
+ )
+
+ class Meta:
+ ordering = ("pk",)
class Payment(ModelWithMetadata):
diff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.py
index 8d47a9849a..e4753f318a 100644
--- a/saleor/payment/tests/test_gateway.py
+++ b/saleor/payment/tests/test_gateway.py
@@ -1,9 +1,22 @@
from decimal import Decimal
from unittest.mock import Mock, patch
+import pytest
+from django.contrib.auth.models import AnonymousUser
+
+from ...order import OrderEvents
from ...plugins.manager import get_plugins_manager
-from .. import ChargeStatus, CustomPaymentChoices, TransactionKind, gateway
-from ..interface import GatewayResponse
+from .. import (
+ ChargeStatus,
+ CustomPaymentChoices,
+ PaymentError,
+ TransactionAction,
+ TransactionKind,
+ gateway,
+)
+from ..gateway import request_capture_action, request_refund_action, request_void_action
+from ..interface import GatewayResponse, TransactionActionData
+from ..models import TransactionItem
from ..utils import create_payment_information
RAW_RESPONSE = {"test": "abcdefgheijklmn"}
@@ -315,6 +328,479 @@ def test_list_gateways(fake_payment_interface):
assert lst == gateways
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_request_capture_action_missing_active_event(
+ mocked_is_active, order, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = False
+ action_value = Decimal("5.00")
+
+ # when & then
+ with pytest.raises(PaymentError):
+ request_capture_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ capture_value=action_value,
+ channel_slug=order.channel.slug,
+ user=staff_user,
+ app=None,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_request_capture_action_on_order(
+ mocked_transaction_action_request, mocked_is_active, order, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = True
+ action_value = Decimal("5.00")
+
+ # when
+ request_capture_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ capture_value=action_value,
+ channel_slug=order.channel.slug,
+ user=staff_user,
+ app=None,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CAPTURE,
+ action_value=action_value,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED
+ assert Decimal(event.parameters["amount"]) == action_value
+ assert event.parameters["reference"] == transaction.reference
+ assert event.user == staff_user
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_request_capture_action_by_app(
+ mocked_transaction_action_request, mocked_is_active, order, app
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = True
+ action_value = Decimal("5.00")
+
+ # when
+ request_capture_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ capture_value=action_value,
+ channel_slug=order.channel.slug,
+ user=AnonymousUser(), # type: ignore
+ app=app,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CAPTURE,
+ action_value=action_value,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED
+ assert Decimal(event.parameters["amount"]) == action_value
+ assert event.parameters["reference"] == transaction.reference
+ assert event.app == app
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_request_capture_action_on_checkout(
+ mocked_transaction_action_request, mocked_is_active, checkout, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ authorized_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = True
+ action_value = Decimal("5.00")
+
+ # when
+ request_capture_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ capture_value=action_value,
+ channel_slug=checkout.channel.slug,
+ user=staff_user,
+ app=None,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CAPTURE,
+ action_value=action_value,
+ ),
+ channel_slug=checkout.channel.slug,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_request_refund_action_missing_active_event(
+ mocked_is_active, order, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ captured_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = False
+ action_value = Decimal("5.00")
+
+ # when & then
+ with pytest.raises(PaymentError):
+ request_refund_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ refund_value=action_value,
+ channel_slug=order.channel.slug,
+ user=staff_user,
+ app=None,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_request_refund_action_on_order(
+ mocked_transaction_action_request, mocked_is_active, order, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ captured_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = True
+ action_value = Decimal("5.00")
+
+ # when
+ request_refund_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ refund_value=action_value,
+ channel_slug=order.channel.slug,
+ user=staff_user,
+ app=None,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=action_value,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_REFUND_REQUESTED
+ assert Decimal(event.parameters["amount"]) == action_value
+ assert event.parameters["reference"] == transaction.reference
+ assert event.user == staff_user
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_request_refund_action_by_app(
+ mocked_transaction_action_request, mocked_is_active, order, app
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ captured_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = True
+ action_value = Decimal("5.00")
+
+ # when
+ request_refund_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ refund_value=action_value,
+ channel_slug=order.channel.slug,
+ user=AnonymousUser(), # type: ignore
+ app=app,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=action_value,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_REFUND_REQUESTED
+ assert Decimal(event.parameters["amount"]) == action_value
+ assert event.parameters["reference"] == transaction.reference
+ assert event.app == app
+ assert not event.user
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_request_refund_action_on_checkout(
+ mocked_transaction_action_request, mocked_is_active, checkout, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ captured_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = True
+ action_value = Decimal("5.00")
+
+ # when
+ request_refund_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ refund_value=action_value,
+ channel_slug=checkout.channel.slug,
+ user=staff_user,
+ app=None,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=action_value,
+ ),
+ channel_slug=checkout.channel.slug,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+def test_request_void_action_missing_active_event(mocked_is_active, order, staff_user):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = False
+
+ # when & then
+ with pytest.raises(PaymentError):
+ request_void_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ channel_slug=order.channel.slug,
+ user=staff_user,
+ app=None,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_request_void_action_on_order(
+ mocked_transaction_action_request, mocked_is_active, order, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = True
+
+ # when
+ request_void_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ channel_slug=order.channel.slug,
+ user=staff_user,
+ app=None,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.VOID,
+ action_value=None,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_VOID_REQUESTED
+ assert event.parameters["reference"] == transaction.reference
+ assert event.user == staff_user
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_request_void_action_by_app(
+ mocked_transaction_action_request, mocked_is_active, order, app
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = True
+
+ # when
+ request_void_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ channel_slug=order.channel.slug,
+ user=AnonymousUser(), # type:ignore
+ app=app,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.VOID,
+ action_value=None,
+ ),
+ channel_slug=order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_VOID_REQUESTED
+ assert event.parameters["reference"] == transaction.reference
+ assert event.app == app
+ assert not event.user
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
+def test_request_void_action_on_checkout(
+ mocked_transaction_action_request, mocked_is_active, checkout, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ authorized_value=Decimal("10"),
+ )
+ mocked_is_active.return_value = True
+
+ # when
+ request_void_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ channel_slug=checkout.channel.slug,
+ user=staff_user,
+ app=None,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.VOID,
+ action_value=None,
+ ),
+ channel_slug=checkout.channel.slug,
+ )
+
+
@patch("saleor.payment.gateway.void")
@patch("saleor.payment.gateway.refund")
def test_payment_refund_or_void_no_payment(refund_mock, void_mock):
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index eba87c1577..f121ed23d3 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -21,6 +21,7 @@ from ..payment.interface import (
InitializedPaymentResponse,
PaymentData,
PaymentGateway,
+ TransactionActionData,
)
from .models import PluginConfiguration
@@ -554,6 +555,8 @@ class BasePlugin:
process_payment: Callable[["PaymentData", Any], Any]
+ transaction_action_request: Callable[["TransactionActionData", None], None]
+
# Trigger when product is created.
#
# Overwrite this method if you need to trigger specific logic after a product is
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 831c741456..30ba79791e 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -54,6 +54,7 @@ if TYPE_CHECKING:
PaymentData,
PaymentGateway,
TokenConfig,
+ TransactionActionData,
)
from ..product.models import (
Category,
@@ -788,6 +789,17 @@ class PluginsManager(PaymentInterface):
default_value = None
return self.__run_method_on_plugins("page_deleted", default_value, page)
+ def transaction_action_request(
+ self, payment_data: "TransactionActionData", channel_slug: str
+ ):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "transaction_action_request",
+ default_value,
+ payment_data,
+ channel_slug=channel_slug,
+ )
+
def category_created(self, category: "Category"):
default_value = None
return self.__run_method_on_plugins("category_created", default_value, category)
@@ -1331,6 +1343,16 @@ class PluginsManager(PaymentInterface):
data=data,
)
+ def is_event_active_for_any_plugin(
+ self, event: str, channel_slug: Optional[str] = None
+ ) -> bool:
+ """Check if any plugin supports defined event."""
+ plugins = (
+ self.plugins_per_channel[channel_slug] if channel_slug else self.all_plugins
+ )
+ only_active_plugins = [plugin for plugin in plugins if plugin.active]
+ return any([plugin.is_event_active(event) for plugin in only_active_plugins])
+
def get_plugins_manager(
requestor_getter: Optional[Callable[[], "Requestor"]] = None
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 08da567291..950fb70778 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -1096,3 +1096,30 @@ def test_calculate_checkout_total_zero_default_value(
# then
assert "calculate_checkout_total" not in mocked_run_method.call_args_list
assert taxed_total == zero_taxed_money(currency)
+
+
+def test_manager_is_event_active_for_any_plugin_with_inactive_plugin(channel_USD):
+ # given
+ plugins = ["saleor.plugins.tests.sample_plugins.PluginInactive"]
+
+ manager = PluginsManager(plugins=plugins)
+
+ # when & then
+ assert not manager.is_event_active_for_any_plugin(
+ "authenticate_user", channel_USD.slug
+ )
+
+
+def test_manager_is_event_active_for_any_plugin(channel_USD):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ manager = PluginsManager(plugins=plugins)
+
+ # when & then
+ assert manager.is_event_active_for_any_plugin(
+ "calculate_checkout_total", channel_USD.slug
+ )
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 0a4a996458..8552fa034c 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -30,6 +30,7 @@ from ...webhook.payloads import (
generate_product_variant_with_stock_payload,
generate_requestor,
generate_sale_payload,
+ generate_transaction_action_request_payload,
generate_translation_payload,
)
from ...webhook.utils import get_webhooks_for_event
@@ -58,7 +59,12 @@ if TYPE_CHECKING:
from ...invoice.models import Invoice
from ...order.models import Fulfillment, Order
from ...page.models import Page
- from ...payment.interface import GatewayResponse, PaymentData, PaymentGateway
+ from ...payment.interface import (
+ GatewayResponse,
+ PaymentData,
+ PaymentGateway,
+ TransactionActionData,
+ )
from ...product.models import Category, Collection, Product, ProductVariant
from ...shipping.interface import ShippingMethodData
from ...shipping.models import ShippingMethod, ShippingZone
@@ -750,6 +756,24 @@ class WebhookPlugin(BasePlugin):
delivery_update(delivery, status=EventDeliveryStatus.PENDING)
send_webhook_request_async.delay(delivery.pk)
+ def transaction_action_request(
+ self, transaction_data: "TransactionActionData", previous_value: None
+ ) -> None:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST
+ if webhooks := get_webhooks_for_event(event_type):
+ payload = generate_transaction_action_request_payload(
+ transaction_data, self.requestor
+ )
+ trigger_webhooks_async(
+ payload,
+ event_type,
+ webhooks,
+ subscribable_object=transaction_data,
+ requestor=self.requestor,
+ )
+
def __run_payment_webhook(
self,
event_type: str,
@@ -950,6 +974,11 @@ class WebhookPlugin(BasePlugin):
)
def is_event_active(self, event: str, channel=Optional[str]):
- map_event = {"invoice_request": WebhookEventAsyncType.INVOICE_REQUESTED}
+ map_event = {
+ "invoice_request": WebhookEventAsyncType.INVOICE_REQUESTED,
+ "transaction_action_request": (
+ WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST
+ ),
+ }
webhooks = get_webhooks_for_event(event_type=map_event[event])
return any(webhooks)
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_action_request_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_action_request_subscription.py
new file mode 100644
index 0000000000..90e36326ab
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_action_request_subscription.py
@@ -0,0 +1,238 @@
+import json
+from decimal import Decimal
+
+import graphene
+from freezegun import freeze_time
+
+from .....core.prices import quantize_price
+from .....payment import TransactionAction
+from .....payment.interface import TransactionActionData
+from .....payment.models import TransactionItem
+from .....webhook.event_types import WebhookEventAsyncType
+from .....webhook.models import Webhook
+from ...tasks import create_deliveries_for_subscriptions
+
+TRANSACTION_ACTION_REQUEST_SUBSCRIPTION_QUERY = """
+subscription{
+ event{
+ ... on TransactionActionRequest{
+ transaction{
+ id
+ createdAt
+ actions
+ authorizedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ voidedAmount{
+ currency
+ amount
+ }
+ capturedAmount{
+ currency
+ amount
+ }
+ events{
+ id
+ }
+ status
+ type
+ reference
+ }
+ action{
+ actionType
+ amount
+ }
+ }
+ }
+}
+"""
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_transaction_refund_action_request(
+ order, webhook_app, permission_manage_payments
+):
+ # given
+ captured_value = Decimal("10")
+ webhook_app.permissions.add(permission_manage_payments)
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ captured_value=captured_value,
+ )
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TRANSACTION_ACTION_REQUEST_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST
+ webhook.events.create(event_type=event_type)
+
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+ action_value = Decimal("5.00")
+ transaction_data = TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=action_value,
+ )
+ # when
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, transaction_data, [webhook]
+ )
+
+ # then
+ assert json.loads(deliveries[0].payload.payload) == {
+ "transaction": {
+ "id": transaction_id,
+ "createdAt": "2020-03-18T12:00:00+00:00",
+ "actions": ["REFUND"],
+ "authorizedAmount": {"currency": "USD", "amount": 0.0},
+ "refundedAmount": {"currency": "USD", "amount": 0.0},
+ "voidedAmount": {"currency": "USD", "amount": 0.0},
+ "capturedAmount": {
+ "currency": "USD",
+ "amount": quantize_price(captured_value, "USD"),
+ },
+ "events": [],
+ "status": "Captured",
+ "type": "Credit card",
+ "reference": "PSP ref",
+ },
+ "action": {
+ "actionType": "REFUND",
+ "amount": quantize_price(action_value, "USD"),
+ },
+ "meta": None,
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_transaction_capture_action_request(
+ order, webhook_app, permission_manage_payments
+):
+ # given
+ authorized_value = Decimal("10")
+ webhook_app.permissions.add(permission_manage_payments)
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=authorized_value,
+ )
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TRANSACTION_ACTION_REQUEST_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST
+ webhook.events.create(event_type=event_type)
+
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+ action_value = Decimal("5.00")
+ transaction_data = TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CAPTURE,
+ action_value=action_value,
+ )
+ # when
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, transaction_data, [webhook]
+ )
+
+ # then
+ assert json.loads(deliveries[0].payload.payload) == {
+ "transaction": {
+ "id": transaction_id,
+ "createdAt": "2020-03-18T12:00:00+00:00",
+ "actions": ["CAPTURE"],
+ "authorizedAmount": {
+ "currency": "USD",
+ "amount": quantize_price(authorized_value, "USD"),
+ },
+ "refundedAmount": {"currency": "USD", "amount": 0.0},
+ "voidedAmount": {"currency": "USD", "amount": 0.0},
+ "capturedAmount": {"currency": "USD", "amount": 0.0},
+ "events": [],
+ "status": "Authorized",
+ "type": "Credit card",
+ "reference": "PSP ref",
+ },
+ "action": {
+ "actionType": "CAPTURE",
+ "amount": quantize_price(action_value, "USD"),
+ },
+ "meta": None,
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_transaction_void_action_request(
+ order, webhook_app, permission_manage_payments
+):
+ # given
+ authorized_value = Decimal("10")
+ webhook_app.permissions.add(permission_manage_payments)
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=authorized_value,
+ )
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TRANSACTION_ACTION_REQUEST_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST
+ webhook.events.create(event_type=event_type)
+
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.VOID,
+ )
+ # when
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, transaction_data, [webhook]
+ )
+
+ # then
+ assert json.loads(deliveries[0].payload.payload) == {
+ "transaction": {
+ "id": transaction_id,
+ "createdAt": "2020-03-18T12:00:00+00:00",
+ "actions": ["VOID"],
+ "authorizedAmount": {
+ "currency": "USD",
+ "amount": quantize_price(authorized_value, "USD"),
+ },
+ "refundedAmount": {"currency": "USD", "amount": 0.0},
+ "voidedAmount": {"currency": "USD", "amount": 0.0},
+ "capturedAmount": {"currency": "USD", "amount": 0.0},
+ "events": [],
+ "status": "Captured",
+ "type": "Credit card",
+ "reference": "PSP ref",
+ },
+ "action": {"actionType": "VOID", "amount": None},
+ "meta": None,
+ }
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 072461b921..42b6e0c2ff 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -29,6 +29,9 @@ from ....core.notify_events import NotifyEventType
from ....core.utils.url import prepare_url
from ....discount.utils import fetch_catalogue_info
from ....graphql.discount.mutations import convert_catalogue_info_to_global_ids
+from ....payment import TransactionAction
+from ....payment.interface import TransactionActionData
+from ....payment.models import TransactionItem
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.payloads import (
generate_checkout_payload,
@@ -42,6 +45,7 @@ from ....webhook.payloads import (
generate_product_variant_payload,
generate_product_variant_with_stock_payload,
generate_sale_payload,
+ generate_transaction_action_request_payload,
)
from ....webhook.utils import get_webhooks_for_event
from ...manager import get_plugins_manager
@@ -1057,6 +1061,55 @@ def test_send_webhook_request_async(
assert delivery.status == EventDeliveryStatus.SUCCESS
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_transaction_action_request(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ order,
+ channel_USD,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ action_value = Decimal("5.00")
+ transaction_action_data = TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CAPTURE,
+ action_value=action_value,
+ )
+
+ # when
+ manager.transaction_action_request(
+ transaction_action_data, channel_slug=channel_USD.slug
+ )
+
+ # then
+ expected_data = generate_transaction_action_request_payload(
+ transaction_action_data,
+ )
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data,
+ WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST,
+ [any_webhook],
+ subscribable_object=transaction_action_data,
+ requestor=ANY,
+ )
+
+
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
def test_send_webhook_request_async_when_delivery_attempt_failed(
mocked_send_response,
@@ -1092,3 +1145,24 @@ def test_send_webhook_request_async_when_max_retries_exceeded(
delivery = EventDelivery.objects.get(id=event_delivery.pk)
assert attempt.status == EventDeliveryStatus.FAILED
assert delivery.status == EventDeliveryStatus.FAILED
+
+
+ "event, expected_is_active",
+ (("invoice_request", False), ("transaction_action_request", True)),
+)
+def test_is_event_active(
+ event, expected_is_active, settings, webhook, permission_manage_payments
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ webhook.app.permissions.add(permission_manage_payments)
+ webhook.events.create(event_type=WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST)
+
+ manager = get_plugins_manager()
+
+ # when
+ is_active = manager.is_event_active_for_any_plugin(event)
+
+ # then
+ assert is_active == expected_is_active
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 0fa86614ea..e6fbe20e67 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -87,6 +87,8 @@ class WebhookEventAsyncType:
SHIPPING_ZONE_UPDATED = "shipping_zone_updated"
SHIPPING_ZONE_DELETED = "shipping_zone_deleted"
+ TRANSACTION_ACTION_REQUEST = "transaction_action_request"
+
TRANSLATION_CREATED = "translation_created"
TRANSLATION_UPDATED = "translation_updated"
@@ -145,6 +147,7 @@ class WebhookEventAsyncType:
SHIPPING_ZONE_CREATED: "Shipping zone created",
SHIPPING_ZONE_UPDATED: "Shipping zone updated",
SHIPPING_ZONE_DELETED: "Shipping zone deleted",
+ TRANSACTION_ACTION_REQUEST: "Payment action request",
TRANSLATION_CREATED: "Create translation",
TRANSLATION_UPDATED: "Update translation",
}
@@ -204,6 +207,7 @@ class WebhookEventAsyncType:
(SHIPPING_ZONE_CREATED, DISPLAY_LABELS[SHIPPING_ZONE_CREATED]),
(SHIPPING_ZONE_UPDATED, DISPLAY_LABELS[SHIPPING_ZONE_UPDATED]),
(SHIPPING_ZONE_DELETED, DISPLAY_LABELS[SHIPPING_ZONE_DELETED]),
+ (TRANSACTION_ACTION_REQUEST, DISPLAY_LABELS[TRANSACTION_ACTION_REQUEST]),
(TRANSLATION_CREATED, DISPLAY_LABELS[TRANSLATION_CREATED]),
(TRANSLATION_UPDATED, DISPLAY_LABELS[TRANSLATION_UPDATED]),
]
@@ -264,6 +268,7 @@ class WebhookEventAsyncType:
SHIPPING_ZONE_CREATED: ShippingPermissions.MANAGE_SHIPPING,
SHIPPING_ZONE_UPDATED: ShippingPermissions.MANAGE_SHIPPING,
SHIPPING_ZONE_DELETED: ShippingPermissions.MANAGE_SHIPPING,
+ TRANSACTION_ACTION_REQUEST: PaymentPermissions.HANDLE_PAYMENTS,
TRANSLATION_CREATED: SitePermissions.MANAGE_TRANSLATIONS,
TRANSLATION_UPDATED: SitePermissions.MANAGE_TRANSLATIONS,
}
@@ -393,6 +398,7 @@ SUBSCRIBABLE_EVENTS = [
WebhookEventAsyncType.SHIPPING_ZONE_CREATED,
WebhookEventAsyncType.SHIPPING_ZONE_UPDATED,
WebhookEventAsyncType.SHIPPING_ZONE_DELETED,
+ WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST,
WebhookEventAsyncType.TRANSLATION_CREATED,
WebhookEventAsyncType.TRANSLATION_UPDATED,
]
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 0e32f4060c..0f9901b041 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -50,7 +50,7 @@ if TYPE_CHECKING:
from ..discount.models import Sale
from ..graphql.discount.mutations import NodeCatalogueInfo
from ..invoice.models import Invoice
- from ..payment.interface import PaymentData
+ from ..payment.interface import PaymentData, TransactionActionData
from ..payment.models import Payment
from ..plugins.base_plugin import RequestorOrLazyObject
from ..translation.models import Translation
@@ -1101,3 +1101,60 @@ def generate_excluded_shipping_methods_for_checkout_payload(
],
}
return json.dumps(payload, cls=CustomJsonEncoder)
+
+
+@traced_payload_generator
+def generate_transaction_action_request_payload(
+ transaction_data: "TransactionActionData",
+ requestor: Optional["RequestorOrLazyObject"] = None,
+) -> str:
+ transaction = transaction_data.transaction
+
+ action_value = (
+ quantize_price(transaction_data.action_value, transaction.currency)
+ if transaction_data.action_value
+ else None
+ )
+
+ order_id = transaction.order_id
+ graphql_order_id = (
+ graphene.Node.to_global_id("Order", order_id) if order_id else None
+ )
+
+ checkout_id = transaction.checkout_id
+ graphql_checkout_id = (
+ graphene.Node.to_global_id("Checkout", checkout_id) if checkout_id else None
+ )
+
+ payload = {
+ "action": {
+ "type": transaction_data.action_type,
+ "value": action_value,
+ "currency": transaction.currency,
+ },
+ "transaction": {
+ "status": transaction.status,
+ "type": transaction.type,
+ "reference": transaction.reference,
+ "available_actions": transaction.available_actions,
+ "currency": transaction.currency,
+ "captured_value": quantize_price(
+ transaction.captured_value, transaction.currency
+ ),
+ "authorized_value": quantize_price(
+ transaction.authorized_value, transaction.currency
+ ),
+ "refunded_value": quantize_price(
+ transaction.refunded_value, transaction.currency
+ ),
+ "voided_value": quantize_price(
+ transaction.voided_value, transaction.currency
+ ),
+ "order_id": graphql_order_id,
+ "checkout_id": graphql_checkout_id,
+ "created_at": transaction.created_at,
+ "modified_at": transaction.modified_at,
+ },
+ "meta": generate_meta(requestor_data=generate_requestor(requestor)),
+ }
+ return json.dumps(payload, cls=CustomJsonEncoder)
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 09734f441f..51aa5ff844 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -7,6 +7,7 @@ from unittest import mock
from unittest.mock import ANY
import graphene
+import pytest
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import timezone
from freezegun import freeze_time
@@ -22,6 +23,9 @@ from ...order import OrderOrigin
from ...order.actions import fulfill_order_lines
from ...order.fetch import OrderLineInfo
from ...order.models import Order
+from ...payment import TransactionAction
+from ...payment.interface import TransactionActionData
+from ...payment.models import TransactionItem
from ...plugins.manager import get_plugins_manager
from ...plugins.webhook.utils import from_payment_app_id
from ...product.models import ProductVariant
@@ -45,6 +49,7 @@ from ..payloads import (
generate_product_variant_with_stock_payload,
generate_requestor,
generate_sale_payload,
+ generate_transaction_action_request_payload,
generate_translation_payload,
)
from ..serializers import serialize_checkout_lines
@@ -1281,3 +1286,155 @@ def test_generate_meta(app, rf):
"issued_at": timestamp,
"version": __version__,
}
+
+
+ "action_type, action_value",
+ [
+ (TransactionAction.CAPTURE, Decimal("5.000")),
+ (TransactionAction.REFUND, Decimal("9.000")),
+ (TransactionAction.VOID, None),
+ ],
+)
+@freeze_time("1914-06-28 10:50")
+def test_generate_transaction_action_request_payload_for_order(
+ action_type, action_value, order, app, rf
+):
+ # given
+ request = rf.request()
+ request.app = app
+ request.user = None
+ requestor = get_user_or_app_from_context(request)
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+
+ # when
+ payload = json.loads(
+ generate_transaction_action_request_payload(
+ transaction_data=TransactionActionData(
+ transaction=transaction,
+ action_type=action_type,
+ action_value=action_value,
+ ),
+ requestor=requestor,
+ )
+ )
+
+ # then
+ currency = transaction.currency
+ action_value = str(quantize_price(action_value, currency)) if action_value else None
+ assert payload == {
+ "action": {
+ "type": action_type,
+ "value": action_value,
+ "currency": currency,
+ },
+ "transaction": {
+ "status": transaction.status,
+ "type": transaction.type,
+ "reference": transaction.reference,
+ "available_actions": transaction.available_actions,
+ "currency": currency,
+ "captured_value": str(quantize_price(transaction.captured_value, currency)),
+ "authorized_value": str(
+ quantize_price(transaction.authorized_value, currency)
+ ),
+ "refunded_value": str(quantize_price(transaction.refunded_value, currency)),
+ "voided_value": str(quantize_price(transaction.voided_value, currency)),
+ "order_id": graphene.Node.to_global_id("Order", order.pk),
+ "checkout_id": None,
+ "created_at": parse_django_datetime(transaction.created_at),
+ "modified_at": parse_django_datetime(transaction.modified_at),
+ },
+ "meta": {
+ "issuing_principal": {"id": "Sample app objects", "type": "app"},
+ "issued_at": timezone.make_aware(
+ datetime.strptime("1914-06-28 10:50", "%Y-%m-%d %H:%M"), timezone.utc
+ ).isoformat(),
+ "version": __version__,
+ },
+ }
+
+
+ "action_type, action_value",
+ [
+ (TransactionAction.CAPTURE, Decimal("5.000")),
+ (TransactionAction.REFUND, Decimal("9.000")),
+ (TransactionAction.VOID, None),
+ ],
+)
+@freeze_time("1914-06-28 10:50")
+def test_generate_transaction_action_request_payload_for_checkout(
+ action_type, action_value, checkout, app, rf
+):
+ # given
+ request = rf.request()
+ request.app = app
+ request.user = None
+ requestor = get_user_or_app_from_context(request)
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ type="Credit card",
+ reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ authorized_value=Decimal("10"),
+ )
+
+ # when
+ payload = json.loads(
+ generate_transaction_action_request_payload(
+ transaction_data=TransactionActionData(
+ transaction=transaction,
+ action_type=action_type,
+ action_value=action_value,
+ ),
+ requestor=requestor,
+ )
+ )
+
+ # then
+ currency = transaction.currency
+ action_value = str(quantize_price(action_value, currency)) if action_value else None
+ assert payload == {
+ "action": {
+ "type": action_type,
+ "value": action_value,
+ "currency": currency,
+ },
+ "transaction": {
+ "status": transaction.status,
+ "type": transaction.type,
+ "reference": transaction.reference,
+ "available_actions": transaction.available_actions,
+ "currency": currency,
+ "captured_value": str(quantize_price(transaction.captured_value, currency)),
+ "authorized_value": str(
+ quantize_price(transaction.authorized_value, currency)
+ ),
+ "refunded_value": str(quantize_price(transaction.refunded_value, currency)),
+ "voided_value": str(quantize_price(transaction.voided_value, currency)),
+ "order_id": None,
+ "checkout_id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "created_at": parse_django_datetime(transaction.created_at),
+ "modified_at": parse_django_datetime(transaction.modified_at),
+ },
+ "meta": {
+ "issuing_principal": {"id": "Sample app objects", "type": "app"},
+ "issued_at": timezone.make_aware(
+ datetime.strptime("1914-06-28 10:50", "%Y-%m-%d %H:%M"), timezone.utc
+ ).isoformat(),
+ "version": __version__,
+ },
+ }