Skip to content

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

Support for payment transaction actions (#12401)

Maciej Korycinskif3c936f539bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0661291b9b..08100a9f1d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,8 +3,107 @@
All notable, unreleased changes to this project will be documented in this file. For the released changes, please visit the [Releases](https://github.com/mirumee/saleor/releases) page.
# 3.13.0 [Unreleased]
+### Highlights
+- Improve support for handling transactions - #10350 by @korycins
+ - API changes:
+ - Add new mutations:
+ - `transactionEventReport` - Report the event for the transaction.
+ - `orderGrantRefundCreate` - Add granted refund to the order.
+ - `orderGrantRefundUpdate` - Update granted refund.
+ - Add new types:
+ - `OrderGrantedRefund` - The details of granted refund.
+ - Add new webhooks:
+ - `TRANSACTION_CHARGE_REQUESTED` - triggered when a staff user request charge for the transaction.
+ - `TRANSACTION_REFUND_REQUESTED` - triggered when a staff user request refund for the transaction.
+ - `TRANSACTION_CANCELATION_REQUESTED` - triggered when a staff user request cancelation for the transaction.
+ - Add new webhook subscriptions:
+ - `TransactionChargeRequested` - Event sent when transaction charge is requested.
+ - `TransactionRefundRequested` - Event sent when transaction refund is requested.
+ - `TransactionCancelationRequested` - Event sent when transaction cancelation is requested.
+ - Add new fields:
+ - `OrderSettings.markAsPaidStrategy` - Determine what strategy will be used to mark the order as paid.
+ - `TransactionItem`:
+ - `authorizePendingAmount` - Total amount of ongoing authorization requests for the transaction.
+ - `refundPendingAmount` - Total amount of ongoing refund requests for the transaction.
+ - `cancelPendingAmount` - Total amount of ongoing cancel requests for the transaction.
+ - `chargePendingAmount` - Total amount of ongoing charge requests for the transaction.
+ - `canceledAmount` - Total amount canceled for this transaction.
+ - `name` - Name of the transaction.
+ - `message` - Message related to the transaction.
+ - `pspReference` - PSP reference of transaction.
+ - `createdBy` - User or App that created the transaction.
+ - `externalUrl` - The url that will allow to redirect user to payment provider page with transaction details.
+ - `TransactionEvent`:
+ - `pspReference` - PSP reference related to the event.
+ - `message` - Message related to the transaction's event.
+ - `externalUrl` - The url that will allow to redirect user to payment provider page with transaction event details.
+ - `amount` - The amount related to this event.
+ - `type` - The type of action related to this event.
+ - `createdBy` - User or App that created the event.
+ - `Order`:
+ - `totalCharged` - Amount charged for the order.
+ - `totalCanceled` - Amount canceled for the order.
+ - `grantedRefunds` - List of granted refunds.
+ - `totalGrantedRefund` - Total amount of granted refund.
+ - `totalRefunded` - Total refund amount for the order.
+ - `totalRefundPending` - Total amount of ongoing refund requests for the order's transactions.
+ - `totalAuthorizePending` - Total amount of ongoing authorize requests for the order's transactions.
+ - `totalChargePending` - Total amount of ongoing charge requests for the order's transactions.
+ - `totalCancelPending` - Total amount of ongoing cancel requests for the order's transactions.
+ - `totalRemainingGrant` - The difference amount between granted refund and the amounts that are pending and refunded.
+ - `OrderEventsEnum`:
+ - `TRANSACTION_CHARGE_REQUESTED`
+ - `TRANSACTION_CANCEL_REQUESTED`
+ - `TRANSACTION_MARK_AS_PAID_FAILED`
+ - Add new input fields:
+ - `TransactionCreateInput` & `TransactionUpdateInput`:
+ - `name` - The name of the transaction.
+ - `message` - The message of the transaction.
+ - `pspReference` - The PSP Reference of the transaction.
+ - `amountCanceled` - Amount canceled by this transaction.
+ - `externalUrl` - The url that will allow to redirect user to payment provider page with transaction.
+ - `TransactionEventInput`:
+ - `pspReference` - The PSP Reference of the transaction.
+ - `message` - Message related to the transaction's event.
+
+ - Deprecate webhooks:
+ - `TRANSACTION_ACTION_REQUEST` - Use `TRANSACTION_CHARGE_REQUESTED`, `TRANSACTION_REFUND_REQUESTED`, `TRANSACTION_CANCELATION_REQUESTED` instead.
+ - Deprecate object fields:
+ - `TransactionItem`:
+ - `voidedAmount` - Use `canceledAmount`. This field will be removed in Saleor 3.14 (Preview feature).
+ - `status` - Not needed anymore. The transaction amounts will be used to determine a current status of transactions. This field will be removed in Saleor 3.14 (Preview feature).
+ - `reference` - Use `pspReference` instead. This field will be removed in Saleor 3.14 (Preview feature).
+ - `TransactionEvent`:
+ - `status` - Use `type` instead. This field will be removed in Saleor 3.14 (Preview feature).
+ - `reference` - Use `pspReference` instead. This field will be removed in Saleor 3.14 (Preview feature).
+ - `name` - Use `message` instead. This field will be removed in Saleor 3.14 (Preview feature).
+ - `TransactionActionEnum`
+ - `VOID` - Use `CANCEL` instead. This field will be removed in Saleor 3.14 (Preview feature).
+ - `Order`:
+ - `totalCaptured` - Use `totalCharged` instead. Will be removed in Saleor 4.0
+ - `OrderEvent`:
+ - `status` - Use `TransactionEvent` to track the status of `TransactionItem`. This field will be removed in Saleor 3.14 (Preview feature).
+ - `OrderEventsEnum`:
+ - `TRANSACTION_CAPTURE_REQUESTED` - Use `TRANSACTION_CHARGE_REQUESTED` instead. This field will be removed in Saleor 3.14 (Preview feature).
+ - `TRANSACTION_VOID_REQUESTED` - Use `TRANSACTION_CANCEL_REQUESTED` instead. This field will be removed in Saleor 3.14 (Preview feature).
+
+ - Deprecate input fields:
+ - `TransactionCreateInput` & `TransactionUpdateInput`:
+ - `status` - Not needed anymore. The transaction amounts will be used to determine a current status of transactions. This input field will be removed in Saleor 3.14 (Preview feature).
+ - `type` - Use `name` and `message` instead. This input field will be removed in Saleor 3.14 (Preview feature).
+ - `reference` - Use `pspReference` instead. This input field will be removed in Saleor 3.14 (Preview feature).
+ - `amountVoided` - Use `amountCanceled` instead. This input field will be removed in Saleor 3.14 (Preview feature).
+ - `TransactionEventInput`:
+ - `status` - Status will be calculated by Saleor. This input field will be removed in Saleor 3.14 (Preview feature).
+ - `reference` - Use `pspReference` instead. This input field will be removed in Saleor 3.14 (Preview feature).
+ - `name` - Use `message` instead. This field will be removed in Saleor 3.14 (Preview feature).
### Breaking changes
+- **Feature preview breaking change**:
+ - Improve support for handling transactions - #10350 by @korycins
+ - For all new `transactionItem` created by `transactionCreate`, any update action can be done only by the same app/user that performed `transactionCreate` action. This changes has impact only on new `transactionItem`, already existing will work in the same way as previously.
+ - `transactionRequestAction` mutation can't be executed with `MANAGE_ORDERS` permission. Permission `HANDLE_PAYMENTS` is required.
+ - Drop calling `TRANSACTION_ACTION_REQUEST` webhook inside a mutation related to `Payment` types. The related mutations: `orderVoid`, `orderCapture`, `orderRefund`, `orderFulfillmentRefundProducts`, `orderFulfillmentReturnProducts`. Use dedicated mutation for triggering an action: `transactionRequestAction`.
### GraphQL API
- [Preview] Add `StockBulkUpdate` mutation - #12139 by @SzymJ
diff --git a/saleor/celeryconf.py b/saleor/celeryconf.py
index 2ab37df664..52ebf0f8df 100644
--- a/saleor/celeryconf.py
+++ b/saleor/celeryconf.py
@@ -29,9 +29,9 @@ app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
app.autodiscover_tasks(
packages=[
- "saleor.payment.migrations.tasks",
+ "saleor.order.migrations.tasks",
],
- related_name="saleor3_12",
+ related_name="saleor3_13",
)
app.autodiscover_tasks(lambda: discover_plugins_modules(settings.PLUGINS)) # type: ignore[misc] # circular import # noqa: E501
app.autodiscover_tasks(related_name="search_tasks")
diff --git a/saleor/channel/__init__.py b/saleor/channel/__init__.py
index c498e4774c..67ebe25c9f 100644
--- a/saleor/channel/__init__.py
+++ b/saleor/channel/__init__.py
@@ -14,3 +14,23 @@ class AllocationStrategy:
(PRIORITIZE_SORTING_ORDER, "Prioritize sorting order"),
(PRIORITIZE_HIGH_STOCK, "Prioritize high stock"),
]
+
+
+class MarkAsPaidStrategy:
+ """Determine the mark as paid strategy for the channel.
+
+ TRANSACTION_FLOW - new orders marked as paid will receive a
+ `TransactionItem` object, that will cover the `order.total`.
+
+ PAYMENT_FLOW - new orders marked as paid will receive a
+ `Payment` object, that will cover the `order.total`.
+
+ """
+
+ TRANSACTION_FLOW = "transaction_flow"
+ PAYMENT_FLOW = "payment_flow"
+
+ CHOICES = [
+ (TRANSACTION_FLOW, "Use transaction"),
+ (PAYMENT_FLOW, "Use payment"),
+ ]
diff --git a/saleor/channel/migrations/0009_channel_order_mark_as_paid_strategy.py b/saleor/channel/migrations/0009_channel_order_mark_as_paid_strategy.py
new file mode 100644
index 0000000000..95a5a766de
--- /dev/null
+++ b/saleor/channel/migrations/0009_channel_order_mark_as_paid_strategy.py
@@ -0,0 +1,32 @@
+# Generated by Django 3.2.17 on 2023-02-08 14:43
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("channel", "0008_update_null_order_settings"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="channel",
+ name="order_mark_as_paid_strategy",
+ field=models.CharField(
+ choices=[
+ ("transaction_flow", "Use transaction"),
+ ("payment_flow", "Use payment"),
+ ],
+ default="payment_flow",
+ max_length=255,
+ ),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE channel_channel
+ ALTER COLUMN order_mark_as_paid_strategy
+ SET DEFAULT 'payment_flow';
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/channel/models.py b/saleor/channel/models.py
index 1314c7b106..d05a9f2ebd 100644
--- a/saleor/channel/models.py
+++ b/saleor/channel/models.py
@@ -3,7 +3,7 @@ from django.db import models
from django_countries.fields import CountryField
from ..permission.enums import ChannelPermissions
-from . import AllocationStrategy
+from . import AllocationStrategy, MarkAsPaidStrategy
class Channel(models.Model):
@@ -17,11 +17,22 @@ class Channel(models.Model):
choices=AllocationStrategy.CHOICES,
default=AllocationStrategy.PRIORITIZE_SORTING_ORDER,
)
+ order_mark_as_paid_strategy = models.CharField(
+ max_length=255,
+ choices=MarkAsPaidStrategy.CHOICES,
+ default=MarkAsPaidStrategy.PAYMENT_FLOW,
+ )
+
automatically_confirm_all_new_orders = models.BooleanField(default=True, null=True)
automatically_fulfill_non_shippable_gift_card = models.BooleanField(
default=True,
null=True,
)
+ order_mark_as_paid_strategy = models.CharField(
+ max_length=255,
+ choices=MarkAsPaidStrategy.CHOICES,
+ default=MarkAsPaidStrategy.PAYMENT_FLOW,
+ )
class Meta:
ordering = ("slug",)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index bcedd05cf0..a264743663 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -23,6 +23,7 @@ from prices import Money, TaxedMoney
from ..account.error_codes import AccountErrorCode
from ..account.models import User
from ..account.utils import store_user_address
+from ..channel import MarkAsPaidStrategy
from ..checkout import calculations
from ..checkout.error_codes import CheckoutErrorCode
from ..core.exceptions import GiftCardNotApplicable, InsufficientStock
@@ -43,7 +44,11 @@ from ..graphql.checkout.utils import (
prepare_insufficient_stock_checkout_validation_error,
)
from ..order import OrderOrigin, OrderStatus
-from ..order.actions import mark_order_as_paid, order_created
+from ..order.actions import (
+ mark_order_as_paid_with_payment,
+ mark_order_as_paid_with_transaction,
+ order_created,
+)
from ..order.fetch import OrderInfo, OrderLineInfo
from ..order.models import Order, OrderLine
from ..order.notifications import send_order_confirmation
@@ -876,7 +881,13 @@ def complete_checkout_post_payment_part(
# if the order total value is 0 it is paid from the definition
if order.total.net.amount == 0:
- mark_order_as_paid(order, user, app, manager)
+ if (
+ order.channel.order_mark_as_paid_strategy
+ == MarkAsPaidStrategy.PAYMENT_FLOW
+ ):
+ mark_order_as_paid_with_payment(order, user, app, manager)
+ else:
+ mark_order_as_paid_with_transaction(order, user, app, manager)
return order, action_required, action_data
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index d28c163e05..6c84a85210 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -8,6 +8,7 @@ from prices import TaxedMoney
from ...account import CustomerEvents
from ...account.models import CustomerEvent
+from ...channel import MarkAsPaidStrategy
from ...core.exceptions import InsufficientStock
from ...core.notify_events import NotifyEventType
from ...core.taxes import zero_money, zero_taxed_money
@@ -15,7 +16,7 @@ from ...core.tests.utils import get_site_context_payload
from ...discount.models import VoucherCustomer
from ...giftcard import GiftCardEvents
from ...giftcard.models import GiftCard, GiftCardEvent
-from ...order import OrderEvents
+from ...order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents
from ...order.models import OrderEvent
from ...order.notifications import get_default_order_payload
from ...payment import TransactionKind
@@ -1189,9 +1190,56 @@ def test_create_order_use_translations(
assert order_line.translated_variant_name == translated_variant_name
+def test_complete_checkout_0_total_with_transaction_for_mark_as_paid(
+ checkout_with_item_total_0,
+ customer_user,
+ app,
+):
+ # given
+ checkout = checkout_with_item_total_0
+
+ channel = checkout.channel
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ # when
+ order, _, _ = complete_checkout(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines,
+ payment_data={},
+ store_source=False,
+ discounts=None,
+ user=customer_user,
+ app=app,
+ )
+
+ # then
+ flush_post_commit_hooks()
+
+ assert order
+ assert order.events.get(type=OrderEvents.ORDER_MARKED_AS_PAID)
+ transaction = order.payment_transactions.get()
+ assert transaction.charged_value == order.total.gross.amount
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
+ assert order.charge_status == OrderChargeStatus.FULL
+
+
+ "mark_as_paid_strategy",
+ [MarkAsPaidStrategy.TRANSACTION_FLOW, MarkAsPaidStrategy.PAYMENT_FLOW],
+)
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_complete_checkout_0_total_captured_payment_creates_expected_events(
mock_notify,
+ mark_as_paid_strategy,
checkout_with_item_total_0,
customer_user,
channel_USD,
@@ -1201,6 +1249,10 @@ def test_complete_checkout_0_total_captured_payment_creates_expected_events(
checkout = checkout_with_item_total_0
checkout_user = customer_user
+ channel = checkout.channel
+ channel.order_mark_as_paid_strategy = mark_as_paid_strategy
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
# Ensure not events are existing prior
assert not OrderEvent.objects.exists()
assert not CustomerEvent.objects.exists()
diff --git a/saleor/graphql/app/dataloaders.py b/saleor/graphql/app/dataloaders.py
index 5f75793c59..562171b6c9 100644
--- a/saleor/graphql/app/dataloaders.py
+++ b/saleor/graphql/app/dataloaders.py
@@ -44,6 +44,19 @@ class AppExtensionByAppIdLoader(DataLoader):
return [extensions_map.get(app_id, []) for app_id in keys]
+class AppsByAppIdentifierLoader(DataLoader):
+ context_key = "apps_by_app_identifier"
+
+ def batch_load(self, keys):
+ apps = App.objects.using(self.database_connection_name).filter(
+ identifier__in=keys
+ )
+ apps_map = defaultdict(list)
+ for app in apps:
+ apps_map[app.identifier].append(app)
+ return [apps_map.get(app_identifier, []) for app_identifier in keys]
+
+
class AppByTokenLoader(DataLoader):
context_key = "app_by_token"
diff --git a/saleor/graphql/channel/enums.py b/saleor/graphql/channel/enums.py
index 6a97b7661b..3095eea7b7 100644
--- a/saleor/graphql/channel/enums.py
+++ b/saleor/graphql/channel/enums.py
@@ -1,4 +1,4 @@
-from ...channel import AllocationStrategy
+from ...channel import AllocationStrategy, MarkAsPaidStrategy
from ..core.enums import to_enum
AllocationStrategyEnum = to_enum(
@@ -6,3 +6,9 @@ AllocationStrategyEnum = to_enum(
type_name="AllocationStrategyEnum",
description=AllocationStrategy.__doc__,
)
+
+MarkAsPaidStrategyEnum = to_enum(
+ MarkAsPaidStrategy,
+ type_name="MarkAsPaidStrategyEnum",
+ description=MarkAsPaidStrategy.__doc__,
+)
diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.py
index c7c8a733e6..321674c03f 100644
--- a/saleor/graphql/channel/mutations/channel_create.py
+++ b/saleor/graphql/channel/mutations/channel_create.py
@@ -12,12 +12,13 @@ from ...core.descriptions import (
ADDED_IN_35,
ADDED_IN_37,
ADDED_IN_312,
+ ADDED_IN_313,
PREVIEW_FEATURE,
)
from ...core.mutations import ModelMutation
from ...core.types import ChannelError, NonNullList
from ...plugins.dataloaders import get_plugin_manager_promise
-from ..enums import AllocationStrategyEnum
+from ..enums import AllocationStrategyEnum, MarkAsPaidStrategyEnum
from ..types import Channel
@@ -43,6 +44,18 @@ class OrderSettingsInput(graphene.InputObjectType):
description="When enabled, all non-shippable gift card orders "
"will be fulfilled automatically. By defualt set to True.",
)
+ mark_as_paid_strategy = MarkAsPaidStrategyEnum(
+ required=False,
+ description=(
+ "Determine what strategy will be used to mark the order as paid. "
+ "Based on the chosen option, the proper object will be created "
+ "and attached to the order when it's manually marked as paid."
+ "\n`PAYMENT_FLOW` - [default option] creates the `Payment` object."
+ "\n`TRANSACTION_FLOW` - creates the `TransactionItem` object."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ )
class ChannelInput(graphene.InputObjectType):
@@ -130,6 +143,8 @@ class ChannelCreate(ModelMutation):
cleaned_input[
"automatically_fulfill_non_shippable_gift_card"
] = automatically_fulfill_non_shippable_gift_card
+ if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):
+ cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategy
return cleaned_input
diff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.py
index 093290ce18..a44dcc407a 100644
--- a/saleor/graphql/channel/mutations/channel_update.py
+++ b/saleor/graphql/channel/mutations/channel_update.py
@@ -106,6 +106,8 @@ class ChannelUpdate(ModelMutation):
"automatically_fulfill_non_shippable_gift_card"
] = automatically_fulfill_non_shippable_gift_card
+ if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):
+ cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategy
return cleaned_input
@classmethod
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.py
index 14c86cc352..57cfc65aee 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py
@@ -13,7 +13,7 @@ from .....tax.models import TaxConfiguration
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate_meta, generate_requestor
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...enums import AllocationStrategyEnum
+from ...enums import AllocationStrategyEnum, MarkAsPaidStrategyEnum
CHANNEL_CREATE_MUTATION = """
mutation CreateChannel($input: ChannelCreateInput!){
@@ -36,6 +36,7 @@ CHANNEL_CREATE_MUTATION = """
orderSettings {
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
+ markAsPaidStrategy
}
}
errors{
@@ -459,3 +460,47 @@ def test_channel_create_creates_tax_configuration(
# then
channel = Channel.objects.get(slug=slug)
assert TaxConfiguration.objects.filter(channel=channel).exists()
+
+
+def test_channel_create_set_order_mark_as_paid(
+ permission_manage_channels,
+ staff_api_client,
+):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ default_country = "US"
+ variables = {
+ "input": {
+ "name": name,
+ "slug": slug,
+ "currencyCode": currency_code,
+ "defaultCountry": default_country,
+ "orderSettings": {
+ "markAsPaidStrategy": MarkAsPaidStrategyEnum.TRANSACTION_FLOW.name
+ },
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelCreate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ channel = Channel.objects.get()
+ assert (
+ channel_data["orderSettings"]["markAsPaidStrategy"]
+ == MarkAsPaidStrategyEnum.TRANSACTION_FLOW.name
+ )
+ assert (
+ channel.order_mark_as_paid_strategy
+ == MarkAsPaidStrategyEnum.TRANSACTION_FLOW.value
+ )
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index 28119d7ead..537e328e5a 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -12,7 +12,7 @@ from .....core.utils.json_serializer import CustomJsonEncoder
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate_meta, generate_requestor
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...enums import AllocationStrategyEnum
+from ...enums import AllocationStrategyEnum, MarkAsPaidStrategyEnum
CHANNEL_UPDATE_MUTATION = """
mutation UpdateChannel($id: ID!,$input: ChannelUpdateInput!){
@@ -35,6 +35,7 @@ CHANNEL_UPDATE_MUTATION = """
orderSettings {
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
+ markAsPaidStrategy
}
}
errors{
@@ -877,3 +878,44 @@ def test_channel_update_order_settings_manage_orders_as_app_permission_denied(
# then
assert_no_permission(response)
+
+
+def test_channel_update_order_mark_as_paid_strategy(
+ permission_manage_orders,
+ staff_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "orderSettings": {
+ "automaticallyConfirmAllNewOrders": False,
+ "automaticallyFulfillNonShippableGiftCard": False,
+ "markAsPaidStrategy": MarkAsPaidStrategyEnum.TRANSACTION_FLOW.name,
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_orders,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ assert (
+ channel_data["orderSettings"]["markAsPaidStrategy"]
+ == MarkAsPaidStrategyEnum.TRANSACTION_FLOW.name
+ )
+ channel_USD.refresh_from_db()
+ assert (
+ channel_USD.order_mark_as_paid_strategy
+ == MarkAsPaidStrategyEnum.TRANSACTION_FLOW.value
+ )
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index daa8232236..8cccef73d9 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -21,6 +21,7 @@ from ..core.descriptions import (
ADDED_IN_36,
ADDED_IN_37,
ADDED_IN_312,
+ ADDED_IN_313,
PREVIEW_FEATURE,
)
from ..core.fields import PermissionsField
@@ -31,7 +32,7 @@ from ..warehouse.dataloaders import WarehousesByChannelIdLoader
from ..warehouse.types import Warehouse
from . import ChannelContext
from .dataloaders import ChannelWithHasOrdersByIdLoader
-from .enums import AllocationStrategyEnum
+from .enums import AllocationStrategyEnum, MarkAsPaidStrategyEnum
if TYPE_CHECKING:
from ...shipping.models import ShippingZone
@@ -179,6 +180,19 @@ class OrderSettings(ObjectType):
),
)
+ mark_as_paid_strategy = MarkAsPaidStrategyEnum(
+ required=True,
+ description=(
+ "Determine what strategy will be used to mark the order as paid. "
+ "Based on the chosen option, the proper object will be created "
+ "and attached to the order when it's manually marked as paid."
+ "\n`PAYMENT_FLOW` - [default option] creates the `Payment` object."
+ "\n`TRANSACTION_FLOW` - creates the `TransactionItem` object."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ )
+
class Meta:
description = "Represents the channel-specific order settings."
@@ -426,4 +440,5 @@ class Channel(ModelObjectType):
automatically_fulfill_non_shippable_gift_card=(
root.automatically_fulfill_non_shippable_gift_card
),
+ mark_as_paid_strategy=root.order_mark_as_paid_strategy,
)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index bb440c8e63..969fc66b6f 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -2123,8 +2123,8 @@ def test_checkout_transactions_missing_permission(api_client, checkout):
# given
checkout.payment_transactions.create(
status="Authorized",
- type="Credit card",
- reference="123",
+ name="Credit card",
+ psp_reference="123",
currency="USD",
authorized_value=Decimal("15"),
available_actions=[TransactionAction.CHARGE, TransactionAction.VOID],
@@ -2145,8 +2145,8 @@ def test_checkout_transactions_with_manage_checkouts(
# given
transaction = checkout.payment_transactions.create(
status="Authorized",
- type="Credit card",
- reference="123",
+ name="Credit card",
+ psp_reference="123",
currency="USD",
authorized_value=Decimal("15"),
available_actions=[TransactionAction.CHARGE, TransactionAction.VOID],
@@ -2174,8 +2174,8 @@ def test_checkout_transactions_with_handle_payments(
# given
transaction = checkout.payment_transactions.create(
status="Authorized",
- type="Credit card",
- reference="123",
+ name="Credit card",
+ psp_reference="123",
currency="USD",
authorized_value=Decimal("15"),
available_actions=[TransactionAction.CHARGE, TransactionAction.VOID],
diff --git a/saleor/graphql/core/descriptions.py b/saleor/graphql/core/descriptions.py
index 0ea6be3d25..d2825dc167 100644
--- a/saleor/graphql/core/descriptions.py
+++ b/saleor/graphql/core/descriptions.py
@@ -1,11 +1,16 @@
# Deprecation message for queries, object fields and mutations. Use it, when
# `deprecation_reason` argument is supported.
DEPRECATED_IN_3X_FIELD = "This field will be removed in Saleor 4.0."
+PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD = (
+ "This field will be removed in Saleor 3.14 (Preview Feature)."
+)
# Deprecation message for input fields and query arguments. Use it, when
# deprecation message needs to be included in the field description.
DEPRECATED_IN_3X_INPUT = "\n\nDEPRECATED: this field will be removed in Saleor 4.0."
-
+PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT = (
+ "\n\nDEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature)."
+)
DEPRECATED_IN_3X_MUTATION = (
"\n\nDEPRECATED: this mutation will be removed in Saleor 4.0."
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 63fc90d8cb..29e2f7d7d1 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -164,6 +164,9 @@ TransactionUpdateErrorCode = graphene.Enum.from_enum(
TransactionRequestActionErrorCode = graphene.Enum.from_enum(
payment_error_codes.TransactionRequestActionErrorCode
)
+TransactionEventReportErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.TransactionEventReportErrorCode
+)
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 989c4ee1e3..4f3096ef3a 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -46,6 +46,7 @@ from ..enums import (
ThumbnailFormatEnum,
TimePeriodTypeEnum,
TransactionCreateErrorCode,
+ TransactionEventReportErrorCode,
TransactionRequestActionErrorCode,
TransactionUpdateErrorCode,
TranslationErrorCode,
@@ -420,6 +421,10 @@ class TransactionRequestActionError(Error):
)
+class TransactionEventReportError(Error):
+ code = TransactionEventReportErrorCode(description="The error code.", required=True)
+
+
class GiftCardError(Error):
code = GiftCardErrorCode(description="The error code.", required=True)
tags = NonNullList(
diff --git a/saleor/graphql/core/types/user_or_app.py b/saleor/graphql/core/types/user_or_app.py
new file mode 100644
index 0000000000..7c9e435bf3
--- /dev/null
+++ b/saleor/graphql/core/types/user_or_app.py
@@ -0,0 +1,22 @@
+import graphene
+
+from ....account import models as account_models
+from ....app import models as app_models
+from ...account import types as account_types
+from ...app import types as app_types
+
+
+# The file hasn't been attached to the __init__ file as it generates the circular
+# graphql import. Graphene for Union types requires already initialized types so
+# we need to provide a fully initialized type.
+class UserOrApp(graphene.Union):
+ class Meta:
+ types = (account_types.User, app_types.App)
+
+ @classmethod
+ def resolve_type(cls, instance, info):
+ if isinstance(instance, account_models.User):
+ return account_types.User
+ if isinstance(instance, app_models.App):
+ return account_types.App
+ return super(UserOrApp, cls).resolve_type(instance, info)
diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.py
index 1c0d9146a5..46eca5450e 100644
--- a/saleor/graphql/core/utils/__init__.py
+++ b/saleor/graphql/core/utils/__init__.py
@@ -8,7 +8,7 @@ from django.core.exceptions import ValidationError
from graphene import ObjectType
from graphql.error import GraphQLError
-from ....plugins.webhook.utils import APP_ID_PREFIX
+from ....plugins.const import APP_ID_PREFIX
from ..validators import validate_if_int_or_uuid
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index 5276706b8a..09eabf73d9 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -3,7 +3,14 @@ from typing import DefaultDict, Iterable, List, Tuple, cast
from django.db.models import F
-from ...order.models import Fulfillment, FulfillmentLine, Order, OrderEvent, OrderLine
+from ...order.models import (
+ Fulfillment,
+ FulfillmentLine,
+ Order,
+ OrderEvent,
+ OrderGrantedRefund,
+ OrderLine,
+)
from ...payment.models import TransactionItem
from ...warehouse.models import Allocation
from ..core.dataloaders import DataLoader
@@ -108,6 +115,20 @@ class OrderEventsByOrderIdLoader(DataLoader):
return [events_map.get(order_id, []) for order_id in keys]
+class OrderGrantedRefundsByOrderIdLoader(DataLoader):
+ context_key = "order_granted_refunds_by_order_id"
+
+ def batch_load(self, keys):
+ refunds = OrderGrantedRefund.objects.using(
+ self.database_connection_name
+ ).filter(order_id__in=keys)
+ refunds_map = defaultdict(list)
+
+ for refund in refunds.iterator():
+ refunds_map[refund.order_id].append(refund)
+ return [refunds_map.get(order_id, []) for order_id in keys]
+
+
class AllocationsByOrderLineIdLoader(DataLoader):
context_key = "allocations_by_orderline_id"
diff --git a/saleor/graphql/order/enums.py b/saleor/graphql/order/enums.py
index e12c53fbb5..d56f66fef6 100644
--- a/saleor/graphql/order/enums.py
+++ b/saleor/graphql/order/enums.py
@@ -9,10 +9,29 @@ from ...order import (
OrderEventsEmails,
OrderOrigin,
OrderStatus,
+ error_codes,
)
+from ..core.descriptions import PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD
+
+
+def order_event_enum_description(enum):
+ if enum is None:
+ return "The different order event types. "
+ if enum == OrderEventsEnum.TRANSACTION_VOID_REQUESTED:
+ return (
+ f"{PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD} "
+ "Use `TRANSACTION_CANCEL_REQUESTED` instead."
+ )
+ if enum == OrderEventsEnum.TRANSACTION_CAPTURE_REQUESTED:
+ return (
+ f"{PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD} "
+ "Use `TRANSACTION_CHARGE_REQUESTED` instead."
+ )
+ return None
+
FulfillmentStatusEnum = to_enum(FulfillmentStatus, type_name="FulfillmentStatus")
-OrderEventsEnum = to_enum(OrderEvents)
+OrderEventsEnum = to_enum(OrderEvents, description=order_event_enum_description)
OrderEventsEmailsEnum = to_enum(OrderEventsEmails)
OrderOriginEnum = to_enum(OrderOrigin)
OrderStatusEnum = to_enum(OrderStatus, type_name="OrderStatus")
@@ -23,6 +42,13 @@ OrderChargeStatusEnum = to_enum(
OrderChargeStatus, description=OrderChargeStatus.__doc__
)
+OrderGrantRefundCreateErrorCode = graphene.Enum.from_enum(
+ error_codes.OrderGrantRefundCreateErrorCode
+)
+OrderGrantRefundUpdateErrorCode = graphene.Enum.from_enum(
+ error_codes.OrderGrantRefundUpdateErrorCode
+)
+
class OrderStatusFilter(graphene.Enum):
READY_TO_FULFILL = "ready_to_fulfill"
diff --git a/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py b/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py
index ca00a4016f..27f569e0df 100644
--- a/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py
+++ b/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
import graphene
from django.core.exceptions import ValidationError
@@ -8,7 +6,6 @@ from ....order import FulfillmentLineData
from ....order import models as order_models
from ....order.error_codes import OrderErrorCode
from ....order.fetch import OrderLineInfo
-from ....payment.models import TransactionItem
from ...core.mutations import BaseMutation
from ..types import FulfillmentLine, OrderLine
@@ -78,13 +75,9 @@ 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
+ def raise_error_for_payment_error(cls):
+ msg = "The refund operation is not available yet."
+ code = OrderErrorCode.CANNOT_REFUND.value
raise ValidationError(
msg,
code=code,
diff --git a/saleor/graphql/order/mutations/fulfillment_refund_products.py b/saleor/graphql/order/mutations/fulfillment_refund_products.py
index 163e9050e6..327e88b6a7 100644
--- a/saleor/graphql/order/mutations/fulfillment_refund_products.py
+++ b/saleor/graphql/order/mutations/fulfillment_refund_products.py
@@ -105,14 +105,8 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
info, order_id, field="order", only_type=Order, qs=qs
)
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
- charged_value = transactions[-1].charged_value
- else:
- cls.clean_order_payment(payment, cleaned_input)
- charged_value = payment.captured_amount
+ cls.clean_order_payment(payment, cleaned_input)
+ charged_value = payment.captured_amount
cls.clean_amount_to_refund(
order, amount_to_refund, charged_value, cleaned_input
)
@@ -121,7 +115,6 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
{
"include_shipping_costs": include_shipping_costs,
"order": order,
- "transactions": transactions,
"payment": payment,
}
)
@@ -155,7 +148,6 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
app,
order,
cleaned_input["payment"],
- cleaned_input["transactions"],
cleaned_input.get("order_lines", []),
cleaned_input.get("fulfillment_lines", []),
manager,
@@ -163,5 +155,5 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
cleaned_input["include_shipping_costs"],
)
except PaymentError:
- cls.raise_error_for_payment_error(cleaned_input.get("transactions"))
+ cls.raise_error_for_payment_error()
return cls(order=order, fulfillment=refund_fulfillment)
diff --git a/saleor/graphql/order/mutations/fulfillment_return_products.py b/saleor/graphql/order/mutations/fulfillment_return_products.py
index a4804fac5e..74aa7bc572 100644
--- a/saleor/graphql/order/mutations/fulfillment_return_products.py
+++ b/saleor/graphql/order/mutations/fulfillment_return_products.py
@@ -128,18 +128,11 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
)
if refund:
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
- charged_value = transactions[-1].charged_value
- else:
- cls.clean_order_payment(payment, cleaned_input)
- charged_value = payment.captured_amount
+ cls.clean_order_payment(payment, cleaned_input)
+ charged_value = payment.captured_amount
cls.clean_amount_to_refund(
order, amount_to_refund, charged_value, cleaned_input
)
- cleaned_input["transactions"] = transactions
cleaned_input.update(
{
@@ -178,7 +171,6 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
app,
order,
cleaned_input.get("payment"),
- cleaned_input.get("transactions"),
cleaned_input.get("order_lines", []),
cleaned_input.get("fulfillment_lines", []),
manager,
@@ -187,7 +179,7 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
cleaned_input["include_shipping_costs"],
)
except PaymentError:
- cls.raise_error_for_payment_error(cleaned_input.get("transactions"))
+ cls.raise_error_for_payment_error()
return_fulfillment, replace_fulfillment, replace_order = response
return cls(
diff --git a/saleor/graphql/order/mutations/order_capture.py b/saleor/graphql/order/mutations/order_capture.py
index 64c497b46a..be7e5b226b 100644
--- a/saleor/graphql/order/mutations/order_capture.py
+++ b/saleor/graphql/order/mutations/order_capture.py
@@ -6,9 +6,8 @@ from django.core.exceptions import ValidationError
from ....order.actions import order_captured
from ....order.error_codes import OrderErrorCode
from ....order.fetch import fetch_order_info
-from ....payment import PaymentError, TransactionKind, gateway
+from ....payment import TransactionKind, gateway
from ....payment import models as payment_models
-from ....payment.gateway import request_charge_action
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
@@ -72,51 +71,32 @@ class OrderCapture(BaseMutation):
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
- 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_charge_action(
- transaction=payment_transaction,
- manager=manager,
- charge_value=amount,
- channel_slug=order.channel.slug,
- user=info.context.user,
- app=app,
- )
- except PaymentError as e:
- raise ValidationError(
- str(e),
- code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value,
- )
- else:
- order_info = fetch_order_info(order)
- payment = order_info.payment
- payment = clean_order_capture(payment)
- transaction = try_payment_action(
- order,
+ order_info = fetch_order_info(order)
+ payment = order_info.payment
+ payment = clean_order_capture(payment)
+ transaction = try_payment_action(
+ order,
+ info.context.user,
+ app,
+ payment,
+ gateway.capture,
+ payment,
+ manager,
+ amount=amount,
+ channel_slug=order.channel.slug,
+ )
+ 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:
+ site = get_site_promise(info.context).get()
+ order_captured(
+ order_info,
info.context.user,
app,
- payment,
- gateway.capture,
+ amount,
payment,
manager,
- amount=amount,
- channel_slug=order.channel.slug,
+ site.settings,
)
- 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:
- site = get_site_promise(info.context).get()
- order_captured(
- order_info,
- info.context.user,
- app,
- amount,
- payment,
- manager,
- site.settings,
- )
return OrderCapture(order=order)
diff --git a/saleor/graphql/order/mutations/order_confirm.py b/saleor/graphql/order/mutations/order_confirm.py
index ae32709df0..f1849b5277 100644
--- a/saleor/graphql/order/mutations/order_confirm.py
+++ b/saleor/graphql/order/mutations/order_confirm.py
@@ -11,8 +11,7 @@ from ....order.actions import order_captured, order_confirmed
from ....order.error_codes import OrderErrorCode
from ....order.fetch import fetch_order_info
from ....order.utils import update_order_display_gross_prices
-from ....payment import PaymentError, gateway
-from ....payment.gateway import request_charge_action
+from ....payment import gateway
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
@@ -74,25 +73,7 @@ class OrderConfirm(ModelMutation):
manager = get_plugin_manager_promise(info.context).get()
app = get_app_promise(info.context).get()
with traced_atomic_transaction():
- 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_charge_action(
- transaction=payment_transaction,
- manager=manager,
- charge_value=payment_transaction.authorized_value,
- channel_slug=order.channel.slug,
- user=info.context.user,
- app=app,
- )
- except PaymentError as e:
- raise ValidationError(
- str(e),
- code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value,
- )
- elif payment and payment.is_authorized and payment.can_capture():
+ if payment and payment.is_authorized and payment.can_capture():
authorized_payment = payment
gateway.capture(payment, manager, channel_slug=order.channel.slug)
site = get_site_promise(info.context).get()
diff --git a/saleor/graphql/order/mutations/order_grant_refund_create.py b/saleor/graphql/order/mutations/order_grant_refund_create.py
new file mode 100644
index 0000000000..186a1bf75b
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_grant_refund_create.py
@@ -0,0 +1,60 @@
+import graphene
+
+from ....permission.enums import OrderPermissions
+from ...core import ResolveInfo
+from ...core.descriptions import ADDED_IN_313, PREVIEW_FEATURE
+from ...core.doc_category import DOC_CATEGORY_ORDERS
+from ...core.mutations import BaseMutation
+from ...core.scalars import Decimal
+from ...core.types.common import Error
+from ..enums import OrderGrantRefundCreateErrorCode
+from ..types import Order, OrderGrantedRefund
+
+
+class OrderGrantRefundCreateError(Error):
+ code = OrderGrantRefundCreateErrorCode(description="The error code.", required=True)
+
+
+class OrderGrantRefundCreateInput(graphene.InputObjectType):
+ amount = Decimal(required=True, description="Amount of the granted refund.")
+ reason = graphene.String(description="Reason of the granted refund.")
+
+
+class OrderGrantRefundCreate(BaseMutation):
+ order = graphene.Field(
+ Order, description="Order which has assigned new grant refund."
+ )
+ granted_refund = graphene.Field(
+ OrderGrantedRefund, description="Created granted refund."
+ )
+
+ class Arguments:
+ id = graphene.ID(description="ID of the order.", required=True)
+ input = OrderGrantRefundCreateInput(
+ required=True,
+ description="Fields required to create a granted refund for the order.",
+ )
+
+ class Meta:
+ description = (
+ "Adds granted refund to the order." + ADDED_IN_313 + PREVIEW_FEATURE
+ )
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderGrantRefundCreateError
+ doc_category = DOC_CATEGORY_ORDERS
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, *, id, input
+ ):
+ order = cls.get_node_or_error(info, id, only_type=Order)
+ amount = input["amount"]
+ reason = input.get("reason", "")
+ granted_refund = order.granted_refunds.create(
+ amount_value=amount,
+ currency=order.currency,
+ reason=reason,
+ user=info.context.user,
+ app=info.context.app,
+ )
+ return cls(order=order, granted_refund=granted_refund)
diff --git a/saleor/graphql/order/mutations/order_grant_refund_update.py b/saleor/graphql/order/mutations/order_grant_refund_update.py
new file mode 100644
index 0000000000..da3b9318eb
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_grant_refund_update.py
@@ -0,0 +1,72 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....order import models
+from ....permission.enums import OrderPermissions
+from ...core.descriptions import ADDED_IN_313, PREVIEW_FEATURE
+from ...core.doc_category import DOC_CATEGORY_ORDERS
+from ...core.mutations import ModelMutation
+from ...core.scalars import Decimal
+from ...core.types.common import Error
+from ..enums import OrderGrantRefundUpdateErrorCode
+from ..types import Order, OrderGrantedRefund
+
+
+class OrderGrantRefundUpdateError(Error):
+ code = OrderGrantRefundUpdateErrorCode(description="The error code.", required=True)
+
+
+class OrderGrantRefundUpdateInput(graphene.InputObjectType):
+ amount = Decimal(description="Amount of the granted refund.")
+ reason = graphene.String(description="Reason of the granted refund.")
+
+
+class OrderGrantRefundUpdate(ModelMutation):
+ order = graphene.Field(
+ Order, description="Order which has assigned updated grant refund."
+ )
+ granted_refund = graphene.Field(
+ OrderGrantedRefund, description="Created granted refund."
+ )
+
+ class Arguments:
+ id = graphene.ID(description="ID of the granted refund.", required=True)
+ input = OrderGrantRefundUpdateInput(
+ required=True,
+ description="Fields required to update a granted refund.",
+ )
+
+ class Meta:
+ description = "Updates granted refund." + ADDED_IN_313 + PREVIEW_FEATURE
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderGrantRefundUpdateError
+ model = models.OrderGrantedRefund
+ object_type = OrderGrantedRefund
+ doc_category = DOC_CATEGORY_ORDERS
+
+ @classmethod
+ def validate_input(cls, amount, reason):
+ if not amount and not reason:
+ error_msg = (
+ "At least amount or reason need to be provided to process update."
+ )
+ raise ValidationError(
+ {
+ "input": ValidationError(
+ error_msg, code=OrderGrantRefundUpdateErrorCode.REQUIRED.value
+ )
+ }
+ )
+
+ @classmethod
+ def success_response(cls, instance):
+ return cls(order=instance.order, granted_refund=instance)
+
+ @classmethod
+ def clean_input(cls, info, instance, data, input_cls=None):
+ cleaned_input = super().clean_input(info, instance, data, input_cls=input_cls)
+ amount = cleaned_input.pop("amount", None)
+ cls.validate_input(amount, data.get("reason"))
+ if amount is not None:
+ cleaned_input["amount_value"] = amount
+ return cleaned_input
diff --git a/saleor/graphql/order/mutations/order_mark_as_paid.py b/saleor/graphql/order/mutations/order_mark_as_paid.py
index 3ddcb1daa9..2f0de56e83 100644
--- a/saleor/graphql/order/mutations/order_mark_as_paid.py
+++ b/saleor/graphql/order/mutations/order_mark_as_paid.py
@@ -1,13 +1,21 @@
-from typing import cast
+from typing import TYPE_CHECKING, Optional, cast
import graphene
from django.core.exceptions import ValidationError
from ....account.models import User
-from ....order.actions import clean_mark_order_as_paid, mark_order_as_paid
+from ....channel import MarkAsPaidStrategy
+from ....order import models as order_models
+from ....order.actions import (
+ clean_mark_order_as_paid,
+ mark_order_as_paid_with_payment,
+ mark_order_as_paid_with_transaction,
+)
from ....order.calculations import fetch_order_prices_if_expired
from ....order.error_codes import OrderErrorCode
+from ....order.events import transaction_mark_order_as_paid_failed_event
from ....order.search import update_order_search_vector
+from ....payment import PaymentError
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
@@ -18,6 +26,10 @@ from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import Order
from .utils import try_payment_action
+if TYPE_CHECKING:
+ from ....app.models import App
+ from ....plugins.manager import PluginsManager
+
class OrderMarkAsPaid(BaseMutation):
order = graphene.Field(Order, description="Order marked as paid.")
@@ -43,6 +55,57 @@ class OrderMarkAsPaid(BaseMutation):
code=OrderErrorCode.BILLING_ADDRESS_NOT_SET.value,
)
+ @classmethod
+ def handle_mark_as_paid_for_payment(
+ cls,
+ order: "order_models.Order",
+ request_user: User,
+ app: Optional["App"],
+ manager: "PluginsManager",
+ external_reference: Optional[str] = None,
+ ):
+ try_payment_action(
+ order, request_user, app, None, clean_mark_order_as_paid, order
+ )
+ mark_order_as_paid_with_payment(
+ order=order,
+ request_user=request_user,
+ app=app,
+ manager=manager,
+ external_reference=external_reference,
+ )
+
+ @classmethod
+ def handle_mark_as_paid_for_transaction(
+ cls,
+ order: "order_models.Order",
+ request_user: User,
+ app: Optional["App"],
+ manager: "PluginsManager",
+ external_reference: Optional[str] = None,
+ ):
+ try:
+ clean_mark_order_as_paid(order=order)
+ except (PaymentError, ValueError) as e:
+ message = str(e)
+ transaction_mark_order_as_paid_failed_event(
+ order=order, user=request_user, app=app, message=message
+ )
+ raise ValidationError(
+ {
+ "transaction": ValidationError(
+ message, code=OrderErrorCode.TRANSACTION_ERROR.value
+ )
+ }
+ )
+ mark_order_as_paid_with_transaction(
+ order=order,
+ request_user=request_user,
+ app=app,
+ manager=manager,
+ external_reference=external_reference,
+ )
+
@classmethod
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, id, transaction_reference=None
@@ -54,9 +117,15 @@ class OrderMarkAsPaid(BaseMutation):
user = info.context.user
user = cast(User, user)
app = get_app_promise(info.context).get()
- try_payment_action(order, user, app, None, clean_mark_order_as_paid, order)
-
- mark_order_as_paid(order, user, app, manager, transaction_reference)
+ channel = order.channel
+ if channel.order_mark_as_paid_strategy == MarkAsPaidStrategy.PAYMENT_FLOW:
+ cls.handle_mark_as_paid_for_payment(
+ order, user, app, manager, transaction_reference
+ )
+ else:
+ cls.handle_mark_as_paid_for_transaction(
+ order, user, app, manager, transaction_reference
+ )
update_order_search_vector(order)
diff --git a/saleor/graphql/order/mutations/order_refund.py b/saleor/graphql/order/mutations/order_refund.py
index 15a3eb1884..6e260f6127 100644
--- a/saleor/graphql/order/mutations/order_refund.py
+++ b/saleor/graphql/order/mutations/order_refund.py
@@ -7,9 +7,8 @@ from ....giftcard.utils import order_has_gift_card_lines
from ....order import FulfillmentStatus, models
from ....order.actions import order_refunded
from ....order.error_codes import OrderErrorCode
-from ....payment import PaymentError, TransactionKind, gateway
+from ....payment import TransactionKind, gateway
from ....payment import models as payment_models
-from ....payment.gateway import request_refund_action
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
@@ -85,49 +84,31 @@ class OrderRefund(BaseMutation):
order = clean_order_refund(order)
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
- 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],
- manager,
- refund_value=amount,
- channel_slug=order.channel.slug,
- user=info.context.user,
- app=app,
- )
- except PaymentError as e:
- raise ValidationError(
- str(e),
- code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value,
- )
- else:
- payment = order.get_last_payment()
- payment = clean_payment(payment)
- payment = clean_refund_payment(payment)
- transaction = try_payment_action(
+ payment = order.get_last_payment()
+ payment = clean_payment(payment)
+ payment = clean_refund_payment(payment)
+ transaction = try_payment_action(
+ order,
+ info.context.user,
+ app,
+ payment,
+ gateway.refund,
+ payment,
+ manager,
+ 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,
app,
- payment,
- gateway.refund,
+ amount,
payment,
manager,
- 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,
- app,
- amount,
- payment,
- manager,
- )
order.fulfillments.create(
status=FulfillmentStatus.REFUNDED, total_refund_amount=amount
diff --git a/saleor/graphql/order/mutations/order_void.py b/saleor/graphql/order/mutations/order_void.py
index 7c7c8a393f..412be9c504 100644
--- a/saleor/graphql/order/mutations/order_void.py
+++ b/saleor/graphql/order/mutations/order_void.py
@@ -5,9 +5,8 @@ from django.core.exceptions import ValidationError
from ....order.actions import order_voided
from ....order.error_codes import OrderErrorCode
-from ....payment import PaymentError, TransactionKind, gateway
+from ....payment import TransactionKind, gateway
from ....payment import models as payment_models
-from ....payment.gateway import request_void_action
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
@@ -56,43 +55,26 @@ class OrderVoid(BaseMutation):
order = cls.get_node_or_error(info, id, only_type=Order)
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
- 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],
- manager,
- channel_slug=order.channel.slug,
- user=info.context.user,
- app=app,
- )
- except PaymentError as e:
- raise ValidationError(
- str(e),
- code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value,
- )
- else:
- payment = order.get_last_payment()
- payment = clean_void_payment(payment)
- transaction = try_payment_action(
+ payment = order.get_last_payment()
+ payment = clean_void_payment(payment)
+ transaction = try_payment_action(
+ order,
+ info.context.user,
+ app,
+ payment,
+ gateway.void,
+ payment,
+ manager,
+ 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,
app,
payment,
- gateway.void,
- payment,
manager,
- 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,
- app,
- payment,
- manager,
- )
return OrderVoid(order=order)
diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.py
index 825f7f0f9a..52a944015b 100644
--- a/saleor/graphql/order/schema.py
+++ b/saleor/graphql/order/schema.py
@@ -40,6 +40,8 @@ from .mutations.order_discount_add import OrderDiscountAdd
from .mutations.order_discount_delete import OrderDiscountDelete
from .mutations.order_discount_update import OrderDiscountUpdate
from .mutations.order_fulfill import OrderFulfill
+from .mutations.order_grant_refund_create import OrderGrantRefundCreate
+from .mutations.order_grant_refund_update import OrderGrantRefundUpdate
from .mutations.order_line_delete import OrderLineDelete
from .mutations.order_line_discount_remove import OrderLineDiscountRemove
from .mutations.order_line_discount_update import OrderLineDiscountUpdate
@@ -230,6 +232,9 @@ class OrderMutations(graphene.ObjectType):
order_fulfillment_refund_products = FulfillmentRefundProducts.Field()
order_fulfillment_return_products = FulfillmentReturnProducts.Field()
+ order_grant_refund_create = OrderGrantRefundCreate.Field()
+ order_grant_refund_update = OrderGrantRefundUpdate.Field()
+
order_lines_create = OrderLinesCreate.Field()
order_line_delete = OrderLineDelete.Field()
order_line_update = OrderLineUpdate.Field()
diff --git a/saleor/graphql/order/tests/benchmark/test_order.py b/saleor/graphql/order/tests/benchmark/test_order.py
index 7a232dec2a..df6088b936 100644
--- a/saleor/graphql/order/tests/benchmark/test_order.py
+++ b/saleor/graphql/order/tests/benchmark/test_order.py
@@ -92,6 +92,9 @@ FRAGMENT_ORDER_DETAILS = (
total {
...Price
}
+ totalCharged {
+ amount
+ }
totalCaptured {
amount
}
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
index 7e89d06b7f..3d89aafed3 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
@@ -5,15 +5,13 @@ import graphene
from prices import Money, TaxedMoney
from .....core.prices import quantize_price
-from .....order import FulfillmentLineData, OrderEvents
+from .....order import FulfillmentLineData
from .....order.error_codes import OrderErrorCode
from .....order.fetch import OrderLineInfo
from .....order.models import FulfillmentLine, FulfillmentStatus
-from .....payment import ChargeStatus, PaymentError, TransactionAction
-from .....payment.interface import RefundData, TransactionActionData
-from .....payment.models import TransactionItem
+from .....payment import ChargeStatus, PaymentError
+from .....payment.interface import RefundData
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 = """
@@ -47,102 +45,6 @@ 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
-
- charged_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,
- charged_value=charged_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
-
- charged_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,
- charged_value=charged_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/mutations/test_fulfillment_return_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
index 50f1478957..d7aa6f14ed 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
@@ -5,15 +5,13 @@ import graphene
from prices import Money, TaxedMoney
from .....core.prices import quantize_price
-from .....order import FulfillmentLineData, OrderEvents, OrderOrigin, OrderStatus
+from .....order import FulfillmentLineData, OrderOrigin, OrderStatus
from .....order.error_codes import OrderErrorCode
from .....order.fetch import OrderLineInfo
from .....order.models import FulfillmentStatus, Order
-from .....payment import ChargeStatus, PaymentError, TransactionAction
-from .....payment.interface import RefundData, TransactionActionData
-from .....payment.models import TransactionItem
+from .....payment import ChargeStatus, PaymentError
+from .....payment.interface import RefundData
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 = """
@@ -68,110 +66,6 @@ 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
-
- charged_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,
- charged_value=charged_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
-
- charged_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,
- charged_value=charged_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/mutations/test_order_capture.py b/saleor/graphql/order/tests/mutations/test_order_capture.py
index fc51b7ff7a..a859c143c6 100644
--- a/saleor/graphql/order/tests/mutations/test_order_capture.py
+++ b/saleor/graphql/order/tests/mutations/test_order_capture.py
@@ -1,18 +1,13 @@
-from decimal import Decimal
from unittest.mock import ANY, patch
import graphene
from .....core.notify_events import NotifyEventType
from .....core.tests.utils import get_site_context_payload
-from .....order import OrderEvents
from .....order import events as order_events
-from .....order.error_codes import OrderErrorCode
from .....order.notifications import get_default_order_payload
-from .....payment import ChargeStatus, TransactionAction
-from .....payment.interface import TransactionActionData
-from .....payment.models import Payment, TransactionItem
-from ....core.utils import to_global_id_or_none
+from .....payment import ChargeStatus
+from .....payment.models import Payment
from ....payment.types import PaymentChargeStatusEnum
from ....tests.utils import get_graphql_content
@@ -23,6 +18,9 @@ ORDER_CAPTURE_MUTATION = """
paymentStatus
paymentStatusDisplay
isPaid
+ totalCharged {
+ amount
+ }
totalCaptured {
amount
}
@@ -69,6 +67,7 @@ def test_order_capture(
assert data["paymentStatusDisplay"] == payment_status_display
assert data["isPaid"]
assert data["totalCaptured"]["amount"] == float(amount)
+ assert data["totalCharged"]["amount"] == float(amount)
event_captured, event_order_fully_paid = order.events.all()
@@ -106,94 +105,3 @@ def test_order_capture(
fulfill_non_shippable_gift_cards_mock.assert_called_once_with(
order, list(order.lines.all()), site_settings, staff_api_client.user, None, ANY
)
-
-
-@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
-@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
-def test_order_charge_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=["charge", "void"],
- currency="USD",
- order_id=order.pk,
- authorized_value=Decimal("10"),
- )
- charge_value = Decimal(5.0)
- mocked_is_active.return_value = True
- order_id = to_global_id_or_none(order)
-
- variables = {"id": order_id, "amount": charge_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.CHARGE,
- action_value=charge_value,
- ),
- channel_slug=order.channel.slug,
- )
-
- event = order.events.first()
- assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED
- assert Decimal(event.parameters["amount"]) == charge_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
diff --git a/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py
new file mode 100644
index 0000000000..ad57366e71
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_create.py
@@ -0,0 +1,191 @@
+from decimal import Decimal
+
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import OrderGrantRefundCreateErrorCode
+
+ORDER_GRANT_REFUND_CREATE = """
+mutation OrderGrantRefundCreate(
+ $id: ID!, $input: OrderGrantRefundCreateInput!
+){
+ orderGrantRefundCreate(id: $id, input:$input){
+ grantedRefund{
+ id
+ createdAt
+ updatedAt
+ amount{
+ amount
+ }
+ reason
+ user{
+ id
+ }
+ app{
+ id
+ }
+ }
+ order{
+ id
+ grantedRefunds{
+ id
+ amount{
+ amount
+ }
+ createdAt
+ updatedAt
+ reason
+ app{
+ id
+ }
+ user{
+ id
+ }
+ }
+ }
+ errors{
+ field
+ code
+ }
+ }
+}
+"""
+
+
+def test_grant_refund_by_user(staff_api_client, permission_manage_orders, order):
+ # given
+ order_id = to_global_id_or_none(order)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ amount = Decimal("10.00")
+ reason = "Granted refund reason."
+ variables = {
+ "id": order_id,
+ "input": {"amount": amount, "reason": reason},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # then
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert not errors
+
+ assert order_id == data["order"]["id"]
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund_from_db = order.granted_refunds.first()
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ assert (
+ granted_refund_assigned_to_order["amount"]["amount"]
+ == granted_refund_from_db.amount_value
+ == amount
+ )
+ assert (
+ granted_refund_assigned_to_order["reason"]
+ == reason
+ == granted_refund_from_db.reason
+ )
+ assert (
+ granted_refund_assigned_to_order["user"]["id"]
+ == to_global_id_or_none(staff_api_client.user)
+ == to_global_id_or_none(granted_refund_from_db.user)
+ )
+ assert not granted_refund_assigned_to_order["app"]
+
+
+def test_grant_refund_by_app(app_api_client, permission_manage_orders, order):
+ # given
+ order_id = to_global_id_or_none(order)
+ app_api_client.app.permissions.set([permission_manage_orders])
+ amount = Decimal("10.00")
+ reason = "Granted refund reason."
+ variables = {
+ "id": order_id,
+ "input": {"amount": amount, "reason": reason},
+ }
+
+ # when
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert not errors
+
+ assert order_id == data["order"]["id"]
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund_from_db = order.granted_refunds.first()
+ granted_refund = data["order"]["grantedRefunds"][0]
+ assert granted_refund == data["grantedRefund"]
+ assert (
+ granted_refund["amount"]["amount"]
+ == amount
+ == granted_refund_from_db.amount_value
+ )
+ assert granted_refund["reason"] == reason == granted_refund_from_db.reason
+ assert not granted_refund["user"]
+ assert (
+ granted_refund["app"]["id"]
+ == to_global_id_or_none(app_api_client.app)
+ == to_global_id_or_none(granted_refund_from_db.app)
+ )
+
+
+def test_grant_refund_by_app_missing_permission(app_api_client, order):
+ # given
+ order_id = to_global_id_or_none(order)
+ amount = Decimal("10.00")
+ reason = "Granted refund reason."
+ variables = {
+ "id": order_id,
+ "input": {"amount": amount, "reason": reason},
+ }
+
+ # when
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_grant_refund_by_user_missing_permission(staff_api_client, order):
+ # given
+ order_id = to_global_id_or_none(order)
+ amount = Decimal("10.00")
+ reason = "Granted refund reason."
+ variables = {
+ "id": order_id,
+ "input": {"amount": amount, "reason": reason},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_grant_refund_incorrect_order_id(staff_api_client, permission_manage_orders):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ amount = Decimal("10.00")
+ reason = "Granted refund reason."
+ variables = {
+ "id": "wrong-id",
+ "input": {"amount": amount, "reason": reason},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_CREATE, variables)
+
+ # then
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundCreate"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "id"
+ assert errors[0]["code"] == OrderGrantRefundCreateErrorCode.GRAPHQL_ERROR.name
diff --git a/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py
new file mode 100644
index 0000000000..68ce720208
--- /dev/null
+++ b/saleor/graphql/order/tests/mutations/test_order_grant_refund_update.py
@@ -0,0 +1,424 @@
+from decimal import Decimal
+
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
+from ...enums import OrderGrantRefundUpdateErrorCode
+
+ORDER_GRANT_REFUND_UPDATE = """
+mutation OrderGrantRefundUpdate(
+ $id: ID!, $input: OrderGrantRefundUpdateInput!
+){
+ orderGrantRefundUpdate(id: $id, input:$input) {
+ grantedRefund {
+ id
+ createdAt
+ updatedAt
+ amount {
+ amount
+ }
+ reason
+ user {
+ id
+ }
+ app {
+ id
+ }
+ }
+ order {
+ id
+ grantedRefunds{
+ id
+ amount{
+ amount
+ }
+ createdAt
+ updatedAt
+ reason
+ app{
+ id
+ }
+ user{
+ id
+ }
+ }
+ }
+ errors {
+ field
+ code
+ }
+ }
+}
+
+"""
+
+
+def test_grant_refund_update_by_user(
+ staff_api_client, app, permission_manage_orders, order
+):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+ updated_at = granted_refund.updated_at
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ amount = Decimal("20.00")
+ reason = "New reason"
+ variables = {
+ "id": granted_refund_id,
+ "input": {"amount": amount, "reason": reason},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ assert not data["errors"]
+
+ assert data["order"]["id"] == to_global_id_or_none(order)
+ assert len(data["order"]["grantedRefunds"]) == 1
+
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ assert updated_at.isoformat() != data["grantedRefund"]["updatedAt"]
+ granted_refund.refresh_from_db()
+ assert granted_refund.updated_at.isoformat() == data["grantedRefund"]["updatedAt"]
+ assert (
+ granted_refund_assigned_to_order["amount"]["amount"]
+ == granted_refund.amount_value
+ == amount
+ )
+ assert granted_refund_assigned_to_order["reason"] == reason == granted_refund.reason
+ assert granted_refund_assigned_to_order["app"]["id"] == to_global_id_or_none(
+ granted_refund.app
+ )
+
+
+def test_grant_refund_update_only_amount_by_user(
+ staff_api_client, app, permission_manage_orders, order
+):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ amount = Decimal("20.00")
+ variables = {
+ "id": granted_refund_id,
+ "input": {"amount": amount},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ assert not data["errors"]
+
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund.refresh_from_db()
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ assert (
+ granted_refund_assigned_to_order["amount"]["amount"]
+ == granted_refund.amount_value
+ == amount
+ )
+ assert granted_refund.reason == current_reason
+
+
+def test_grant_refund_update_only_reason_by_user(
+ staff_api_client, app, permission_manage_orders, order
+):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ reason = "new reason"
+ variables = {
+ "id": granted_refund_id,
+ "input": {"reason": reason},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ assert not data["errors"]
+
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund.refresh_from_db()
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ assert granted_refund_assigned_to_order["reason"] == reason == granted_refund.reason
+ assert granted_refund.amount_value == current_amount
+
+
+def test_grant_refund_update_by_user_missing_permission(staff_api_client, app, order):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ app=app,
+ )
+ amount = Decimal("10.00")
+ reason = "Granted refund reason."
+ variables = {
+ "id": to_global_id_or_none(granted_refund),
+ "input": {"amount": amount, "reason": reason},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_grant_refund_update_by_user_missing_input(
+ staff_api_client, staff_user, order, permission_manage_orders
+):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+
+ variables = {
+ "id": to_global_id_or_none(granted_refund),
+ "input": {},
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content_from_response(response)
+ errors = content["data"]["orderGrantRefundUpdate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderGrantRefundUpdateErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "input"
+
+
+def test_grant_refund_update_by_app(
+ app_api_client, staff_user, permission_manage_orders, order, permission_manage_users
+):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+ updated_at = granted_refund.updated_at
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ app_api_client.app.permissions.set(
+ [permission_manage_orders, permission_manage_users]
+ )
+ amount = Decimal("20.00")
+ reason = "New reason"
+ variables = {
+ "id": granted_refund_id,
+ "input": {"amount": amount, "reason": reason},
+ }
+
+ # when
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+
+ assert not data["errors"]
+
+ assert data["order"]["id"] == to_global_id_or_none(order)
+ assert len(data["order"]["grantedRefunds"]) == 1
+
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ assert updated_at.isoformat() != data["grantedRefund"]["updatedAt"]
+ granted_refund.refresh_from_db()
+ assert granted_refund.updated_at.isoformat() == data["grantedRefund"]["updatedAt"]
+ assert (
+ granted_refund_assigned_to_order["amount"]["amount"]
+ == granted_refund.amount_value
+ == amount
+ )
+ assert granted_refund_assigned_to_order["reason"] == reason == granted_refund.reason
+ assert granted_refund_assigned_to_order["user"]["id"] == to_global_id_or_none(
+ granted_refund.user
+ )
+
+
+def test_grant_refund_update_only_amount_by_app(
+ app_api_client, staff_user, permission_manage_orders, order
+):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ app_api_client.app.permissions.set([permission_manage_orders])
+ amount = Decimal("20.00")
+ variables = {
+ "id": granted_refund_id,
+ "input": {"amount": amount},
+ }
+
+ # when
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ assert not data["errors"]
+
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ granted_refund.refresh_from_db()
+ assert (
+ granted_refund_assigned_to_order["amount"]["amount"]
+ == granted_refund.amount_value
+ == amount
+ )
+ assert (
+ granted_refund_assigned_to_order["reason"]
+ == current_reason
+ == granted_refund.reason
+ )
+
+
+def test_grant_refund_update_only_reason_by_app(
+ app_api_client, staff_user, permission_manage_orders, order
+):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+ granted_refund_id = to_global_id_or_none(granted_refund)
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ reason = "new reason"
+ variables = {
+ "id": granted_refund_id,
+ "input": {"reason": reason},
+ }
+
+ # when
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderGrantRefundUpdate"]
+ assert not data["errors"]
+
+ assert len(data["order"]["grantedRefunds"]) == 1
+ granted_refund.refresh_from_db()
+ granted_refund_assigned_to_order = data["order"]["grantedRefunds"][0]
+ assert granted_refund_assigned_to_order == data["grantedRefund"]
+ assert granted_refund_assigned_to_order["reason"] == reason == granted_refund.reason
+ assert granted_refund.amount_value == current_amount
+
+
+def test_grant_refund_update_by_app_missing_permission(
+ app_api_client, staff_user, order
+):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+
+ amount = Decimal("10.00")
+ reason = "Granted refund reason."
+ variables = {
+ "id": to_global_id_or_none(granted_refund),
+ "input": {"amount": amount, "reason": reason},
+ }
+
+ # when
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_grant_refund_update_by_app_missing_input(
+ app_api_client, staff_user, order, permission_manage_orders
+):
+ # given
+ current_reason = "Granted refund reason."
+ current_amount = Decimal("10.00")
+ granted_refund = order.granted_refunds.create(
+ amount_value=current_amount,
+ currency=order.currency,
+ reason=current_reason,
+ user=staff_user,
+ )
+
+ variables = {
+ "id": to_global_id_or_none(granted_refund),
+ "input": {},
+ }
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDER_GRANT_REFUND_UPDATE, variables)
+
+ # then
+ content = get_graphql_content_from_response(response)
+ errors = content["data"]["orderGrantRefundUpdate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderGrantRefundUpdateErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "input"
diff --git a/saleor/graphql/order/tests/mutations/test_order_mark_as_paid.py b/saleor/graphql/order/tests/mutations/test_order_mark_as_paid.py
index ae7a771122..0747e37b52 100644
--- a/saleor/graphql/order/tests/mutations/test_order_mark_as_paid.py
+++ b/saleor/graphql/order/tests/mutations/test_order_mark_as_paid.py
@@ -1,9 +1,12 @@
import graphene
+import pytest
from prices import Money, TaxedMoney
+from .....channel import MarkAsPaidStrategy
from .....order import OrderStatus
from .....order import events as order_events
from .....order.error_codes import OrderErrorCode
+from .....payment import TransactionEventType
from ....tests.utils import get_graphql_content
MUTATION_MARK_ORDER_AS_PAID = """
@@ -29,7 +32,7 @@ MUTATION_MARK_ORDER_AS_PAID = """
"""
-def test_paid_order_mark_as_paid(
+def test_paid_order_mark_as_paid_with_payment(
staff_api_client, permission_manage_orders, payment_txn_preauth
):
order = payment_txn_preauth.order
@@ -49,7 +52,7 @@ def test_paid_order_mark_as_paid(
assert order_errors[0]["code"] == OrderErrorCode.PAYMENT_ERROR.name
-def test_order_mark_as_paid_with_external_reference(
+def test_order_mark_as_paid_with_external_reference_with_payment(
staff_api_client, permission_manage_orders, order_with_lines, staff_user
):
transaction_reference = "searchable-id"
@@ -78,17 +81,35 @@ def test_order_mark_as_paid_with_external_reference(
assert order_payments.count() == 1
-def test_order_mark_as_paid(
- staff_api_client, permission_manage_orders, order_with_lines, staff_user
+ "order_mark_as_paid_strategy",
+ [MarkAsPaidStrategy.TRANSACTION_FLOW, MarkAsPaidStrategy.PAYMENT_FLOW],
+)
+def test_order_mark_as_paid_with_payment(
+ order_mark_as_paid_strategy,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ staff_user,
):
+ # given
order = order_with_lines
+
+ channel = order.channel
+ channel.order_mark_as_paid_strategy = order_mark_as_paid_strategy
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
query = MUTATION_MARK_ORDER_AS_PAID
assert not order.is_fully_paid()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
+
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderMarkAsPaid"]["order"]
order.refresh_from_db()
@@ -99,25 +120,42 @@ def test_order_mark_as_paid(
assert event_order_paid.user == staff_user
-def test_order_mark_as_paid_no_billing_address(
- staff_api_client, permission_manage_orders, order_with_lines, staff_user
+ "order_mark_as_paid_strategy",
+ [MarkAsPaidStrategy.TRANSACTION_FLOW, MarkAsPaidStrategy.PAYMENT_FLOW],
+)
+def test_order_mark_as_paid_no_billing_address_with_payment(
+ order_mark_as_paid_strategy,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ staff_user,
):
+ # given
order = order_with_lines
order_with_lines.billing_address = None
order_with_lines.save()
+ channel = order.channel
+ channel.order_mark_as_paid_strategy = order_mark_as_paid_strategy
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
query = MUTATION_MARK_ORDER_AS_PAID
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
+
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderMarkAsPaid"]["errors"]
assert data[0]["code"] == OrderErrorCode.BILLING_ADDRESS_NOT_SET.name
-def test_draft_order_mark_as_paid_check_price_recalculation(
+def test_draft_order_mark_as_paid_check_price_recalculation_with_payment(
staff_api_client, permission_manage_orders, order_with_lines, staff_user
):
# given
@@ -151,3 +189,145 @@ def test_draft_order_mark_as_paid_check_price_recalculation(
event_order_paid = order.events.first()
assert event_order_paid.type == order_events.OrderEvents.ORDER_MARKED_AS_PAID
assert event_order_paid.user == staff_user
+
+
+def test_paid_order_mark_as_paid_with_transaction(
+ staff_api_client, permission_manage_orders, order_with_lines
+):
+ # given
+ order = order_with_lines
+ channel = order.channel
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
+ order.payment_transactions.create(charged_value=order.total.gross.amount)
+
+ query = MUTATION_MARK_ORDER_AS_PAID
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["orderMarkAsPaid"]["errors"]
+ msg = "Orders with transactions can not be manually marked as paid."
+ assert errors[0]["message"] == msg
+ assert errors[0]["field"] == "transaction"
+
+ order_errors = content["data"]["orderMarkAsPaid"]["errors"]
+ assert order_errors[0]["code"] == OrderErrorCode.TRANSACTION_ERROR.name
+
+
+def test_order_mark_as_paid_with_external_reference_with_transaction(
+ staff_api_client, permission_manage_orders, order_with_lines, staff_user
+):
+ # given
+ order = order_with_lines
+ channel = order.channel
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
+ transaction_reference = "searchable-id"
+ query = MUTATION_MARK_ORDER_AS_PAID
+ assert not order.is_fully_paid()
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id, "transaction": transaction_reference}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["orderMarkAsPaid"]["order"]
+ order.refresh_from_db()
+ assert data["isPaid"] is True
+ assert len(data["events"]) == 1
+ assert data["events"][0]["transactionReference"] == transaction_reference
+ assert order.is_fully_paid()
+ event_order_paid = order.events.first()
+ assert event_order_paid.type == order_events.OrderEvents.ORDER_MARKED_AS_PAID
+ assert event_order_paid.user == staff_user
+ event_reference = event_order_paid.parameters.get("transaction_reference")
+ assert event_reference == transaction_reference
+ transactions = order.payment_transactions.filter(
+ psp_reference=transaction_reference
+ )
+ assert transactions.count() == 1
+
+
+def test_order_mark_as_paid_with_transaction_creates_transaction_event(
+ staff_api_client, permission_manage_orders, order_with_lines, staff_user
+):
+ # given
+ order = order_with_lines
+ channel = order.channel
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
+ query = MUTATION_MARK_ORDER_AS_PAID
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ get_graphql_content(response)
+
+ order.refresh_from_db()
+ transaction = order.payment_transactions.get()
+ assert transaction.charged_value == order.total.gross.amount
+ transaction_event = transaction.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
+ assert transaction_event.amount_value == order.total.gross.amount
+
+
+def test_draft_order_mark_as_paid_check_price_recalculation_transaction(
+ staff_api_client, permission_manage_orders, order_with_lines, staff_user
+):
+ # given
+ order = order_with_lines
+ # we need to change order total and set it as invalidated prices.
+ # we couldn't use `order.total.gross` because this test don't use any tax app
+ # or plugin.
+ expected_total_net = order.total.net
+ expected_total = TaxedMoney(net=expected_total_net, gross=expected_total_net)
+ order.total = TaxedMoney(net=Money(0, "USD"), gross=Money(0, "USD"))
+ order.should_refresh_prices = True
+ order.status = OrderStatus.DRAFT
+ order.save()
+
+ channel = order.channel
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
+ query = MUTATION_MARK_ORDER_AS_PAID
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderMarkAsPaid"]["order"]
+ assert data["isPaid"] is True is order.is_fully_paid()
+ order.refresh_from_db()
+ assert order.total == expected_total
+ transaction = order.payment_transactions.get()
+ assert transaction.charged_value == expected_total_net.amount
+ event_order_paid = order.events.first()
+ assert event_order_paid.type == order_events.OrderEvents.ORDER_MARKED_AS_PAID
+ assert event_order_paid.user == staff_user
diff --git a/saleor/graphql/order/tests/mutations/test_order_refund.py b/saleor/graphql/order/tests/mutations/test_order_refund.py
index 0d58d80816..d214717651 100644
--- a/saleor/graphql/order/tests/mutations/test_order_refund.py
+++ b/saleor/graphql/order/tests/mutations/test_order_refund.py
@@ -1,15 +1,9 @@
-from decimal import Decimal
-from unittest.mock import patch
-
import graphene
-from .....order import FulfillmentStatus, OrderEvents
+from .....order import FulfillmentStatus
from .....order import events as order_events
from .....order.error_codes import OrderErrorCode
-from .....payment import ChargeStatus, TransactionAction
-from .....payment.interface import TransactionActionData
-from .....payment.models import TransactionItem
-from ....core.utils import to_global_id_or_none
+from .....payment import ChargeStatus
from ....payment.types import PaymentChargeStatusEnum
from ....tests.utils import get_graphql_content
@@ -79,90 +73,3 @@ def test_order_refund_with_gift_card_lines(
assert len(data["errors"]) == 1
assert data["errors"][0]["code"] == OrderErrorCode.CANNOT_REFUND.name
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
- authorized_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=authorized_value,
- )
- mocked_is_active.return_value = False
-
- order_id = to_global_id_or_none(order)
- variables = {"id": order_id, "amount": authorized_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
diff --git a/saleor/graphql/order/tests/mutations/test_order_void.py b/saleor/graphql/order/tests/mutations/test_order_void.py
index e3facb0eee..2a142dbce9 100644
--- a/saleor/graphql/order/tests/mutations/test_order_void.py
+++ b/saleor/graphql/order/tests/mutations/test_order_void.py
@@ -1,16 +1,11 @@
-from decimal import Decimal
from unittest.mock import patch
import graphene
-from .....order import OrderEvents
from .....order import events as order_events
from .....order.error_codes import OrderErrorCode
-from .....payment import ChargeStatus, TransactionAction
-from .....payment.interface import TransactionActionData
-from .....payment.models import TransactionItem
+from .....payment import ChargeStatus
from .....plugins.manager import PluginsManager
-from ....core.utils import to_global_id_or_none
from ....payment.types import PaymentChargeStatusEnum
from ....tests.utils import get_graphql_content
@@ -76,92 +71,3 @@ def test_order_void_payment_error(
assert order_errors[0]["code"] == OrderErrorCode.PAYMENT_ERROR.name
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
diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.py
index 2650976548..2baf7d2ffb 100644
--- a/saleor/graphql/order/tests/queries/test_order.py
+++ b/saleor/graphql/order/tests/queries/test_order.py
@@ -8,18 +8,22 @@ from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID
from .....core.prices import quantize_price
from .....core.taxes import zero_taxed_money
from .....order import OrderStatus
+from .....order.events import transaction_event
from .....order.models import Order
from .....order.utils import (
get_order_country,
update_order_authorize_data,
+ update_order_authorize_status,
update_order_charge_data,
+ update_order_charge_status,
)
-from .....payment import ChargeStatus, TransactionAction, TransactionStatus
+from .....payment import ChargeStatus, TransactionAction
from .....payment.models import TransactionEvent, TransactionItem
from .....shipping.models import ShippingMethod, ShippingMethodChannelListing
from .....warehouse.models import Warehouse
+from ....core.utils import to_global_id_or_none
from ....order.enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnum
-from ....payment.enums import TransactionStatusEnum
+from ....payment.enums import TransactionEventStatusEnum
from ....payment.types import PaymentChargeStatusEnum
from ....tests.utils import (
assert_graphql_error_with_message,
@@ -50,10 +54,18 @@ query OrdersQuery {
amount
currency
}
+ totalCharged{
+ amount
+ currency
+ }
totalCaptured{
amount
currency
}
+ totalCanceled{
+ amount
+ currency
+ }
totalBalance{
amount
currency
@@ -113,32 +125,11 @@ query OrdersQuery {
}
}
transactions{
- reference
- type
- status
- modifiedAt
- createdAt
- authorizedAmount{
- amount
- currency
- }
- voidedAmount{
- currency
- amount
- }
- chargedAmount{
- currency
- amount
- }
- refundedAmount{
- currency
- amount
- }
+ id
events{
status
- reference
+ pspReference
name
- createdAt
}
}
authorizeStatus
@@ -250,6 +241,24 @@ query OrdersQuery {
}
}
checkoutId
+ events {
+ id
+ date
+ type
+ user {
+ id
+ }
+ app {
+ id
+ }
+ message
+ email
+ reference
+ discount {
+ value
+ }
+ status
+ }
}
}
}
@@ -562,6 +571,7 @@ def test_order_query_authorize_status(
assert fulfilled_order.total.gross.amount == Decimal("98.40")
fulfilled_order.total_authorized_amount = total_authorized
fulfilled_order.total_charged_amount = total_charged
+ update_order_authorize_status(fulfilled_order, Decimal(0))
fulfilled_order.save()
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -600,6 +610,7 @@ def test_order_query_charge_status(
assert fulfilled_order.total.gross.amount == Decimal("98.40")
fulfilled_order.total_authorized_amount = total_authorized
fulfilled_order.total_charged_amount = total_charged
+ update_order_charge_status(fulfilled_order, Decimal(0))
fulfilled_order.save()
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -658,13 +669,21 @@ def test_order_query_with_transactions_details(
order.shipping_method.store_value_in_private_metadata({"test": private_value})
order.shipping_method.save()
order.save()
+ transaction_event(
+ order=order,
+ user=None,
+ app=None,
+ reference="ref-123",
+ status=None,
+ message="Message",
+ )
transactions = TransactionItem.objects.bulk_create(
[
TransactionItem(
order_id=order.id,
status="Authorized",
- type="Credit card",
- reference="123",
+ name="Credit card",
+ psp_reference="123",
currency="USD",
authorized_value=Decimal("15"),
available_actions=[TransactionAction.CHARGE, TransactionAction.VOID],
@@ -672,8 +691,8 @@ def test_order_query_with_transactions_details(
TransactionItem(
order_id=order.id,
status="Authorized second credit card",
- type="Credit card",
- reference="321",
+ name="Credit card",
+ psp_reference="321",
currency="USD",
authorized_value=Decimal("10"),
available_actions=[TransactionAction.CHARGE, TransactionAction.VOID],
@@ -681,25 +700,34 @@ def test_order_query_with_transactions_details(
TransactionItem(
order_id=order.id,
status="Captured",
- type="Credit card",
- reference="321",
+ name="Credit card",
+ psp_reference="111",
currency="USD",
charged_value=Decimal("15"),
available_actions=[TransactionAction.REFUND],
),
+ TransactionItem(
+ order_id=order.id,
+ status="Captured",
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ canceled_value=Decimal("19"),
+ available_actions=[],
+ ),
]
)
update_order_authorize_data(order)
update_order_charge_data(order)
- event_status = TransactionStatus.FAILURE
+ event_status = TransactionEventStatusEnum.FAILURE.value
event_reference = "PSP-ref"
event_name = "Failed authorization"
TransactionEvent.objects.bulk_create(
[
TransactionEvent(
- name=event_name,
+ message=event_name,
status=event_status,
- reference=event_reference,
+ psp_reference=f"{event_reference}{to_global_id_or_none(transaction)}",
transaction=transaction,
currency=transaction.currency,
)
@@ -728,6 +756,8 @@ def test_order_query_with_transactions_details(
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(order_data["totalCharged"]["amount"]) == Decimal("15")
+ assert Decimal(order_data["totalCanceled"]["amount"]) == Decimal("19")
assert Decimal(str(order_data["totalBalance"]["amount"])) == Decimal("-83.4")
@@ -735,8 +765,8 @@ def test_order_query_with_transactions_details(
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
+ assert event["status"] == TransactionEventStatusEnum.FAILURE.name
+ assert event["pspReference"] == f"{event_reference}{transaction.get('id')}"
def test_order_query_shipping_method_channel_listing_does_not_exist(
diff --git a/saleor/graphql/order/tests/queries/test_order_amounts.py b/saleor/graphql/order/tests/queries/test_order_amounts.py
new file mode 100644
index 0000000000..53b0c06959
--- /dev/null
+++ b/saleor/graphql/order/tests/queries/test_order_amounts.py
@@ -0,0 +1,950 @@
+from decimal import Decimal
+
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+ORDERS_QUERY_WITH_AMOUNT_FIELDS = """
+query OrdersQuery {
+ orders(first: 1) {
+ edges {
+ node {
+ totalAuthorized{
+ amount
+ currency
+ }
+ totalCanceled{
+ amount
+ currency
+ }
+ totalCharged{
+ amount
+ currency
+ }
+ totalCaptured{
+ amount
+ currency
+ }
+ totalBalance{
+ amount
+ currency
+ }
+ shippingPrice {
+ gross {
+ amount
+ }
+ }
+ totalRefunded{
+ currency
+ amount
+ }
+ totalRemainingGrant{
+ currency
+ amount
+ }
+ totalGrantedRefund{
+ currency
+ amount
+ }
+ totalRefundPending{
+ currency
+ amount
+ }
+ totalAuthorizePending{
+ currency
+ amount
+ }
+ totalChargePending{
+ currency
+ amount
+ }
+ totalCancelPending{
+ currency
+ amount
+ }
+ transactions{
+ reference
+ pspReference
+ type
+ status
+ modifiedAt
+ createdAt
+ authorizedAmount{
+ amount
+ currency
+ }
+ voidedAmount{
+ currency
+ amount
+ }
+ chargedAmount{
+ currency
+ amount
+ }
+ refundedAmount{
+ currency
+ amount
+ }
+ events{
+ status
+ pspReference
+ reference
+ name
+ createdAt
+ }
+ }
+ subtotal {
+ net {
+ amount
+ }
+ }
+ total {
+ net {
+ amount
+ }
+ }
+ }
+ }
+ }
+}
+ """
+
+
+def test_order_total_refunded_query_with_transactions_by_staff_user(
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_refund_amount = Decimal("10.00")
+ second_refund_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ refunded_value=first_refund_amount,
+ currency=order.currency,
+ )
+ order.payment_transactions.create(
+ refunded_value=second_refund_amount,
+ currency=order.currency,
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_granted_refund = order_data["totalRefunded"]
+ assert total_granted_refund["amount"] == first_refund_amount + second_refund_amount
+
+
+def test_order_total_refunded_query_by_user(
+ user_api_client,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_refund_amount = Decimal("10.00")
+ second_refund_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ refunded_value=first_refund_amount,
+ currency=order.currency,
+ )
+ order.payment_transactions.create(
+ refunded_value=second_refund_amount,
+ currency=order.currency,
+ )
+ query = """
+ query Order($id: ID!) {
+ order(id: $id) {
+ totalRefunded {
+ currency
+ amount
+ }
+ }
+ }
+ """
+
+ # when
+ response = user_api_client.post_graphql(
+ query, variables={"id": to_global_id_or_none(order)}
+ )
+
+ # then
+ content = get_graphql_content(response)
+ order_data = content["data"]["order"]
+ total_granted_refund = order_data["totalRefunded"]
+ assert total_granted_refund["amount"] == first_refund_amount + second_refund_amount
+
+
+def test_order_total_refunded_query_with_transactions_by_app(
+ app_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_refund_amount = Decimal("10.00")
+ second_refund_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ refunded_value=first_refund_amount,
+ currency=order.currency,
+ )
+ order.payment_transactions.create(
+ refunded_value=second_refund_amount,
+ currency=order.currency,
+ )
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_granted_refund = order_data["totalRefunded"]
+ assert total_granted_refund["amount"] == first_refund_amount + second_refund_amount
+
+
+def test_order_total_refunded_query_with_payment_by_staff_user(
+ staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+ first_refund_amount = Decimal("5.00")
+ second_refund_amount = Decimal("12.50")
+ refund_transaction = payment.transactions.first()
+ refund_transaction.amount = first_refund_amount
+ refund_transaction.save()
+ refund_transaction.pk = None
+ refund_transaction.amount = second_refund_amount
+ refund_transaction.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_refunded = order_data["totalRefunded"]
+ assert total_refunded["amount"] == first_refund_amount + second_refund_amount
+
+
+def test_order_total_refunded_query_with_payment_by_app(
+ app_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+ first_refund_amount = Decimal("5.00")
+ second_refund_amount = Decimal("12.50")
+ refund_transaction = payment.transactions.first()
+ refund_transaction.amount = first_refund_amount
+ refund_transaction.save()
+ refund_transaction.pk = None
+ refund_transaction.amount = second_refund_amount
+ refund_transaction.save()
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_refunded = order_data["totalRefunded"]
+ assert total_refunded["amount"] == first_refund_amount + second_refund_amount
+
+
+def test_order_total_refund_pending_query_with_transactions_by_staff_user(
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_pending_refund_amount = Decimal("10.00")
+ second_pending_refund_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ refund_pending_value=first_pending_refund_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(
+ refund_pending_value=second_pending_refund_amount, currency="USD"
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalRefundPending"]
+ assert (
+ total_pending["amount"]
+ == first_pending_refund_amount + second_pending_refund_amount
+ )
+
+
+def test_order_total_refund_pending_query_by_user(
+ user_api_client,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ query = """
+ query Order($id: ID!) {
+ order(id: $id) {
+ totalRefundPending {
+ currency
+ amount
+ }
+ }
+ }
+ """
+ # when
+ response = user_api_client.post_graphql(
+ query, variables={"id": to_global_id_or_none(order)}
+ )
+ # then
+ assert_no_permission(response)
+
+
+def test_order_total_refund_pending_query_with_transactions_by_app(
+ app_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_pending_refund_amount = Decimal("10.00")
+ second_pending_refund_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ refund_pending_value=first_pending_refund_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(
+ refund_pending_value=second_pending_refund_amount, currency="USD"
+ )
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalRefundPending"]
+ assert (
+ total_pending["amount"]
+ == first_pending_refund_amount + second_pending_refund_amount
+ )
+
+
+def test_order_total_refund_pending_query_with_payment_by_staff_user(
+ staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalRefundPending"]
+ assert total_pending["amount"] == Decimal(0)
+
+
+def test_order_total_refund_pending_query_with_payment_by_app(
+ app_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+
+ app_api_client.app.permissions.add(permission_manage_orders)
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalRefundPending"]
+ assert total_pending["amount"] == Decimal(0)
+
+
+def test_order_total_authorize_pending_query_with_transactions_by_staff_user(
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_pending_authorize_amount = Decimal("10.00")
+ second_pending_authorize_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ authorize_pending_value=first_pending_authorize_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(
+ authorize_pending_value=second_pending_authorize_amount, currency="USD"
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalAuthorizePending"]
+ assert (
+ total_pending["amount"]
+ == first_pending_authorize_amount + second_pending_authorize_amount
+ )
+
+
+def test_order_total_authorize_pending_query_by_user(
+ user_api_client,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ query = """
+ query Order($id: ID!) {
+ order(id: $id) {
+ totalAuthorizePending {
+ currency
+ amount
+ }
+ }
+ }
+ """
+ # when
+ response = user_api_client.post_graphql(
+ query, variables={"id": to_global_id_or_none(order)}
+ )
+ # then
+ assert_no_permission(response)
+
+
+def test_order_total_authorize_pending_query_with_transactions_by_app(
+ app_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_pending_authorize_amount = Decimal("10.00")
+ second_pending_authorize_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ authorize_pending_value=first_pending_authorize_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(
+ authorize_pending_value=second_pending_authorize_amount, currency="USD"
+ )
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalAuthorizePending"]
+ assert (
+ total_pending["amount"]
+ == first_pending_authorize_amount + second_pending_authorize_amount
+ )
+
+
+def test_order_total_authorize_pending_query_with_payment_by_staff_user(
+ staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalAuthorizePending"]
+ assert total_pending["amount"] == Decimal(0)
+
+
+def test_order_total_authorize_pending_query_with_payment_by_app(
+ app_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+
+ app_api_client.app.permissions.add(permission_manage_orders)
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalAuthorizePending"]
+ assert total_pending["amount"] == Decimal(0)
+
+
+def test_order_total_charge_pending_query_with_transactions_by_staff_user(
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_pending_charge_amount = Decimal("10.00")
+ second_pending_charge_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ charge_pending_value=first_pending_charge_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(
+ charge_pending_value=second_pending_charge_amount, currency="USD"
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalChargePending"]
+ assert (
+ total_pending["amount"]
+ == first_pending_charge_amount + second_pending_charge_amount
+ )
+
+
+def test_order_total_charge_pending_query_by_user(
+ user_api_client,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ query = """
+ query Order($id: ID!) {
+ order(id: $id) {
+ totalChargePending {
+ currency
+ amount
+ }
+ }
+ }
+ """
+ # when
+ response = user_api_client.post_graphql(
+ query, variables={"id": to_global_id_or_none(order)}
+ )
+ # then
+ assert_no_permission(response)
+
+
+def test_order_total_charge_pending_query_with_transactions_by_app(
+ app_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_pending_charge_amount = Decimal("10.00")
+ second_pending_charge_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ charge_pending_value=first_pending_charge_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(
+ charge_pending_value=second_pending_charge_amount, currency="USD"
+ )
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalChargePending"]
+ assert (
+ total_pending["amount"]
+ == first_pending_charge_amount + second_pending_charge_amount
+ )
+
+
+def test_order_total_charge_pending_query_with_payment_by_staff_user(
+ staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalChargePending"]
+ assert total_pending["amount"] == Decimal(0)
+
+
+def test_order_total_charge_pending_query_with_payment_by_app(
+ app_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+
+ app_api_client.app.permissions.add(permission_manage_orders)
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalChargePending"]
+ assert total_pending["amount"] == Decimal(0)
+
+
+def test_order_total_cancel_pending_query_with_transactions_by_staff_user(
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_pending_cancel_amount = Decimal("10.00")
+ second_pending_cancel_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ cancel_pending_value=first_pending_cancel_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(
+ cancel_pending_value=second_pending_cancel_amount, currency="USD"
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalCancelPending"]
+ assert (
+ total_pending["amount"]
+ == first_pending_cancel_amount + second_pending_cancel_amount
+ )
+
+
+def test_order_total_cancel_pending_query_by_user(
+ user_api_client,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ query = """
+ query Order($id: ID!) {
+ order(id: $id) {
+ totalCancelPending {
+ currency
+ amount
+ }
+ }
+ }
+ """
+ # when
+ response = user_api_client.post_graphql(
+ query, variables={"id": to_global_id_or_none(order)}
+ )
+ # then
+ assert_no_permission(response)
+
+
+def test_order_total_cancel_pending_query_with_transactions_by_app(
+ app_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ first_pending_cancel_amount = Decimal("10.00")
+ second_pending_cancel_amount = Decimal("12.50")
+ order.payment_transactions.create(
+ cancel_pending_value=first_pending_cancel_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(
+ cancel_pending_value=second_pending_cancel_amount, currency="USD"
+ )
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalCancelPending"]
+ assert (
+ total_pending["amount"]
+ == first_pending_cancel_amount + second_pending_cancel_amount
+ )
+
+
+def test_order_total_cancel_pending_query_with_payment_by_staff_user(
+ staff_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalCancelPending"]
+ assert total_pending["amount"] == Decimal(0)
+
+
+def test_order_total_cancel_pending_query_with_payment_by_app(
+ app_api_client, permission_manage_orders, order_with_lines, payment_txn_refunded
+):
+ # given
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+
+ app_api_client.app.permissions.add(permission_manage_orders)
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_pending = order_data["totalCancelPending"]
+ assert total_pending["amount"] == Decimal(0)
+
+
+def test_order_total_remaining_grant_query_with_transactions_by_staff_user(
+ staff_api_client, permission_manage_orders, fulfilled_order, staff_user
+):
+ # given
+ order = fulfilled_order
+ granted_refund_amount = Decimal("20.00")
+ pending_refund_amount = Decimal("10.00")
+ refund_amount = Decimal("12.50")
+ order.granted_refunds.create(
+ amount_value=granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+ order.payment_transactions.create(
+ refund_pending_value=pending_refund_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(refunded_value=refund_amount, currency="USD")
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_remaining_grant = order_data["totalRemainingGrant"]
+ assert total_remaining_grant["amount"] == granted_refund_amount - (
+ pending_refund_amount + refund_amount
+ )
+
+
+def test_order_total_remaining_grant_query_by_user(
+ user_api_client,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ query = """
+ query Order($id: ID!) {
+ order(id: $id) {
+ totalRemainingGrant {
+ currency
+ amount
+ }
+ }
+ }
+ """
+ # when
+ response = user_api_client.post_graphql(
+ query, variables={"id": to_global_id_or_none(order)}
+ )
+ # then
+ assert_no_permission(response)
+
+
+def test_order_total_remaining_grant_query_with_transactions_by_app(
+ app_api_client, permission_manage_orders, fulfilled_order, staff_user
+):
+ # given
+ order = fulfilled_order
+ granted_refund_amount = Decimal("20.00")
+ pending_refund_amount = Decimal("10.00")
+ refund_amount = Decimal("12.50")
+ order.granted_refunds.create(
+ amount_value=granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+ order.payment_transactions.create(
+ refund_pending_value=pending_refund_amount,
+ currency="USD",
+ )
+ order.payment_transactions.create(refunded_value=refund_amount, currency="USD")
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_remaining_grant = order_data["totalRemainingGrant"]
+ assert total_remaining_grant["amount"] == granted_refund_amount - (
+ pending_refund_amount + refund_amount
+ )
+
+
+def test_order_total_remaining_grant_query_with_payment_by_staff_user(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ payment_txn_refunded,
+ staff_user,
+):
+ # given
+ granted_refund_amount = Decimal("20.00")
+ order_with_lines.granted_refunds.create(
+ amount_value=granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+ first_refund_amount = Decimal("5.00")
+ second_refund_amount = Decimal("12.50")
+ refund_transaction = payment.transactions.first()
+ refund_transaction.amount = first_refund_amount
+ refund_transaction.save()
+ refund_transaction.pk = None
+ refund_transaction.amount = second_refund_amount
+ refund_transaction.save()
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_remaining_grant = order_data["totalRemainingGrant"]
+ assert total_remaining_grant["amount"] == granted_refund_amount - (
+ first_refund_amount + second_refund_amount
+ )
+
+
+def test_order_total_remaining_grant_query_with_payment_by_app(
+ app_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ payment_txn_refunded,
+ staff_user,
+):
+ # given
+ granted_refund_amount = Decimal("20.00")
+ order_with_lines.granted_refunds.create(
+ amount_value=granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+ payment = payment_txn_refunded
+ payment.is_active = True
+ payment.save()
+ first_refund_amount = Decimal("5.00")
+ second_refund_amount = Decimal("12.50")
+ refund_transaction = payment.transactions.first()
+ refund_transaction.amount = first_refund_amount
+ refund_transaction.save()
+ refund_transaction.pk = None
+ refund_transaction.amount = second_refund_amount
+ refund_transaction.save()
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY_WITH_AMOUNT_FIELDS)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_remaining_grant = order_data["totalRemainingGrant"]
+ assert total_remaining_grant["amount"] == granted_refund_amount - (
+ first_refund_amount + second_refund_amount
+ )
diff --git a/saleor/graphql/order/tests/queries/test_order_granted_refunds.py b/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
new file mode 100644
index 0000000000..3d15bdf1b2
--- /dev/null
+++ b/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
@@ -0,0 +1,323 @@
+from decimal import Decimal
+
+from prices import Money, TaxedMoney
+
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+ORDERS_QUERY = """
+query OrdersQuery {
+ orders(first: 1) {
+ edges {
+ node {
+ number
+ totalGrantedRefund {
+ currency
+ amount
+ }
+ grantedRefunds{
+ id
+ createdAt
+ updatedAt
+ amount{
+ amount
+ currency
+ }
+ reason
+ user{
+ id
+ }
+ app{
+ id
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_order_granted_refunds_query_by_user(
+ staff_user,
+ app,
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+ shipping_zone,
+):
+ # given
+ order = fulfilled_order
+ net = Money(amount=Decimal("10"), 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
+ order.save()
+ first_granted_refund = order.granted_refunds.create(
+ amount_value=Decimal("10.0"),
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+ second_granted_refund = order.granted_refunds.create(
+ amount_value=Decimal("12.5"), currency="USD", reason="Test reason", app=app
+ )
+
+ 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"]
+ granted_refunds = order_data["grantedRefunds"]
+ assert len(granted_refunds) == 2
+ assert granted_refunds == [
+ {
+ "id": to_global_id_or_none(first_granted_refund),
+ "createdAt": first_granted_refund.created_at.isoformat(),
+ "updatedAt": first_granted_refund.updated_at.isoformat(),
+ "amount": {
+ "amount": float(first_granted_refund.amount.amount),
+ "currency": first_granted_refund.currency,
+ },
+ "reason": first_granted_refund.reason,
+ "user": {"id": to_global_id_or_none(first_granted_refund.user)},
+ "app": None,
+ },
+ {
+ "id": to_global_id_or_none(second_granted_refund),
+ "createdAt": second_granted_refund.created_at.isoformat(),
+ "updatedAt": second_granted_refund.updated_at.isoformat(),
+ "amount": {
+ "amount": float(second_granted_refund.amount.amount),
+ "currency": second_granted_refund.currency,
+ },
+ "reason": second_granted_refund.reason,
+ "app": {"id": to_global_id_or_none(second_granted_refund.app)},
+ "user": None,
+ },
+ ]
+
+
+def test_order_granted_refunds_query_by_app(
+ staff_user,
+ app,
+ app_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ permission_manage_users,
+ fulfilled_order,
+ shipping_zone,
+):
+ # given
+ order = fulfilled_order
+ net = Money(amount=Decimal("10"), 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
+ order.save()
+ first_granted_refund = order.granted_refunds.create(
+ amount_value=Decimal("10.0"),
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+ second_granted_refund = order.granted_refunds.create(
+ amount_value=Decimal("12.5"), currency="USD", reason="Test reason", app=app
+ )
+
+ app_api_client.app.permissions.set(
+ [permission_manage_orders, permission_manage_shipping, permission_manage_users]
+ )
+
+ query = """
+ query OrdersQuery {
+ orders(first: 1) {
+ edges {
+ node {
+ number
+ grantedRefunds{
+ id
+ createdAt
+ updatedAt
+ amount{
+ amount
+ currency
+ }
+ reason
+ user{
+ id
+ }
+ app{
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ # when
+ response = app_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ granted_refunds = order_data["grantedRefunds"]
+ assert len(granted_refunds) == 2
+ assert granted_refunds == [
+ {
+ "id": to_global_id_or_none(first_granted_refund),
+ "createdAt": first_granted_refund.created_at.isoformat(),
+ "updatedAt": first_granted_refund.updated_at.isoformat(),
+ "amount": {
+ "amount": float(first_granted_refund.amount.amount),
+ "currency": first_granted_refund.currency,
+ },
+ "reason": first_granted_refund.reason,
+ "user": {"id": to_global_id_or_none(first_granted_refund.user)},
+ "app": None,
+ },
+ {
+ "id": to_global_id_or_none(second_granted_refund),
+ "createdAt": second_granted_refund.created_at.isoformat(),
+ "updatedAt": second_granted_refund.updated_at.isoformat(),
+ "amount": {
+ "amount": float(second_granted_refund.amount.amount),
+ "currency": second_granted_refund.currency,
+ },
+ "reason": second_granted_refund.reason,
+ "app": {"id": to_global_id_or_none(second_granted_refund.app)},
+ "user": None,
+ },
+ ]
+
+
+def test_order_total_granted_refund_query_by_staff_user(
+ staff_user,
+ app,
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ shipping_zone,
+):
+ # given
+ order = fulfilled_order
+ first_granted_refund_amount = Decimal("10.00")
+ second_granted_refund_amount = Decimal("12.50")
+ order.granted_refunds.create(
+ amount_value=first_granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+ order.granted_refunds.create(
+ amount_value=second_granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ app=app,
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_granted_refund = order_data["totalGrantedRefund"]
+ assert (
+ total_granted_refund["amount"]
+ == first_granted_refund_amount + second_granted_refund_amount
+ )
+
+
+def test_order_total_granted_refund_query_by_user(
+ user_api_client,
+ staff_user,
+ app,
+ fulfilled_order,
+ shipping_zone,
+):
+ # given
+ order = fulfilled_order
+ first_granted_refund_amount = Decimal("10.00")
+ second_granted_refund_amount = Decimal("12.50")
+ order.granted_refunds.create(
+ amount_value=first_granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+ order.granted_refunds.create(
+ amount_value=second_granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ app=app,
+ )
+ query = """
+ query Order($id: ID!) {
+ order(id: $id) {
+ totalGrantedRefund {
+ currency
+ amount
+ }
+ }
+ }
+ """
+ # when
+ response = user_api_client.post_graphql(
+ query, variables={"id": to_global_id_or_none(order)}
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_order_total_granted_refund_query_by_app(
+ staff_user,
+ app,
+ app_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ shipping_zone,
+):
+ # given
+ order = fulfilled_order
+ first_granted_refund_amount = Decimal("10.00")
+ second_granted_refund_amount = Decimal("12.50")
+ order.granted_refunds.create(
+ amount_value=first_granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ user=staff_user,
+ )
+ order.granted_refunds.create(
+ amount_value=second_granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ app=app,
+ )
+
+ app_api_client.app.permissions.set([permission_manage_orders])
+
+ # when
+ response = app_api_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ total_granted_refund = order_data["totalGrantedRefund"]
+ assert (
+ total_granted_refund["amount"]
+ == first_granted_refund_amount + second_granted_refund_amount
+ )
diff --git a/saleor/graphql/order/tests/queries/test_order_total_balance.py b/saleor/graphql/order/tests/queries/test_order_total_balance.py
new file mode 100644
index 0000000000..e9a76846d2
--- /dev/null
+++ b/saleor/graphql/order/tests/queries/test_order_total_balance.py
@@ -0,0 +1,349 @@
+from decimal import Decimal
+
+from .....core.prices import quantize_price
+from .....order.models import OrderGrantedRefund
+from .....payment.models import TransactionItem
+from ....tests.utils import get_graphql_content
+
+ORDERS_QUERY = """
+query OrdersQuery {
+ orders(first: 1) {
+ edges {
+ node {
+ totalBalance{
+ amount
+ currency
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_total_balance_only_charged(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ transactions = TransactionItem.objects.bulk_create(
+ [
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ charged_value=Decimal("15"),
+ ),
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ charged_value=Decimal("19"),
+ available_actions=[],
+ ),
+ ]
+ )
+
+ 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"]
+ total_charged = sum([t.charged_value for t in transactions], Decimal(0))
+ total_balance = quantize_price(
+ total_charged - order.total.gross.amount, order.currency
+ )
+ assert (
+ quantize_price(Decimal(order_data["totalBalance"]["amount"]), order.currency)
+ == total_balance
+ )
+
+
+def test_total_balance_charged_and_pending_charged(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ transactions = TransactionItem.objects.bulk_create(
+ [
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ charged_value=Decimal("15"),
+ ),
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ charge_pending_value=Decimal("19"),
+ available_actions=[],
+ ),
+ ]
+ )
+
+ 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"]
+ total_charged = sum([t.charged_value for t in transactions], Decimal(0))
+ total_charged += sum([t.charge_pending_value for t in transactions], Decimal(0))
+ total_balance = quantize_price(
+ total_charged - order.total.gross.amount, order.currency
+ )
+ assert (
+ quantize_price(Decimal(order_data["totalBalance"]["amount"]), order.currency)
+ == total_balance
+ )
+
+
+def test_total_balance_only_refunded(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ TransactionItem.objects.bulk_create(
+ [
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ refunded_value=Decimal("15"),
+ ),
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ refunded_value=Decimal("19"),
+ available_actions=[],
+ ),
+ ]
+ )
+
+ 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"]
+ total_balance = quantize_price(-order.total.gross.amount, order.currency)
+ assert (
+ quantize_price(Decimal(order_data["totalBalance"]["amount"]), order.currency)
+ == total_balance
+ )
+
+
+def test_total_balance_refunded_and_pending_refund(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ TransactionItem.objects.bulk_create(
+ [
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ refunded_value=Decimal("15"),
+ ),
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ refund_pending_value=Decimal("19"),
+ available_actions=[],
+ ),
+ ]
+ )
+
+ 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"]
+ total_balance = quantize_price(-order.total.gross.amount, order.currency)
+ assert (
+ quantize_price(Decimal(order_data["totalBalance"]["amount"]), order.currency)
+ == total_balance
+ )
+
+
+def test_total_balance_refunded_and_charged(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ transactions = TransactionItem.objects.bulk_create(
+ [
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ refunded_value=Decimal("15"),
+ ),
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ charged_value=Decimal("19"),
+ available_actions=[],
+ ),
+ ]
+ )
+
+ 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"]
+ total_charged = sum([t.charged_value for t in transactions], Decimal(0))
+ total_balance = quantize_price(
+ total_charged - order.total.gross.amount, order.currency
+ )
+ assert (
+ quantize_price(Decimal(order_data["totalBalance"]["amount"]), order.currency)
+ == total_balance
+ )
+
+
+def test_total_balance_with_granted_refund(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ granted_refund = OrderGrantedRefund.objects.create(
+ amount_value=Decimal("10.15"), currency=order.currency, order_id=order.pk
+ )
+
+ 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"]
+ total_balance = quantize_price(
+ -(order.total.gross.amount - granted_refund.amount_value), order.currency
+ )
+ assert (
+ quantize_price(Decimal(order_data["totalBalance"]["amount"]), order.currency)
+ == total_balance
+ )
+
+
+def test_total_balance_with_granted_refund_and_transactions(
+ staff_api_client,
+ permission_manage_orders,
+ permission_manage_shipping,
+ fulfilled_order,
+):
+ # given
+ order = fulfilled_order
+ granted_refund = OrderGrantedRefund.objects.create(
+ amount_value=Decimal("10.15"), currency=order.currency, order_id=order.pk
+ )
+ transactions = TransactionItem.objects.bulk_create(
+ [
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ refunded_value=Decimal("15"),
+ ),
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ refund_pending_value=Decimal("19"),
+ available_actions=[],
+ ),
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ charged_value=Decimal("11"),
+ available_actions=[],
+ ),
+ TransactionItem(
+ order_id=order.id,
+ name="Credit card",
+ psp_reference="111",
+ currency="USD",
+ charge_pending_value=Decimal("12"),
+ available_actions=[],
+ ),
+ ]
+ )
+
+ 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"]
+ total_charged = sum([t.charged_value for t in transactions], Decimal(0))
+ total_charged += sum([t.charge_pending_value for t in transactions], Decimal(0))
+ total_balance = quantize_price(
+ total_charged - (order.total.gross.amount - granted_refund.amount_value),
+ order.currency,
+ )
+ assert (
+ quantize_price(Decimal(order_data["totalBalance"]["amount"]), order.currency)
+ == total_balance
+ )
diff --git a/saleor/graphql/order/tests/queries/test_order_with_filter.py b/saleor/graphql/order/tests/queries/test_order_with_filter.py
index 5a6bd44e6b..d6d66632e2 100644
--- a/saleor/graphql/order/tests/queries/test_order_with_filter.py
+++ b/saleor/graphql/order/tests/queries/test_order_with_filter.py
@@ -1067,9 +1067,9 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
1,
),
(
- {"authorized_value": Decimal("00")},
- [OrderAuthorizeStatusEnum.PARTIAL.name],
- 0,
+ {"authorized_value": Decimal("0")},
+ [OrderAuthorizeStatusEnum.NONE.name],
+ 1,
),
(
{"authorized_value": Decimal("100")},
@@ -1087,9 +1087,9 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
2,
),
(
- {"authorized_value": Decimal("10"), "charged_value": Decimal("90")},
- [OrderAuthorizeStatusEnum.FULL.name],
- 2,
+ {"authorized_value": Decimal("10"), "charged_value": Decimal("80")},
+ [OrderAuthorizeStatusEnum.PARTIAL.name],
+ 1,
),
],
)
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index beb71dc7cb..e701413eaa 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -10,9 +10,11 @@ from graphene import relay
from promise import Promise
from ...account.models import Address
+from ...account.models import User as UserModel
from ...checkout.utils import get_external_shipping_id
from ...core.anonymize import obfuscate_address, obfuscate_email
from ...core.prices import quantize_price
+from ...core.taxes import zero_money
from ...discount import OrderDiscountType
from ...graphql.checkout.types import DeliveryMethod
from ...graphql.core.federation.entities import federated_entity
@@ -27,7 +29,7 @@ from ...order.utils import (
get_valid_collection_points_for_order,
get_valid_shipping_methods_for_order,
)
-from ...payment import ChargeStatus
+from ...payment import ChargeStatus, TransactionKind
from ...payment.dataloaders import PaymentsByOrderIdLoader
from ...payment.model_helpers import get_last_payment, get_total_authorized
from ...permission.auth_filters import AuthorizationFilters
@@ -71,8 +73,10 @@ from ..core.descriptions import (
ADDED_IN_39,
ADDED_IN_310,
ADDED_IN_311,
+ ADDED_IN_313,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
+ PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD,
)
from ..core.enums import LanguageCodeEnum
from ..core.fields import PermissionsField
@@ -100,7 +104,8 @@ from ..invoice.dataloaders import InvoicesByOrderIdLoader
from ..invoice.types import Invoice
from ..meta.resolvers import check_private_metadata_privilege, resolve_metadata
from ..meta.types import MetadataItem, ObjectWithMetadata
-from ..payment.enums import OrderAction, TransactionStatusEnum
+from ..payment.dataloaders import TransactionByPaymentIdLoader
+from ..payment.enums import OrderAction, TransactionEventStatusEnum
from ..payment.types import Payment, PaymentChargeStatusEnum, TransactionItem
from ..plugins.dataloaders import (
get_plugin_manager_promise,
@@ -136,6 +141,7 @@ from .dataloaders import (
OrderByIdLoader,
OrderByNumberLoader,
OrderEventsByOrderIdLoader,
+ OrderGrantedRefundsByOrderIdLoader,
OrderLineByIdLoader,
OrderLinesByOrderIdLoader,
TransactionItemsByOrderIDLoader,
@@ -186,6 +192,53 @@ def get_payment_status_for_order(order):
return status
+class OrderGrantedRefund(ModelObjectType):
+ id = graphene.GlobalID(required=True)
+ created_at = graphene.DateTime(required=True, description="Time of creation.")
+ updated_at = graphene.DateTime(required=True, description="Time of last update.")
+ amount = graphene.Field(Money, required=True, description="Refund amount.")
+ reason = graphene.String(description="Reason of the refund.")
+ user = graphene.Field(
+ User,
+ description=(
+ "User who performed the action. Requires of of the following "
+ f"permissions: {AccountPermissions.MANAGE_USERS.name}, "
+ f"{AccountPermissions.MANAGE_STAFF.name}, "
+ f"{AuthorizationFilters.OWNER.name}."
+ ),
+ )
+ app = graphene.Field(App, description=("App that performed the action."))
+
+ class Meta:
+ description = "The details of granted refund." + ADDED_IN_313 + PREVIEW_FEATURE
+ model = models.OrderGrantedRefund
+
+ @staticmethod
+ def resolve_user(root: models.OrderGrantedRefund, info):
+ def _resolve_user(event_user: UserModel):
+ requester = get_user_or_app_from_context(info.context)
+ if not requester:
+ return None
+ if (
+ requester == event_user
+ or requester.has_perm(AccountPermissions.MANAGE_USERS)
+ or requester.has_perm(AccountPermissions.MANAGE_STAFF)
+ ):
+ return event_user
+ return None
+
+ if not root.user_id:
+ return None
+
+ return UserByUserIdLoader(info.context).load(root.user_id).then(_resolve_user)
+
+ @staticmethod
+ def resolve_app(root: models.OrderGrantedRefund, info):
+ if root.app_id:
+ return AppByIdLoader(info.context).load(root.app_id)
+ return None
+
+
class OrderDiscount(graphene.ObjectType):
value_type = graphene.Field(
DiscountValueTypeEnum,
@@ -280,7 +333,12 @@ class OrderEvent(ModelObjectType[models.OrderEvent]):
OrderEventDiscountObject, description="The discount applied to the order."
)
status = graphene.Field(
- TransactionStatusEnum, description="The status of payment's transaction."
+ TransactionEventStatusEnum,
+ description="The status of payment's transaction.",
+ deprecation_reason=(
+ PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD
+ + "Use `TransactionEvent` to track the status of `TransactionItem`."
+ ),
)
reference = graphene.String(description="The reference of payment's transaction.")
@@ -1083,8 +1141,21 @@ class Order(ModelObjectType[models.Order]):
Money, description="Amount authorized for the order.", required=True
)
total_captured = graphene.Field(
- Money, description="Amount captured by payment.", required=True
+ Money,
+ description="Amount captured for the order. ",
+ deprecation_reason=f"{DEPRECATED_IN_3X_FIELD} Use `totalCharged` instead.",
+ required=True,
)
+ total_charged = graphene.Field(
+ Money, description="Amount charged for the order." + ADDED_IN_313, required=True
+ )
+
+ total_canceled = graphene.Field(
+ Money,
+ description="Amount canceled for the order." + ADDED_IN_313,
+ required=True,
+ )
+
events = PermissionsField(
NonNullList(OrderEvent),
description="List of events associated with the order.",
@@ -1173,6 +1244,76 @@ class Order(ModelObjectType[models.Order]):
required=False,
)
+ granted_refunds = PermissionsField(
+ NonNullList(OrderGrantedRefund),
+ required=True,
+ description="List of granted refunds." + ADDED_IN_313 + PREVIEW_FEATURE,
+ permissions=[OrderPermissions.MANAGE_ORDERS],
+ )
+ total_granted_refund = PermissionsField(
+ Money,
+ required=True,
+ description="Total amount of granted refund." + ADDED_IN_313 + PREVIEW_FEATURE,
+ permissions=[OrderPermissions.MANAGE_ORDERS],
+ )
+ total_refunded = graphene.Field(
+ Money,
+ required=True,
+ description="Total refund amount for the order."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE,
+ )
+ total_refund_pending = PermissionsField(
+ Money,
+ required=True,
+ description=(
+ "Total amount of ongoing refund requests for the order's transactions."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ permissions=[OrderPermissions.MANAGE_ORDERS],
+ )
+ total_authorize_pending = PermissionsField(
+ Money,
+ required=True,
+ description=(
+ "Total amount of ongoing authorize requests for the order's transactions."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ permissions=[OrderPermissions.MANAGE_ORDERS],
+ )
+ total_charge_pending = PermissionsField(
+ Money,
+ required=True,
+ description=(
+ "Total amount of ongoing charge requests for the order's transactions."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ permissions=[OrderPermissions.MANAGE_ORDERS],
+ )
+ total_cancel_pending = PermissionsField(
+ Money,
+ required=True,
+ description=(
+ "Total amount of ongoing cancel requests for the order's transactions."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ permissions=[OrderPermissions.MANAGE_ORDERS],
+ )
+
+ total_remaining_grant = PermissionsField(
+ Money,
+ required=True,
+ description=(
+ "The difference amount between granted refund and the "
+ "amounts that are pending and refunded." + ADDED_IN_313 + PREVIEW_FEATURE
+ ),
+ permissions=[OrderPermissions.MANAGE_ORDERS],
+ )
+
class Meta:
description = "Represents an order in the shop."
interfaces = [relay.Node, ObjectWithMetadata]
@@ -1399,35 +1540,54 @@ class Order(ModelObjectType[models.Order]):
)
@staticmethod
- def resolve_total_captured(root: models.Order, info):
- def _resolve_total_captured(transactions):
+ def resolve_total_canceled(root: models.Order, info):
+ def _resolve_total_canceled(transactions):
+ canceled_money = prices.Money(Decimal(0), root.currency)
if transactions:
- charged_money = prices.Money(Decimal(0), root.currency)
for transaction in transactions:
- charged_money += transaction.amount_charged
- return quantize_price(charged_money, root.currency)
- return root.total_charged
+ canceled_money += transaction.amount_canceled
+ return quantize_price(canceled_money, root.currency)
return (
TransactionItemsByOrderIDLoader(info.context)
.load(root.id)
- .then(_resolve_total_captured)
+ .then(_resolve_total_canceled)
)
+ @staticmethod
+ def resolve_total_captured(root: models.Order, info):
+ return root.total_charged
+
+ @staticmethod
+ def resolve_total_charged(root: models.Order, info):
+ return root.total_charged
+
@staticmethod
def resolve_total_balance(root: models.Order, info):
- def _resolve_total_balance(transactions):
- if transactions:
- charged_money = prices.Money(Decimal(0), root.currency)
+ def _resolve_total_balance(data):
+ granted_refunds, transactions, payments = data
+ if any([p.is_active for p in payments]):
+ return root.total_balance
+ else:
+ total_granted_refund = sum(
+ [granted_refund.amount for granted_refund in granted_refunds],
+ zero_money(root.currency),
+ )
+ total_charged = prices.Money(Decimal(0), root.currency)
+
for transaction in transactions:
- charged_money += transaction.amount_charged
- return quantize_price(charged_money - root.total.gross, root.currency)
- return root.total_balance
+ total_charged += transaction.amount_charged
+ total_charged += transaction.amount_charge_pending
+ order_granted_refunds_difference = (
+ root.total.gross - total_granted_refund
+ )
+ return total_charged - order_granted_refunds_difference
- return (
- TransactionItemsByOrderIDLoader(info.context)
- .load(root.id)
- .then(_resolve_total_balance)
+ granted_refunds = OrderGrantedRefundsByOrderIdLoader(info.context).load(root.id)
+ transactions = TransactionItemsByOrderIDLoader(info.context).load(root.id)
+ payments = PaymentsByOrderIdLoader(info.context).load(root.id)
+ return Promise.all([granted_refunds, transactions, payments]).then(
+ _resolve_total_balance
)
@staticmethod
@@ -1510,30 +1670,6 @@ class Order(ModelObjectType[models.Order]):
_resolve_payment_status
)
- @staticmethod
- def resolve_authorize_status(root: models.Order, info):
- total_covered = quantize_price(
- root.total_authorized_amount + root.total_charged_amount, root.currency
- )
- total_gross = quantize_price(root.total_gross_amount, root.currency)
- if total_covered == 0:
- return OrderAuthorizeStatusEnum.NONE
- if total_covered >= total_gross:
- return OrderAuthorizeStatusEnum.FULL
- return OrderAuthorizeStatusEnum.PARTIAL
-
- @staticmethod
- def resolve_charge_status(root: models.Order, info):
- total_charged = quantize_price(root.total_charged_amount, root.currency)
- total_gross = quantize_price(root.total_gross_amount, root.currency)
- if total_charged <= 0:
- return OrderChargeStatusEnum.NONE
- if total_charged < total_gross:
- return OrderChargeStatusEnum.PARTIAL
- if total_charged == total_gross:
- return OrderChargeStatusEnum.FULL
- return OrderChargeStatusEnum.OVERCHARGED
-
@staticmethod
def resolve_payment_status_display(root: models.Order, info):
def _resolve_payment_status(data):
@@ -1781,6 +1917,160 @@ class Order(ModelObjectType[models.Order]):
return []
@staticmethod
+ def resolve_granted_refunds(root: models.Order, info):
+ return OrderGrantedRefundsByOrderIdLoader(info.context).load(root.id)
+
+ @staticmethod
+ def resolve_total_granted_refund(root: models.Order, info):
+ def calculate_total_granted_refund(granted_refunds):
+ return sum(
+ [granted_refund.amount for granted_refund in granted_refunds],
+ zero_money(root.currency),
+ )
+
+ return (
+ OrderGrantedRefundsByOrderIdLoader(info.context)
+ .load(root.id)
+ .then(calculate_total_granted_refund)
+ )
+
+ @staticmethod
+ def resolve_total_refunded(root: models.Order, info):
+ def _resolve_total_refunded_for_transactions(transactions):
+ return sum(
+ [transaction.amount_refunded for transaction in transactions],
+ zero_money(root.currency),
+ )
+
+ def _resolve_total_refunded_for_payment(transactions):
+ # Calculate payment total refund requires iterating
+ # over payment's transactions
+ total_refund_amount = Decimal(0)
+ for transaction in transactions:
+ if transaction.kind == TransactionKind.REFUND:
+ total_refund_amount += transaction.amount
+ return prices.Money(total_refund_amount, root.currency)
+
+ def _resolve_total_refund(data):
+ payments, transactions = data
+ last_payment = get_last_payment(payments)
+ if last_payment and last_payment.is_active:
+ return (
+ TransactionByPaymentIdLoader(info.context)
+ .load(last_payment.id)
+ .then(_resolve_total_refunded_for_payment)
+ )
+ return _resolve_total_refunded_for_transactions(transactions)
+
+ payments = PaymentsByOrderIdLoader(info.context).load(root.id)
+ transactions = TransactionItemsByOrderIDLoader(info.context).load(root.id)
+ return Promise.all([payments, transactions]).then(_resolve_total_refund)
+
+ @staticmethod
+ def resolve_total_refund_pending(root: models.Order, info):
+ def _resolve_total_refund_pending(transactions):
+ return sum(
+ [transaction.amount_refund_pending for transaction in transactions],
+ zero_money(root.currency),
+ )
+
+ return (
+ TransactionItemsByOrderIDLoader(info.context)
+ .load(root.id)
+ .then(_resolve_total_refund_pending)
+ )
+
+ @staticmethod
+ def resolve_total_authorize_pending(root: models.Order, info):
+ def _resolve_total_authorize_pending(transactions):
+ return sum(
+ [transaction.amount_authorize_pending for transaction in transactions],
+ zero_money(root.currency),
+ )
+
+ return (
+ TransactionItemsByOrderIDLoader(info.context)
+ .load(root.id)
+ .then(_resolve_total_authorize_pending)
+ )
+
+ @staticmethod
+ def resolve_total_charge_pending(root: models.Order, info):
+ def _resolve_total_charge_pending(transactions):
+ return sum(
+ [transaction.amount_charge_pending for transaction in transactions],
+ zero_money(root.currency),
+ )
+
+ return (
+ TransactionItemsByOrderIDLoader(info.context)
+ .load(root.id)
+ .then(_resolve_total_charge_pending)
+ )
+
+ @staticmethod
+ def resolve_total_cancel_pending(root: models.Order, info):
+ def _resolve_total_cancel_pending(transactions):
+ return sum(
+ [transaction.amount_cancel_pending for transaction in transactions],
+ zero_money(root.currency),
+ )
+
+ return (
+ TransactionItemsByOrderIDLoader(info.context)
+ .load(root.id)
+ .then(_resolve_total_cancel_pending)
+ )
+
+ @staticmethod
+ def resolve_total_remaining_grant(root: models.Order, info):
+ def _resolve_total_remaining_grant_for_transactions(
+ transactions, total_granted_refund
+ ):
+ total_pending_refund = sum(
+ [transaction.amount_refund_pending for transaction in transactions],
+ zero_money(root.currency),
+ )
+ total_refund = sum(
+ [transaction.amount_refunded for transaction in transactions],
+ zero_money(root.currency),
+ )
+ return total_granted_refund - (total_pending_refund + total_refund)
+
+ def _resolve_total_remaining_grant(data):
+ transactions, payments, granted_refunds = data
+ total_granted_refund = sum(
+ [granted_refund.amount for granted_refund in granted_refunds],
+ zero_money(root.currency),
+ )
+
+ def _resolve_total_remaining_grant_for_payment(payment_transactions):
+ total_refund_amount = Decimal(0)
+ for transaction in payment_transactions:
+ if transaction.kind == TransactionKind.REFUND:
+ total_refund_amount += transaction.amount
+ return prices.Money(
+ total_granted_refund.amount - total_refund_amount, root.currency
+ )
+
+ last_payment = get_last_payment(payments)
+ if last_payment and last_payment.is_active:
+ return (
+ TransactionByPaymentIdLoader(info.context)
+ .load(last_payment.id)
+ .then(_resolve_total_remaining_grant_for_payment)
+ )
+ return _resolve_total_remaining_grant_for_transactions(
+ transactions, total_granted_refund
+ )
+
+ granted_refunds = OrderGrantedRefundsByOrderIdLoader(info.context).load(root.id)
+ transactions = TransactionItemsByOrderIDLoader(info.context).load(root.id)
+ payments = PaymentsByOrderIdLoader(info.context).load(root.id)
+ return Promise.all([transactions, payments, granted_refunds]).then(
+ _resolve_total_remaining_grant
+ )
+
def resolve_display_gross_prices(root: models.Order, info):
tax_config = TaxConfigurationByChannelId(info.context).load(root.channel_id)
country_code = get_order_country(root)
diff --git a/saleor/graphql/payment/dataloaders.py b/saleor/graphql/payment/dataloaders.py
index f65ebb8d73..e4e9d72351 100644
--- a/saleor/graphql/payment/dataloaders.py
+++ b/saleor/graphql/payment/dataloaders.py
@@ -11,7 +11,7 @@ class TransactionEventByTransactionIdLoader(DataLoader):
events = (
TransactionEvent.objects.using(self.database_connection_name)
.filter(transaction_id__in=keys)
- .order_by("pk")
+ .order_by("-created_at")
)
event_map = defaultdict(list)
for event in events:
diff --git a/saleor/graphql/payment/enums.py b/saleor/graphql/payment/enums.py
index c6aae29b9b..e3ace62ccd 100644
--- a/saleor/graphql/payment/enums.py
+++ b/saleor/graphql/payment/enums.py
@@ -4,8 +4,9 @@ from ...payment import (
ChargeStatus,
StorePaymentMethod,
TransactionAction,
+ TransactionEventStatus,
+ TransactionEventType,
TransactionKind,
- TransactionStatus,
)
from ..core.enums import to_enum
@@ -16,7 +17,14 @@ TransactionActionEnum = to_enum(
type_name="TransactionActionEnum",
description=TransactionAction.__doc__,
)
-TransactionStatusEnum = to_enum(TransactionStatus, type_name="TransactionStatus")
+TransactionEventTypeEnum = to_enum(
+ TransactionEventType, description=TransactionEventType.__doc__
+)
+TransactionEventStatusEnum = to_enum(
+ TransactionEventStatus,
+ type_name="TransactionStatus",
+ description=TransactionEventStatus.__doc__,
+)
class OrderAction(graphene.Enum):
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 57d16a3838..607f59d72b 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,11 +1,12 @@
-import uuid
from decimal import Decimal
-from typing import Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Dict, List, Optional, Union, cast
import graphene
from django.core.exceptions import ValidationError
+from django.core.validators import URLValidator
from django.db import transaction
-from django.db.models import F, Model
+from django.db.models import Model
+from django.utils import timezone
from ...channel.models import Channel
from ...checkout import models as checkout_models
@@ -14,12 +15,21 @@ from ...checkout.checkout_cleaner import clean_billing_address, clean_checkout_s
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.exceptions import PermissionDenied
+from ...core.tracing import traced_atomic_transaction
from ...core.utils import get_client_ip
from ...core.utils.url import validate_storefront_url
from ...order import models as order_models
from ...order.events import transaction_event as order_transaction_event
-from ...order.models import Order
-from ...payment import PaymentError, StorePaymentMethod, TransactionAction, gateway
+from ...order.search import update_order_search_vector
+from ...order.utils import updates_amounts_for_order
+from ...payment import (
+ PaymentError,
+ StorePaymentMethod,
+ TransactionAction,
+ TransactionEventType,
+ gateway,
+)
from ...payment import models as payment_models
from ...payment.error_codes import (
PaymentErrorCode,
@@ -28,11 +38,23 @@ from ...payment.error_codes import (
TransactionUpdateErrorCode,
)
from ...payment.gateway import (
+ request_cancelation_action,
request_charge_action,
request_refund_action,
- request_void_action,
)
-from ...payment.utils import create_payment, is_currency_supported
+from ...payment.transaction_item_calculations import (
+ calculate_transaction_amount_based_on_events,
+ recalculate_transaction_amounts,
+)
+from ...payment.utils import (
+ authorization_success_already_exists,
+ create_failed_transaction_event,
+ create_manual_adjustment_events,
+ create_payment,
+ get_already_existing_event,
+ is_currency_supported,
+)
+from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import OrderPermissions, PaymentPermissions
from ..account.i18n import I18nMixin
from ..app.dataloaders import get_app_promise
@@ -43,12 +65,15 @@ from ..core import ResolveInfo
from ..core.descriptions import (
ADDED_IN_31,
ADDED_IN_34,
+ ADDED_IN_313,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
+ PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT,
)
from ..core.doc_category import DOC_CATEGORY_PAYMENTS
+from ..core.enums import TransactionEventReportErrorCode
from ..core.fields import JSONString
-from ..core.mutations import BaseMutation
+from ..core.mutations import BaseMutation, ModelMutation
from ..core.scalars import UUID, PositiveDecimal
from ..core.types import BaseInputObjectType
from ..core.types import common as common_types
@@ -56,20 +81,19 @@ from ..discount.dataloaders import load_discounts
from ..meta.mutations import MetadataInput
from ..plugins.dataloaders import get_plugin_manager_promise
from ..utils import get_user_or_app_from_context
-from .enums import StorePaymentMethodEnum, TransactionActionEnum, TransactionStatusEnum
-from .types import Payment, PaymentInitialized, TransactionItem
-from .utils import metadata_contains_empty_key
-
-
-def add_to_order_total_authorized_and_total_charged(
- order_id: uuid.UUID,
- authorized_amount_to_add: Decimal,
- charged_amount_to_add: Decimal,
-):
- Order.objects.filter(id=order_id).update(
- total_authorized_amount=F("total_authorized_amount") + authorized_amount_to_add,
- total_charged_amount=F("total_charged_amount") + charged_amount_to_add,
- )
+from .enums import (
+ StorePaymentMethodEnum,
+ TransactionActionEnum,
+ TransactionEventStatusEnum,
+ TransactionEventTypeEnum,
+)
+from .types import Payment, PaymentInitialized, TransactionEvent, TransactionItem
+from .utils import check_if_requestor_has_access, metadata_contains_empty_key
+
+if TYPE_CHECKING:
+ from ...account.models import User
+ from ...app.models import App
+ from ...order.models import Order
class PaymentInput(BaseInputObjectType):
@@ -634,12 +658,35 @@ class PaymentCheckBalance(BaseMutation):
class TransactionUpdateInput(BaseInputObjectType):
status = graphene.String(
- description="Status of the transaction.",
+ description=(
+ "Status of the transaction."
+ + PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT
+ + " The `status` is not needed. The amounts can be used to define "
+ "the current status of transactions."
+ ),
)
type = graphene.String(
- description="Payment type used for this transaction.",
+ description="Payment type used for this transaction."
+ + PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT
+ + " Use `name` and `message` instead.",
+ )
+ name = graphene.String(
+ description="Payment name of the transaction." + ADDED_IN_313
+ )
+ message = graphene.String(
+ description="The message of the transaction." + ADDED_IN_313
+ )
+
+ reference = graphene.String(
+ description=(
+ "Reference of the transaction. "
+ + PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT
+ + " Use `pspReference` instead."
+ )
+ )
+ psp_reference = graphene.String(
+ description=("PSP Reference of the transaction. " + ADDED_IN_313)
)
- reference = graphene.String(description="Reference of the transaction.")
available_actions = graphene.List(
graphene.NonNull(TransactionActionEnum),
description="List of all possible actions for the transaction",
@@ -647,7 +694,14 @@ class TransactionUpdateInput(BaseInputObjectType):
amount_authorized = MoneyInput(description="Amount authorized by this transaction.")
amount_charged = MoneyInput(description="Amount charged by this transaction.")
amount_refunded = MoneyInput(description="Amount refunded by this transaction.")
- amount_voided = MoneyInput(description="Amount voided by this transaction.")
+ amount_voided = MoneyInput(
+ description="Amount voided by this transaction."
+ + PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT
+ + " Use `amountCanceled` instead."
+ )
+ amount_canceled = MoneyInput(
+ description="Amount canceled by this transaction." + ADDED_IN_313
+ )
metadata = graphene.List(
graphene.NonNull(MetadataInput),
@@ -659,16 +713,19 @@ class TransactionUpdateInput(BaseInputObjectType):
description="Payment private metadata.",
required=False,
)
+ external_url = graphene.String(
+ description=(
+ "The url that will allow to redirect user to "
+ "payment provider page with transaction event details." + ADDED_IN_313
+ )
+ )
class Meta:
doc_category = DOC_CATEGORY_PAYMENTS
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 Meta:
doc_category = DOC_CATEGORY_PAYMENTS
@@ -676,12 +733,31 @@ class TransactionCreateInput(TransactionUpdateInput):
class TransactionEventInput(BaseInputObjectType):
status = graphene.Field(
- TransactionStatusEnum,
- required=True,
- description="Current status of the payment transaction.",
+ TransactionEventStatusEnum,
+ required=False,
+ description="Current status of the payment transaction."
+ + PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT
+ + " Status will be calculated by Saleor.",
+ )
+ reference = graphene.String(
+ description=(
+ "Reference of the transaction. "
+ + PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT
+ + " Use `pspReference` instead."
+ )
+ )
+
+ psp_reference = graphene.String(
+ description=("PSP Reference related to this action." + ADDED_IN_313)
+ )
+ name = graphene.String(
+ description="Name of the transaction."
+ + PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT
+ + " Use `message` instead. `name` field will be added to `message`."
+ )
+ message = graphene.String(
+ description="The message related to the event." + ADDED_IN_313
)
- reference = graphene.String(description="Reference of the transaction.")
- name = graphene.String(description="Name of the transaction.")
class Meta:
doc_category = DOC_CATEGORY_PAYMENTS
@@ -704,24 +780,28 @@ class TransactionCreate(BaseMutation):
)
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
+ "Create transaction for checkout or order." + ADDED_IN_34 + PREVIEW_FEATURE
)
doc_category = DOC_CATEGORY_PAYMENTS
error_type_class = common_types.TransactionCreateError
permissions = (PaymentPermissions.HANDLE_PAYMENTS,)
@classmethod
- def check_permissions(cls, context, permissions=None, **data):
- """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
+ def validate_external_url(cls, external_url: Optional[str], error_code: str):
+ if external_url is None:
+ return
+ validator = URLValidator()
+ try:
+ validator(external_url)
+ except ValidationError:
+ raise ValidationError(
+ {
+ "transaction": ValidationError(
+ "Invalid format of `externalUrl`.", code=error_code
+ )
+ }
+ )
@classmethod
def validate_metadata_keys( # type: ignore[override]
@@ -731,26 +811,27 @@ class TransactionCreate(BaseMutation):
raise ValidationError(
{
"transaction": ValidationError(
- {
- field_name: ValidationError(
- "Metadata key cannot be empty.",
- code=error_code,
- )
- }
+ f"{field_name} key cannot be empty.",
+ code=error_code,
)
}
)
@classmethod
- def cleanup_money_data(cls, cleaned_data: dict):
+ def get_money_data_from_input(cls, cleaned_data: dict) -> Dict[str, Decimal]:
+ money_data = {}
if amount_authorized := cleaned_data.pop("amount_authorized", None):
- cleaned_data["authorized_value"] = amount_authorized["amount"]
+ money_data["authorized_value"] = amount_authorized["amount"]
if amount_charged := cleaned_data.pop("amount_charged", None):
- cleaned_data["charged_value"] = amount_charged["amount"]
+ money_data["charged_value"] = amount_charged["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"]
+ money_data["refunded_value"] = amount_refunded["amount"]
+
+ if amount_canceled := cleaned_data.pop("amount_canceled", None):
+ money_data["canceled_value"] = amount_canceled["amount"]
+ elif amount_voided := cleaned_data.pop("amount_voided", None):
+ money_data["canceled_value"] = amount_voided["amount"]
+ return money_data
@classmethod
def cleanup_metadata_data(cls, cleaned_data: dict):
@@ -787,6 +868,7 @@ class TransactionCreate(BaseMutation):
"amount_authorized",
"amount_charged",
"amount_refunded",
+ "amount_canceled",
"amount_voided",
]
errors = {}
@@ -824,41 +906,70 @@ class TransactionCreate(BaseMutation):
field_name="privateMetadata",
error_code=TransactionCreateErrorCode.METADATA_KEY_REQUIRED.value,
)
+ cls.validate_external_url(
+ transaction.get("external_url"),
+ error_code=TransactionCreateErrorCode.INVALID.value,
+ )
return instance
@classmethod
def create_transaction(
- cls, transaction_input: dict
+ cls, transaction_input: dict, user, app
) -> payment_models.TransactionItem:
- cls.cleanup_money_data(transaction_input)
cls.cleanup_metadata_data(transaction_input)
+
+ transaction_type = transaction_input.pop("type", None)
+ transaction_input["name"] = transaction_input.get("name", transaction_type)
+ reference = transaction_input.pop("reference", None)
+ transaction_input["psp_reference"] = transaction_input.get(
+ "psp_reference", reference
+ )
+ app_identifier = None
+ if app and app.identifier:
+ app_identifier = app.identifier
return payment_models.TransactionItem.objects.create(
**transaction_input,
+ user=user if user and user.is_authenticated else None,
+ app_identifier=app_identifier,
+ app=app,
)
@classmethod
def create_transaction_event(
- cls, transaction_event_input: dict, transaction: payment_models.TransactionItem
+ cls,
+ transaction_event_input: dict,
+ transaction: payment_models.TransactionItem,
+ user,
+ app,
) -> payment_models.TransactionEvent:
+ reference = transaction_event_input.pop("reference", None)
+ psp_reference = transaction_event_input.get("psp_reference", reference)
+ app_identifier = None
+ if app and app.identifier:
+ app_identifier = app.identifier
return transaction.events.create(
- status=transaction_event_input["status"],
- reference=transaction_event_input.get("reference", ""),
- name=transaction_event_input.get("name", ""),
+ status=transaction_event_input.get("status"),
+ psp_reference=psp_reference,
+ message=cls.create_event_message(transaction_event_input),
transaction=transaction,
+ user=user if user and user.is_authenticated else None,
+ app_identifier=app_identifier,
+ app=app,
+ type=TransactionEventType.INFO,
currency=transaction.currency,
)
@classmethod
- def add_amounts_to_order(cls, order_id: uuid.UUID, transaction_data: dict):
- authorized_amount = transaction_data.get("authorized_value", 0)
- charged_amount = transaction_data.get("charged_value", 0)
- if not authorized_amount and not charged_amount:
- return
- add_to_order_total_authorized_and_total_charged(
- order_id=order_id,
- authorized_amount_to_add=authorized_amount,
- charged_amount_to_add=charged_amount,
- )
+ def create_event_message(cls, transaction_event: dict) -> str:
+ message = transaction_event.get("message")
+ name = transaction_event.get("name")
+ if message and name:
+ return message + " " + name
+ elif message:
+ return message
+ elif name:
+ return name
+ return ""
@classmethod
def perform_mutation( # type: ignore[override]
@@ -878,26 +989,48 @@ class TransactionCreate(BaseMutation):
)
transaction_data = {**transaction}
transaction_data["currency"] = order_or_checkout_instance.currency
+ app = get_app_promise(info.context).get()
+ user = info.context.user
+
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:
- app = get_app_promise(info.context).get()
+ reference = transaction_event.get("reference", None)
+ psp_reference = transaction_event.get("psp_reference", reference)
order_transaction_event(
order=order_or_checkout_instance,
- user=info.context.user,
+ user=user,
app=app,
- reference=transaction_event.get("reference", ""),
- status=transaction_event["status"],
- name=transaction_event.get("name", ""),
+ reference=psp_reference,
+ status=transaction_event.get("status"),
+ message=cls.create_event_message(transaction_event),
)
- new_transaction = cls.create_transaction(transaction_data)
- if order_id := transaction_data.get("order_id"):
- cls.add_amounts_to_order(order_id, transaction_data)
+ money_data = cls.get_money_data_from_input(transaction_data)
+ new_transaction = cls.create_transaction(transaction_data, user=user, app=app)
+ if money_data:
+ create_manual_adjustment_events(
+ transaction=new_transaction, money_data=money_data, user=user, app=app
+ )
+ recalculate_transaction_amounts(new_transaction)
+ if transaction_data.get("order_id") and money_data:
+ order = cast(order_models.Order, new_transaction.order)
+ update_order_search_vector(order, save=False)
+ updates_amounts_for_order(order, save=False)
+ order.save(
+ update_fields=[
+ "total_charged_amount",
+ "charge_status",
+ "updated_at",
+ "total_authorized_amount",
+ "authorize_status",
+ "search_vector",
+ ]
+ )
if transaction_event:
- cls.create_transaction_event(transaction_event, new_transaction)
+ cls.create_transaction_event(transaction_event, new_transaction, user, app)
return TransactionCreate(transaction=new_transaction)
@@ -919,16 +1052,35 @@ class TransactionUpdate(TransactionCreate):
class Meta:
auto_permission_message = False
description = (
- "Create transaction for checkout or order. Requires the "
- "following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS."
+ "Create transaction for checkout or order."
+ ADDED_IN_34
+ PREVIEW_FEATURE
+ + "\n\nRequires the following permissions: "
+ + f"{AuthorizationFilters.OWNER.name} "
+ + f"and {PaymentPermissions.HANDLE_PAYMENTS.name}."
)
doc_category = DOC_CATEGORY_PAYMENTS
error_type_class = common_types.TransactionUpdateError
permissions = (PaymentPermissions.HANDLE_PAYMENTS,)
object_type = TransactionItem
+ @classmethod
+ def check_can_update(
+ cls,
+ transaction: payment_models.TransactionItem,
+ user: Optional["User"],
+ app: Optional["App"],
+ ):
+ if not check_if_requestor_has_access(
+ transaction=transaction, user=user, app=app
+ ):
+ raise PermissionDenied(
+ permissions=[
+ AuthorizationFilters.OWNER,
+ PaymentPermissions.HANDLE_PAYMENTS,
+ ]
+ )
+
@classmethod
def validate_transaction_input(
cls, instance: payment_models.TransactionItem, transaction_data
@@ -949,33 +1101,74 @@ class TransactionUpdate(TransactionCreate):
field_name="privateMetadata",
error_code=TransactionUpdateErrorCode.METADATA_KEY_REQUIRED.value,
)
+ cls.validate_external_url(
+ transaction_data.get("external_url"),
+ error_code=TransactionCreateErrorCode.INVALID.value,
+ )
@classmethod
- def update_amounts_for_order(
+ def update_transaction(
cls,
- transaction: payment_models.TransactionItem,
- order_id: uuid.UUID,
+ instance: payment_models.TransactionItem,
transaction_data: dict,
+ user: Optional["User"],
+ app: Optional["App"],
):
- current_authorized_amount = transaction.authorized_value
- updated_authorized_amount = transaction_data.get(
- "authorized_value", current_authorized_amount
+ money_data = cls.get_money_data_from_input(transaction_data)
+ psp_reference = transaction_data.get(
+ "psp_reference", transaction_data.pop("reference", None)
)
- authorized_amount_to_add = updated_authorized_amount - current_authorized_amount
-
- current_charged_amount = transaction.charged_value
- updated_charged_amount = transaction_data.get(
- "charged_value", current_charged_amount
+ if psp_reference and instance.psp_reference != psp_reference:
+ if payment_models.TransactionItem.objects.filter(
+ psp_reference=psp_reference
+ ).exists():
+ raise ValidationError(
+ {
+ "transaction": ValidationError(
+ "Transaction with provided `pspReference` already exists.",
+ code=TransactionUpdateErrorCode.UNIQUE.value,
+ )
+ }
+ )
+ transaction_data["name"] = transaction_data.get(
+ "name", transaction_data.pop("type", None)
)
- charged_amount_to_add = updated_charged_amount - current_charged_amount
+ transaction_data["psp_reference"] = psp_reference
+ instance = cls.construct_instance(instance, transaction_data)
+ instance.save()
+ if money_data:
+ calculate_transaction_amount_based_on_events(transaction=instance)
+ create_manual_adjustment_events(
+ transaction=instance, money_data=money_data, user=user, app=app
+ )
+ recalculate_transaction_amounts(instance)
+ if instance.order_id:
+ order = cast(order_models.Order, instance.order)
+ cls.update_order(order, money_data, psp_reference)
- if not authorized_amount_to_add and not charged_amount_to_add:
- return
- add_to_order_total_authorized_and_total_charged(
- order_id=order_id,
- authorized_amount_to_add=authorized_amount_to_add,
- charged_amount_to_add=charged_amount_to_add,
- )
+ @classmethod
+ def update_order(
+ cls, order: "Order", money_data: dict, psp_reference: Optional[str]
+ ) -> None:
+ update_fields = []
+ if money_data:
+ updates_amounts_for_order(order)
+ update_fields.extend(
+ [
+ "total_charged_amount",
+ "charge_status",
+ "total_authorized_amount",
+ "authorize_status",
+ ]
+ )
+ if psp_reference:
+ update_order_search_vector(order, save=False)
+ update_fields.append(
+ "search_vector",
+ )
+ if update_fields:
+ update_fields.append("updated_at")
+ order.save(update_fields=update_fields)
@classmethod
def perform_mutation( # type: ignore[override]
@@ -988,27 +1181,33 @@ class TransactionUpdate(TransactionCreate):
transaction=None,
transaction_event=None
):
+ app = get_app_promise(info.context).get()
+ user = info.context.user
instance = cls.get_node_or_error(info, id, only_type=TransactionItem)
+
+ cls.check_can_update(
+ transaction=instance,
+ user=user if user and user.is_authenticated else None,
+ app=app,
+ )
+
if transaction:
cls.validate_transaction_input(instance, transaction)
- cls.cleanup_money_data(transaction)
cls.cleanup_metadata_data(transaction)
- if instance.order_id:
- cls.update_amounts_for_order(instance, instance.order_id, transaction)
- instance = cls.construct_instance(instance, transaction)
- instance.save()
+ cls.update_transaction(instance, transaction, user, app)
if transaction_event:
- cls.create_transaction_event(transaction_event, instance)
+ cls.create_transaction_event(transaction_event, instance, user, app)
if instance.order:
- app = get_app_promise(info.context).get()
+ reference = transaction_event.pop("reference", None)
+ psp_reference = transaction_event.get("psp_reference", reference)
order_transaction_event(
order=instance.order,
- user=info.context.user,
+ user=user,
app=app,
- reference=transaction_event.get("reference", ""),
+ reference=psp_reference or "",
status=transaction_event["status"],
- name=transaction_event.get("name", ""),
+ message=cls.create_event_message(transaction_event),
)
return TransactionUpdate(transaction=instance)
@@ -1039,10 +1238,7 @@ class TransactionRequestAction(BaseMutation):
)
doc_category = DOC_CATEGORY_PAYMENTS
error_type_class = common_types.TransactionRequestActionError
- permissions = (
- PaymentPermissions.HANDLE_PAYMENTS,
- OrderPermissions.MANAGE_ORDERS,
- )
+ permissions = (PaymentPermissions.HANDLE_PAYMENTS,)
@classmethod
def check_permissions(cls, context, permissions=None, **data):
@@ -1059,18 +1255,60 @@ class TransactionRequestAction(BaseMutation):
def handle_transaction_action(
cls, action, action_kwargs, action_value: Optional[Decimal]
):
- if action == TransactionAction.VOID:
- request_void_action(**action_kwargs)
+ if action == TransactionAction.VOID or action == TransactionAction.CANCEL:
+ transaction = action_kwargs["transaction"]
+ request_event = cls.create_transaction_event_requested(
+ transaction, 0, action
+ )
+ request_cancelation_action(
+ **action_kwargs,
+ cancel_value=action_value,
+ request_event=request_event,
+ action=action,
+ )
elif action == TransactionAction.CHARGE:
transaction = action_kwargs["transaction"]
action_value = action_value or transaction.authorized_value
action_value = min(action_value, transaction.authorized_value)
- request_charge_action(**action_kwargs, charge_value=action_value)
+ request_event = cls.create_transaction_event_requested(
+ transaction, action_value, TransactionAction.CHARGE
+ )
+ request_charge_action(
+ **action_kwargs, charge_value=action_value, request_event=request_event
+ )
elif action == TransactionAction.REFUND:
transaction = action_kwargs["transaction"]
action_value = action_value or transaction.charged_value
action_value = min(action_value, transaction.charged_value)
- request_refund_action(**action_kwargs, refund_value=action_value)
+ request_event = cls.create_transaction_event_requested(
+ transaction, action_value, TransactionAction.REFUND
+ )
+ request_refund_action(
+ **action_kwargs, refund_value=action_value, request_event=request_event
+ )
+
+ @classmethod
+ def create_transaction_event_requested(cls, transaction, action_value, action):
+ if action in (TransactionAction.CANCEL, TransactionAction.VOID):
+ type = TransactionEventType.CANCEL_REQUEST
+ elif action == TransactionAction.CHARGE:
+ type = TransactionEventType.CHARGE_REQUEST
+ elif action == TransactionAction.REFUND:
+ type = TransactionEventType.REFUND_REQUEST
+ else:
+ raise ValidationError(
+ {
+ "actionType": ValidationError(
+ "Incorrect action.",
+ code=TransactionRequestActionErrorCode.INVALID.value,
+ )
+ }
+ )
+ return transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=type,
+ )
@classmethod
def perform_mutation(cls, root, info: ResolveInfo, /, **data):
@@ -1100,3 +1338,193 @@ class TransactionRequestAction(BaseMutation):
code = error_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
raise ValidationError(str(e), code=code)
return TransactionRequestAction(transaction=transaction)
+
+
+class TransactionEventReport(ModelMutation):
+ already_processed = graphene.Boolean(
+ description="Defines if the reported event hasn't been processed earlier."
+ )
+ transaction = graphene.Field(
+ TransactionItem, description="The transaction related to the reported event."
+ )
+ transaction_event = graphene.Field(
+ TransactionEvent,
+ description=(
+ "The event assigned to this report. if `alreadyProcessed` is set to `true`,"
+ " the previously processed event will be returned."
+ ),
+ )
+
+ class Arguments:
+ id = graphene.ID(
+ description="The ID of the transaction.",
+ required=True,
+ )
+ psp_reference = graphene.String(
+ description="PSP Reference of the event to report.", required=True
+ )
+ type = graphene.Argument(
+ TransactionEventTypeEnum,
+ required=True,
+ description="Current status of the event to report.",
+ )
+ amount = PositiveDecimal(
+ description="The amount of the event to report.", required=True
+ )
+ time = graphene.DateTime(
+ description=(
+ "The time of the event to report. If not provide, "
+ "the current time will be used."
+ )
+ )
+ external_url = graphene.String(
+ description=(
+ "The url that will allow to redirect user to "
+ "payment provider page with event details."
+ )
+ )
+ message = graphene.String(description="The message related to the event.")
+ available_actions = graphene.List(
+ graphene.NonNull(TransactionActionEnum),
+ description="List of all possible actions for the transaction",
+ )
+
+ class Meta:
+ description = (
+ "Report the event for the transaction."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ + "\n\nRequires the following permissions: "
+ + f"{AuthorizationFilters.OWNER.name} "
+ + f"and {PaymentPermissions.HANDLE_PAYMENTS.name}."
+ )
+ error_type_class = common_types.TransactionEventReportError
+ permissions = (PaymentPermissions.HANDLE_PAYMENTS,)
+ doc_category = DOC_CATEGORY_PAYMENTS
+ model = payment_models.TransactionEvent
+ object_type = TransactionEvent
+ auto_permission_message = False
+
+ @classmethod
+ def _update_mutation_arguments_and_fields(cls, arguments, fields):
+ cls._meta.arguments.update(arguments)
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls,
+ root,
+ info: ResolveInfo,
+ /,
+ *,
+ id,
+ psp_reference,
+ type,
+ amount,
+ time=None,
+ external_url=None,
+ message=None,
+ available_actions=None
+ ):
+ user = info.context.user
+ app = get_app_promise(info.context).get()
+ transaction = cls.get_node_or_error(info, id, only_type="TransactionItem")
+ transaction = cast(payment_models.TransactionItem, transaction)
+
+ if not check_if_requestor_has_access(
+ transaction=transaction, user=user, app=app
+ ):
+ raise PermissionDenied(
+ permissions=[
+ AuthorizationFilters.OWNER,
+ PaymentPermissions.HANDLE_PAYMENTS,
+ ]
+ )
+
+ app_identifier = None
+ if app and app.identifier:
+ app_identifier = app.identifier
+
+ transaction_event_data = {
+ "psp_reference": psp_reference,
+ "type": type,
+ "amount_value": amount,
+ "currency": transaction.currency,
+ "created_at": time or timezone.now(),
+ "external_url": external_url or "",
+ "message": message or "",
+ "transaction": transaction,
+ "app_identifier": app_identifier,
+ "app": app,
+ "user": user,
+ "include_in_calculations": True,
+ }
+ transaction_event = cls.get_instance(info, **transaction_event_data)
+ transaction_event = cast(payment_models.TransactionEvent, transaction_event)
+ transaction_event = cls.construct_instance(
+ transaction_event, transaction_event_data
+ )
+
+ cls.clean_instance(info, transaction_event)
+ already_processed = False
+ error_code = None
+ error_msg = None
+ error_field = None
+ with traced_atomic_transaction():
+ # The mutation can be called multiple times by the app. That can cause a
+ # thread race. We need to be sure, that we will always create a single event
+ # on our side for specific action.
+ existing_event = get_already_existing_event(transaction_event)
+ if existing_event and existing_event.amount != transaction_event.amount:
+ error_code = TransactionEventReportErrorCode.INCORRECT_DETAILS.value
+ error_msg = (
+ "The transaction with provided `pspReference` and "
+ "`type` already exists with different amount."
+ )
+ error_field = "pspReference"
+ elif existing_event:
+ already_processed = True
+ transaction_event = existing_event
+ elif (
+ transaction_event.type == TransactionEventType.AUTHORIZATION_SUCCESS
+ and authorization_success_already_exists(transaction.pk)
+ ):
+ error_code = TransactionEventReportErrorCode.ALREADY_EXISTS.value
+ error_msg = (
+ "Event with `AUTHORIZATION_SUCCESS` already "
+ "reported for the transaction. Use "
+ "`AUTHORIZATION_ADJUSTMENT` to change the "
+ "authorization amount."
+ )
+ error_field = "type"
+ else:
+ transaction_event.save()
+
+ if error_msg and error_code and error_field:
+ create_failed_transaction_event(transaction_event, cause=error_msg)
+ raise ValidationError({error_field: ValidationError(error_msg, error_code)})
+ if not already_processed:
+ if available_actions is not None:
+ transaction.available_actions = available_actions
+ transaction.save(update_fields=["available_actions"])
+ recalculate_transaction_amounts(transaction)
+ if transaction.order_id:
+ order = cast(order_models.Order, transaction.order)
+ update_order_search_vector(order, save=False)
+ updates_amounts_for_order(order, save=False)
+ order.save(
+ update_fields=[
+ "total_charged_amount",
+ "charge_status",
+ "updated_at",
+ "total_authorized_amount",
+ "authorize_status",
+ "search_vector",
+ ]
+ )
+
+ return cls(
+ already_processed=already_processed,
+ transaction=transaction,
+ transaction_event=transaction_event,
+ errors=[],
+ )
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index aa06375f55..f7c859c9da 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -15,6 +15,7 @@ from .mutations import (
PaymentRefund,
PaymentVoid,
TransactionCreate,
+ TransactionEventReport,
TransactionRequestAction,
TransactionUpdate,
)
@@ -82,3 +83,4 @@ class PaymentMutations(graphene.ObjectType):
transaction_create = TransactionCreate.Field()
transaction_update = TransactionUpdate.Field()
transaction_request_action = TransactionRequestAction.Field()
+ transaction_event_report = TransactionEventReport.Field()
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index 023338e11d..76a2c469ac 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -3,13 +3,20 @@ from decimal import Decimal
import graphene
import pytest
-from .....order import OrderEvents
+from .....order import OrderAuthorizeStatus, OrderEvents
from .....order.utils import update_order_authorize_data, update_order_charge_data
-from .....payment import TransactionStatus
+from .....payment import TransactionEventStatus, TransactionEventType
from .....payment.error_codes import TransactionCreateErrorCode
from .....payment.models import TransactionItem
+from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...enums import TransactionActionEnum, TransactionStatusEnum
+from ...enums import (
+ TransactionActionEnum,
+ TransactionEventStatusEnum,
+ TransactionEventTypeEnum,
+)
+
+TEST_SERVER_DOMAIN = "testserver.com"
MUTATION_TRANSACTION_CREATE = """
mutation TransactionCreate(
@@ -25,15 +32,20 @@ mutation TransactionCreate(
transaction{
id
actions
- reference
+ pspReference
type
status
modifiedAt
createdAt
+ externalUrl
authorizedAmount{
amount
currency
}
+ canceledAmount{
+ currency
+ amount
+ }
voidedAmount{
currency
amount
@@ -46,11 +58,34 @@ mutation TransactionCreate(
currency
amount
}
+ createdBy{
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
events{
- status
- reference
- name
- createdAt
+ status
+ pspReference
+ name
+ message
+ createdAt
+ externalUrl
+ amount{
+ amount
+ currency
+ }
+ type
+ createdBy{
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
}
}
errors{
@@ -63,13 +98,59 @@ mutation TransactionCreate(
"""
-def test_transaction_create_for_order(
+def test_transaction_create_updates_order_authorize_amounts(
+ order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ "externalUrl": external_url,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ order_with_lines.refresh_from_db()
+ assert order_with_lines.total_authorized.amount == authorized_value
+ assert order_with_lines.authorize_status == OrderAuthorizeStatus.PARTIAL
+ assert order_with_lines.search_vector
+
+
+def test_transaction_create_for_order_by_app(
order_with_lines, permission_manage_payments, app_api_client
):
# given
status = "Authorized for 10$"
type = "Credit Card"
- reference = "PSP reference - 123"
+ psp_reference = "PSP reference - 123"
available_actions = [
TransactionActionEnum.CHARGE.name,
TransactionActionEnum.VOID.name,
@@ -77,13 +158,14 @@ def test_transaction_create_for_order(
authorized_value = Decimal("10")
metadata = {"key": "test-1", "value": "123"}
private_metadata = {"key": "test-2", "value": "321"}
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
variables = {
"id": graphene.Node.to_global_id("Order", order_with_lines.pk),
"transaction": {
"status": status,
"type": type,
- "reference": reference,
+ "pspReference": psp_reference,
"availableActions": available_actions,
"amountAuthorized": {
"amount": authorized_value,
@@ -91,6 +173,7 @@ def test_transaction_create_for_order(
},
"metadata": [metadata],
"privateMetadata": [private_metadata],
+ "externalUrl": external_url,
},
}
@@ -105,20 +188,26 @@ def test_transaction_create_for_order(
data = content["data"]["transactionCreate"]["transaction"]
assert data["actions"] == available_actions
assert data["status"] == status
- assert data["reference"] == reference
+ assert data["pspReference"] == psp_reference
assert data["authorizedAmount"]["amount"] == authorized_value
+ assert data["externalUrl"] == external_url
+ assert data["createdBy"]["id"] == to_global_id_or_none(app_api_client.app)
assert available_actions == list(map(str.upper, transaction.available_actions))
assert status == transaction.status
- assert reference == transaction.reference
+ assert psp_reference == transaction.psp_reference
assert authorized_value == transaction.authorized_value
assert transaction.metadata == {metadata["key"]: metadata["value"]}
assert transaction.private_metadata == {
private_metadata["key"]: private_metadata["value"]
}
+ assert transaction.app_identifier == app_api_client.app.identifier
+ assert transaction.app == app_api_client.app
+ assert transaction.user is None
+ assert transaction.external_url == external_url
-def test_transaction_create_for_order_updates_order_total_authorized(
+def test_transaction_create_for_order_updates_order_total_authorized_by_app(
order_with_lines, permission_manage_payments, app_api_client
):
# given
@@ -136,7 +225,7 @@ def test_transaction_create_for_order_updates_order_total_authorized(
"transaction": {
"status": "Authorized for 10$",
"type": "Credit Card",
- "reference": "PSP reference - 123",
+ "pspReference": "PSP reference - 123",
"availableActions": [],
"amountAuthorized": {
"amount": authorized_value,
@@ -165,7 +254,7 @@ def test_transaction_create_for_order_updates_order_total_authorized(
assert authorized_value == transaction.authorized_value
-def test_transaction_create_for_order_updates_order_total_charged(
+def test_transaction_create_for_order_updates_order_total_charged_by_app(
order_with_lines, permission_manage_payments, app_api_client
):
# given
@@ -182,7 +271,7 @@ def test_transaction_create_for_order_updates_order_total_charged(
"transaction": {
"status": "Charged 10$",
"type": "Credit Card",
- "reference": "PSP reference - 123",
+ "pspReference": "PSP reference - 123",
"availableActions": [],
"amountCharged": {
"amount": charged_value,
@@ -211,13 +300,13 @@ def test_transaction_create_for_order_updates_order_total_charged(
assert charged_value == transaction.charged_value
-def test_transaction_create_for_checkout(
+def test_transaction_create_for_checkout_by_app(
checkout_with_items, permission_manage_payments, app_api_client
):
# given
status = "Authorized for 10$"
type = "Credit Card"
- reference = "PSP reference - 123"
+ psp_reference = "PSP reference - 123"
available_actions = [
TransactionActionEnum.CHARGE.name,
TransactionActionEnum.VOID.name,
@@ -225,13 +314,14 @@ def test_transaction_create_for_checkout(
authorized_value = Decimal("10")
metadata = {"key": "test-1", "value": "123"}
private_metadata = {"key": "test-2", "value": "321"}
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
variables = {
"id": graphene.Node.to_global_id("Checkout", checkout_with_items.pk),
"transaction": {
"status": status,
"type": type,
- "reference": reference,
+ "pspReference": psp_reference,
"availableActions": available_actions,
"amountAuthorized": {
"amount": authorized_value,
@@ -239,6 +329,7 @@ def test_transaction_create_for_checkout(
},
"metadata": [metadata],
"privateMetadata": [private_metadata],
+ "externalUrl": external_url,
},
}
@@ -253,17 +344,23 @@ def test_transaction_create_for_checkout(
data = content["data"]["transactionCreate"]["transaction"]
assert data["actions"] == available_actions
assert data["status"] == status
- assert data["reference"] == reference
+ assert data["pspReference"] == psp_reference
assert data["authorizedAmount"]["amount"] == authorized_value
+ assert data["externalUrl"] == external_url
+ assert data["createdBy"]["id"] == to_global_id_or_none(app_api_client.app)
assert available_actions == list(map(str.upper, transaction.available_actions))
assert status == transaction.status
- assert reference == transaction.reference
+ assert psp_reference == transaction.psp_reference
assert authorized_value == transaction.authorized_value
assert transaction.metadata == {metadata["key"]: metadata["value"]}
assert transaction.private_metadata == {
private_metadata["key"]: private_metadata["value"]
}
+ assert transaction.external_url == external_url
+ assert transaction.app_identifier == app_api_client.app.identifier
+ assert transaction.app == app_api_client.app
+ assert transaction.user is None
@pytest.mark.parametrize(
@@ -271,11 +368,12 @@ def test_transaction_create_for_checkout(
[
("amountAuthorized", "authorized_value"),
("amountCharged", "charged_value"),
- ("amountVoided", "voided_value"),
+ ("amountVoided", "canceled_value"),
+ ("amountCanceled", "canceled_value"),
("amountRefunded", "refunded_value"),
],
)
-def test_transaction_create_calculate_amount(
+def test_transaction_create_calculate_amount_by_app(
amount_field_name,
amount_db_field,
order_with_lines,
@@ -285,7 +383,7 @@ def test_transaction_create_calculate_amount(
# given
status = "Authorized for 10$"
type = "Credit Card"
- reference = "PSP reference - 123"
+ psp_reference = "PSP reference - 123"
expected_value = Decimal("10")
variables = {
@@ -293,7 +391,7 @@ def test_transaction_create_calculate_amount(
"transaction": {
"status": status,
"type": type,
- "reference": reference,
+ "pspReference": psp_reference,
"availableActions": [],
amount_field_name: {
"amount": expected_value,
@@ -314,13 +412,13 @@ def test_transaction_create_calculate_amount(
assert getattr(transaction, amount_db_field) == expected_value
-def test_transaction_create_multiple_amounts_provided(
+def test_transaction_create_multiple_amounts_provided_by_app(
order_with_lines, permission_manage_payments, app_api_client
):
# given
status = "Authorized for 10$"
type = "Credit Card"
- reference = "PSP reference - 123"
+ psp_reference = "PSP reference - 123"
available_actions = [
TransactionActionEnum.CHARGE.name,
TransactionActionEnum.VOID.name,
@@ -328,14 +426,14 @@ def test_transaction_create_multiple_amounts_provided(
authorized_value = Decimal("10")
charged_value = Decimal("11")
refunded_value = Decimal("12")
- voided_value = Decimal("13")
+ canceled_value = Decimal("13")
variables = {
"id": graphene.Node.to_global_id("Order", order_with_lines.pk),
"transaction": {
"status": status,
"type": type,
- "reference": reference,
+ "pspReference": psp_reference,
"availableActions": available_actions,
"amountAuthorized": {
"amount": authorized_value,
@@ -349,8 +447,8 @@ def test_transaction_create_multiple_amounts_provided(
"amount": refunded_value,
"currency": "USD",
},
- "amountVoided": {
- "amount": voided_value,
+ "amountCanceled": {
+ "amount": canceled_value,
"currency": "USD",
},
},
@@ -367,31 +465,30 @@ def test_transaction_create_multiple_amounts_provided(
data = content["data"]["transactionCreate"]["transaction"]
assert data["actions"] == available_actions
assert data["status"] == status
- assert data["reference"] == reference
+ assert data["pspReference"] == psp_reference
assert data["authorizedAmount"]["amount"] == authorized_value
assert data["chargedAmount"]["amount"] == charged_value
assert data["refundedAmount"]["amount"] == refunded_value
- assert data["voidedAmount"]["amount"] == voided_value
+ assert data["canceledAmount"]["amount"] == canceled_value
assert transaction.authorized_value == authorized_value
assert transaction.charged_value == charged_value
- assert transaction.voided_value == voided_value
+ assert transaction.canceled_value == canceled_value
assert transaction.refunded_value == refunded_value
-def test_transaction_create_create_event_for_order(
+def test_transaction_create_create_event_for_order_by_app(
order_with_lines, permission_manage_payments, app_api_client
):
# given
status = "Authorized for 10$"
type = "Credit Card"
- reference = "PSP reference - 123"
+ psp_reference = "PSP reference - 123"
available_actions = [
TransactionActionEnum.CHARGE.name,
TransactionActionEnum.VOID.name,
]
authorized_value = Decimal("10")
- transaction_status = "PENDING"
transaction_reference = "transaction reference"
transaction_name = "Processing transaction"
@@ -400,7 +497,7 @@ def test_transaction_create_create_event_for_order(
"transaction": {
"status": status,
"type": type,
- "reference": reference,
+ "pspReference": psp_reference,
"availableActions": available_actions,
"amountAuthorized": {
"amount": authorized_value,
@@ -408,9 +505,8 @@ def test_transaction_create_create_event_for_order(
},
},
"transaction_event": {
- "status": transaction_status,
- "reference": transaction_reference,
- "name": transaction_name,
+ "pspReference": transaction_reference,
+ "message": transaction_name,
},
}
@@ -420,23 +516,22 @@ def test_transaction_create_create_event_for_order(
)
# then
+ assert order_with_lines.events.count() == 1
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(),
+ "status": None,
}
-def test_transaction_create_permission_denied_for_staff(
- order_with_lines, staff_api_client, permission_manage_payments
-):
+def test_transaction_create_missing_permission_by_app(order_with_lines, app_api_client):
# given
status = "Authorized for 10$"
type = "Credit Card"
- reference = "PSP reference - 123"
+ psp_reference = "PSP reference - 123"
available_actions = [
TransactionActionEnum.CHARGE.name,
TransactionActionEnum.VOID.name,
@@ -450,7 +545,7 @@ def test_transaction_create_permission_denied_for_staff(
"transaction": {
"status": status,
"type": type,
- "reference": reference,
+ "pspReference": psp_reference,
"availableActions": available_actions,
"amountAuthorized": {
"amount": authorized_value,
@@ -462,33 +557,83 @@ def test_transaction_create_permission_denied_for_staff(
}
# when
- response = staff_api_client.post_graphql(
+ response = app_api_client.post_graphql(MUTATION_TRANSACTION_CREATE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+ "amount_field_name, amount_db_field",
+ [
+ ("amountAuthorized", "authorized_value"),
+ ("amountCharged", "charged_value"),
+ ("amountVoided", "canceled_value"),
+ ("amountCanceled", "canceled_value"),
+ ("amountRefunded", "refunded_value"),
+ ],
+)
+def test_transaction_create_incorrect_currency_by_app(
+ amount_field_name,
+ amount_db_field,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_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,
+ "pspReference": psp_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
- assert_no_permission(response)
+ 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_transaction_create_missing_app_permission(order_with_lines, app_api_client):
+def test_transaction_create_empty_metadata_key_by_app(
+ order_with_lines, permission_manage_payments, app_api_client
+):
# given
status = "Authorized for 10$"
type = "Credit Card"
- reference = "PSP reference - 123"
+ psp_reference = "PSP reference - 123"
available_actions = [
TransactionActionEnum.CHARGE.name,
TransactionActionEnum.VOID.name,
]
authorized_value = Decimal("10")
- metadata = {"key": "test-1", "value": "123"}
+ metadata = {"key": "", "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,
+ "pspReference": psp_reference,
"availableActions": available_actions,
"amountAuthorized": {
"amount": authorized_value,
@@ -500,45 +645,46 @@ def test_transaction_create_missing_app_permission(order_with_lines, app_api_cli
}
# when
- response = app_api_client.post_graphql(MUTATION_TRANSACTION_CREATE, variables)
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
# then
- assert_no_permission(response)
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionCreate"]["transaction"]
+ errors = content["data"]["transactionCreate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionCreateErrorCode.METADATA_KEY_REQUIRED.name
- "amount_field_name, amount_db_field",
- [
- ("amountAuthorized", "authorized_value"),
- ("amountCharged", "charged_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,
+def test_transaction_create_empty_private_metadata_key_by_app(
+ 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")
-
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "", "value": "321"}
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",
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
},
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
},
}
@@ -548,35 +694,35 @@ def test_transaction_create_incorrect_currency(
)
# 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
- )
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionCreate"]["transaction"]
+ errors = content["data"]["transactionCreate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionCreateErrorCode.METADATA_KEY_REQUIRED.name
-def test_creates_transaction_event_for_order(
+def test_creates_transaction_event_for_order_by_app(
order_with_lines, permission_manage_payments, app_api_client
):
# given
status = "Failed authorized for 10$"
type = "Credit Card"
- reference = "PSP reference - 123"
+ psp_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"
+ event_psp_reference = "PSP-ref"
+ event_message = "Failed authorization"
+ event_name = "Depreceated field attached to message."
variables = {
"id": graphene.Node.to_global_id("Order", order_with_lines.pk),
"transaction": {
"status": status,
"type": type,
- "reference": reference,
+ "pspReference": psp_reference,
"availableActions": available_actions,
"amountAuthorized": {
"amount": authorized_value,
@@ -586,8 +732,8 @@ def test_creates_transaction_event_for_order(
"privateMetadata": [private_metadata],
},
"transaction_event": {
- "status": TransactionStatusEnum.FAILURE.name,
- "reference": event_reference,
+ "pspReference": event_psp_reference,
+ "message": event_message,
"name": event_name,
},
}
@@ -605,34 +751,38 @@ def test_creates_transaction_event_for_order(
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 event_data["message"] == event_message + " " + event_name
+ assert event_data["name"] == event_message + " " + event_name
+ assert event_data["pspReference"] == event_psp_reference
+ assert event_data["externalUrl"] == ""
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(app_api_client.app)
assert transaction.events.count() == 1
event = transaction.events.first()
- assert event.name == event_name
- assert event.status == event_status
- assert event.reference == event_reference
+ assert event.message == event_message + " " + event_name
+ assert event.status is None
+ assert event.psp_reference == event_psp_reference
+ assert event.app_identifier == app_api_client.app.identifier
+ assert event.app == app_api_client.app
+ assert event.user is None
-def test_creates_transaction_event_for_checkout(
+def test_creates_transaction_event_for_checkout_by_app(
checkout_with_items, permission_manage_payments, app_api_client
):
# given
status = "Authorized for 10$"
type = "Credit Card"
- reference = "PSP reference - 123"
+ psp_reference = "PSP reference - 123"
available_actions = [
TransactionActionEnum.CHARGE.name,
TransactionActionEnum.VOID.name,
]
- authorized_value = Decimal("10")
+ 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_psp_reference = "PSP-ref"
event_name = "Failed authorization"
variables = {
@@ -640,7 +790,7 @@ def test_creates_transaction_event_for_checkout(
"transaction": {
"status": status,
"type": type,
- "reference": reference,
+ "pspReference": psp_reference,
"availableActions": available_actions,
"amountAuthorized": {
"amount": authorized_value,
@@ -650,8 +800,7 @@ def test_creates_transaction_event_for_checkout(
"privateMetadata": [private_metadata],
},
"transaction_event": {
- "status": TransactionStatusEnum.FAILURE.name,
- "reference": event_reference,
+ "pspReference": event_psp_reference,
"name": event_name,
},
}
@@ -669,12 +818,834 @@ def test_creates_transaction_event_for_checkout(
events_data = data["events"]
assert len(events_data) == 1
event_data = events_data[0]
+ assert event_data["message"] == event_name
assert event_data["name"] == event_name
- assert event_data["status"] == TransactionStatusEnum.FAILURE.name
- assert event_data["reference"] == event_reference
+ assert event_data["pspReference"] == event_psp_reference
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(app_api_client.app)
assert transaction.events.count() == 1
event = transaction.events.first()
- assert event.name == event_name
- assert event.status == event_status
- assert event.reference == event_reference
+ assert event.message == event_name
+ assert event.psp_reference == event_psp_reference
+ assert event.app_identifier == app_api_client.app.identifier
+ assert event.app == app_api_client.app
+ assert event.user is None
+
+
+def test_transaction_create_for_order_by_staff(
+ order_with_lines, permission_manage_payments, staff_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.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,
+ "pspReference": psp_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
+ 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["pspReference"] == psp_reference
+ assert data["authorizedAmount"]["amount"] == authorized_value
+ assert data["createdBy"]["id"] == to_global_id_or_none(staff_api_client.user)
+
+ assert available_actions == list(map(str.upper, transaction.available_actions))
+ assert status == transaction.status
+ assert psp_reference == transaction.psp_reference
+ assert authorized_value == transaction.authorized_value
+ assert transaction.metadata == {metadata["key"]: metadata["value"]}
+ assert transaction.private_metadata == {
+ private_metadata["key"]: private_metadata["value"]
+ }
+ assert transaction.user == staff_api_client.user
+ assert not transaction.app_identifier
+ assert not transaction.app
+
+
+def test_transaction_create_for_order_updates_order_total_authorized_by_staff(
+ order_with_lines, permission_manage_payments, staff_api_client
+):
+ # given
+ previously_authorized_value = Decimal("90")
+ old_transaction = order_with_lines.payment_transactions.create(
+ authorized_value=previously_authorized_value, currency=order_with_lines.currency
+ )
+
+ update_order_authorize_data(order_with_lines)
+
+ authorized_value = Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": "Authorized for 10$",
+ "type": "Credit Card",
+ "pspReference": "PSP reference - 123",
+ "availableActions": [],
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ transaction = order_with_lines.payment_transactions.exclude(
+ id=old_transaction.id
+ ).last()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionCreate"]["transaction"]
+ assert data["authorizedAmount"]["amount"] == authorized_value
+ assert (
+ order_with_lines.total_authorized_amount
+ == previously_authorized_value + authorized_value
+ )
+ assert authorized_value == transaction.authorized_value
+
+
+def test_transaction_create_for_order_updates_order_total_charged_by_staff(
+ order_with_lines, permission_manage_payments, staff_api_client
+):
+ # given
+ previously_charged_value = Decimal("90")
+ old_transaction = order_with_lines.payment_transactions.create(
+ charged_value=previously_charged_value, currency=order_with_lines.currency
+ )
+ update_order_charge_data(order_with_lines)
+
+ charged_value = Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": "Charged 10$",
+ "type": "Credit Card",
+ "pspReference": "PSP reference - 123",
+ "availableActions": [],
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ transaction = order_with_lines.payment_transactions.exclude(
+ id=old_transaction.id
+ ).last()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionCreate"]["transaction"]
+ assert data["chargedAmount"]["amount"] == charged_value
+ assert (
+ order_with_lines.total_charged_amount
+ == previously_charged_value + charged_value
+ )
+ assert charged_value == transaction.charged_value
+
+
+def test_transaction_create_for_checkout_by_staff(
+ checkout_with_items, permission_manage_payments, staff_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.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,
+ "pspReference": psp_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
+ 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["pspReference"] == psp_reference
+ assert data["authorizedAmount"]["amount"] == authorized_value
+ assert data["createdBy"]["id"] == to_global_id_or_none(staff_api_client.user)
+
+ assert available_actions == list(map(str.upper, transaction.available_actions))
+ assert status == transaction.status
+ assert psp_reference == transaction.psp_reference
+ assert authorized_value == transaction.authorized_value
+ assert transaction.metadata == {metadata["key"]: metadata["value"]}
+ assert transaction.private_metadata == {
+ private_metadata["key"]: private_metadata["value"]
+ }
+ assert transaction.app_identifier is None
+ assert transaction.app is None
+ assert transaction.user == staff_api_client.user
+
+
+ "amount_field_name, amount_db_field",
+ [
+ ("amountAuthorized", "authorized_value"),
+ ("amountCharged", "charged_value"),
+ ("amountVoided", "canceled_value"),
+ ("amountCanceled", "canceled_value"),
+ ("amountRefunded", "refunded_value"),
+ ],
+)
+def test_transaction_create_calculate_amount_by_staff(
+ amount_field_name,
+ amount_db_field,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_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,
+ "pspReference": psp_reference,
+ "availableActions": [],
+ amount_field_name: {
+ "amount": expected_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_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_by_staff(
+ order_with_lines, permission_manage_payments, staff_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ charged_value = Decimal("11")
+ refunded_value = Decimal("12")
+ canceled_value = Decimal("13")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ "amountRefunded": {
+ "amount": refunded_value,
+ "currency": "USD",
+ },
+ "amountVoided": {
+ "amount": canceled_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_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["pspReference"] == psp_reference
+ assert data["authorizedAmount"]["amount"] == authorized_value
+ assert data["chargedAmount"]["amount"] == charged_value
+ assert data["refundedAmount"]["amount"] == refunded_value
+ assert data["voidedAmount"]["amount"] == canceled_value
+ assert data["canceledAmount"]["amount"] == canceled_value
+
+ assert transaction.authorized_value == authorized_value
+ assert transaction.charged_value == charged_value
+ assert transaction.canceled_value == canceled_value
+ assert transaction.refunded_value == refunded_value
+
+
+def test_transaction_create_create_event_for_order_by_staff(
+ order_with_lines, permission_manage_payments, staff_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.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,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ },
+ "transaction_event": {
+ "status": transaction_status,
+ "pspReference": transaction_reference,
+ "message": transaction_name,
+ },
+ }
+
+ # when
+ staff_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_missing_permission_by_staff(
+ order_with_lines, staff_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.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,
+ "pspReference": psp_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)
+
+ # then
+ assert_no_permission(response)
+
+
+ "amount_field_name, amount_db_field",
+ [
+ ("amountAuthorized", "authorized_value"),
+ ("amountCharged", "charged_value"),
+ ("amountVoided", "canceled_value"),
+ ("amountCanceled", "canceled_value"),
+ ("amountRefunded", "refunded_value"),
+ ],
+)
+def test_transaction_create_incorrect_currency_by_staff(
+ amount_field_name,
+ amount_db_field,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_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,
+ "pspReference": psp_reference,
+ "availableActions": [],
+ amount_field_name: {
+ "amount": expected_value,
+ "currency": "PLN",
+ },
+ },
+ }
+
+ # when
+ response = staff_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_transaction_create_empty_metadata_key_by_staff(
+ order_with_lines, permission_manage_payments, staff_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "", "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,
+ "pspReference": psp_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
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionCreate"]["transaction"]
+ errors = content["data"]["transactionCreate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionCreateErrorCode.METADATA_KEY_REQUIRED.name
+
+
+def test_transaction_create_empty_private_metadata_key_by_staff(
+ order_with_lines, permission_manage_payments, staff_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "", "value": "321"}
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "pspReference": psp_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
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionCreate"]["transaction"]
+ errors = content["data"]["transactionCreate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionCreateErrorCode.METADATA_KEY_REQUIRED.name
+
+
+def test_creates_transaction_event_for_order_by_staff(
+ order_with_lines, permission_manage_payments, staff_api_client
+):
+ # given
+ status = "Failed authorized for 10$"
+ type = "Credit Card"
+ psp_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 = TransactionEventStatus.FAILURE
+ event_psp_reference = "PSP-ref"
+ event_name = "Failed authorization"
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ "transaction_event": {
+ "status": TransactionEventStatusEnum.FAILURE.name,
+ "pspReference": event_psp_reference,
+ "message": event_name,
+ },
+ }
+
+ # when
+ response = staff_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["message"] == event_name
+ assert event_data["name"] == event_name
+ assert event_data["status"] == TransactionEventStatusEnum.FAILURE.name
+ assert event_data["pspReference"] == event_psp_reference
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(staff_api_client.user)
+ assert event_data["type"] == TransactionEventTypeEnum.INFO.name
+
+ assert transaction.events.count() == 1
+ event = transaction.events.first()
+ assert event.message == event_name
+ assert event.status == event_status
+ assert event.psp_reference == event_psp_reference
+ assert event.user == staff_api_client.user
+ assert event.app_identifier is None
+ assert event.app is None
+ assert event.type == TransactionEventType.INFO
+
+
+def test_creates_transaction_event_for_checkout_by_staff(
+ checkout_with_items, permission_manage_payments, staff_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ event_status = TransactionEventStatus.SUCCESS
+ event_psp_reference = "PSP-ref"
+ event_name = "Failed authorization"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout_with_items.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ "transaction_event": {
+ "status": TransactionEventStatusEnum.SUCCESS.name,
+ "pspReference": event_psp_reference,
+ "message": event_name,
+ },
+ }
+
+ # when
+ response = staff_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) == 2
+ event_data = [
+ event for event in events_data if event["pspReference"] == event_psp_reference
+ ][0]
+ assert event_data["message"] == event_name
+ assert event_data["name"] == event_name
+ assert event_data["status"] == TransactionEventStatusEnum.SUCCESS.name
+ assert event_data["pspReference"] == event_psp_reference
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(staff_api_client.user)
+ assert event_data["type"] == TransactionEventTypeEnum.INFO.name
+
+ assert transaction.events.count() == 2
+ event = transaction.events.exclude(
+ type=TransactionEventType.AUTHORIZATION_SUCCESS
+ ).first()
+ assert event.message == event_name
+ assert event.status == event_status
+ assert event.psp_reference == event_psp_reference
+ assert event.user == staff_api_client.user
+ assert event.app_identifier is None
+ assert event.app is None
+ assert event.type == TransactionEventType.INFO
+
+
+def test_transaction_create_external_url_incorrect_url_format_by_app(
+ order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ authorized_value = Decimal("10")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test", "value": "321"}
+ external_url = "incorrect"
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ "externalUrl": external_url,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionCreate"]["transaction"]
+ errors = content["data"]["transactionCreate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionCreateErrorCode.INVALID.name
+
+
+def test_transaction_create_creates_calculation_events(
+ order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ psp_reference = "PSP reference - 123"
+ available_actions = []
+ authorized_value = Decimal("10")
+ charged_value = Decimal("8")
+ refunded_value = Decimal("5")
+ canceled_value = Decimal("2")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ "amountRefunded": {
+ "amount": refunded_value,
+ "currency": "USD",
+ },
+ "amountCanceled": {
+ "amount": canceled_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ order_with_lines.refresh_from_db()
+ transaction = order_with_lines.payment_transactions.first()
+ assert order_with_lines.total_authorized.amount == authorized_value
+ assert order_with_lines.total_charged.amount == charged_value
+
+ assert transaction.authorized_value == authorized_value
+ assert transaction.charged_value == charged_value
+ assert transaction.refunded_value == refunded_value
+ assert transaction.canceled_value == canceled_value
+
+ assert transaction.events.count() == 4
+ authorize_event = transaction.events.filter(
+ type=TransactionEventType.AUTHORIZATION_SUCCESS
+ ).first()
+ assert authorize_event
+ assert authorize_event.amount.amount == authorized_value
+ charge_event = transaction.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).first()
+ assert charge_event
+ assert charge_event.amount.amount == charged_value
+
+ refund_event = transaction.events.filter(
+ type=TransactionEventType.REFUND_SUCCESS
+ ).first()
+ assert refund_event
+ assert refund_event.amount.amount == refunded_value
+
+ cancel_event = transaction.events.filter(
+ type=TransactionEventType.CANCEL_SUCCESS
+ ).first()
+ assert cancel_event
+ assert cancel_event.amount.amount == canceled_value
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
new file mode 100644
index 0000000000..3365c80bfb
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -0,0 +1,808 @@
+from decimal import Decimal
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from .....payment import TransactionEventType
+from .....payment.models import TransactionEvent
+from .....payment.transaction_item_calculations import recalculate_transaction_amounts
+from ....core.enums import TransactionEventReportErrorCode
+from ....core.utils import to_global_id_or_none
+from ....order.enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnum
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import TransactionActionEnum, TransactionEventTypeEnum
+
+TEST_SERVER_DOMAIN = "testserver.com"
+
+MUTATION_DATA_FRAGMENT = """
+fragment TransactionEventData on TransactionEventReport {
+ alreadyProcessed
+ transaction {
+ id
+ actions
+ events {
+ id
+ }
+ }
+ transactionEvent {
+ id
+ createdAt
+ pspReference
+ message
+ externalUrl
+ amount {
+ currency
+ amount
+ }
+ type
+ createdBy {
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
+ }
+ errors {
+ field
+ code
+ }
+}
+"""
+
+
+def test_transaction_event_report_by_app(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ transaction = transaction_item_generator(
+ app=app_api_client.app, authorized_value=Decimal("10")
+ )
+ event_time = timezone.now()
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+ message = "Sucesfull charge"
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction_id = to_global_id_or_none(transaction)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "time": event_time.isoformat(),
+ "externalUrl": external_url,
+ "message": message,
+ "availableActions": [TransactionActionEnum.REFUND.name],
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ time: $time
+ externalUrl: $externalUrl
+ message: $message
+ availableActions: $availableActions
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_report_data = response["data"]["transactionEventReport"]
+ assert transaction_report_data["alreadyProcessed"] is False
+
+ event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).first()
+ assert event
+ assert event.psp_reference == psp_reference
+ assert event.type == TransactionEventTypeEnum.CHARGE_SUCCESS.value
+ assert event.amount_value == amount
+ assert event.currency == transaction.currency
+ assert event.created_at == event_time
+ assert event.external_url == external_url
+ assert event.transaction == transaction
+ assert event.app_identifier == app_api_client.app.identifier
+ assert event.app == app_api_client.app
+ assert event.user is None
+
+
+def test_transaction_event_report_by_user(
+ staff_api_client, permission_manage_payments, staff_user, transaction_item_generator
+):
+ # given
+ transaction = transaction_item_generator(user=staff_user)
+ event_time = timezone.now()
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+ message = "Sucesfull charge"
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction_id = to_global_id_or_none(transaction)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "time": event_time.isoformat(),
+ "externalUrl": external_url,
+ "message": message,
+ "availableActions": [TransactionActionEnum.CANCEL.name],
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ time: $time
+ externalUrl: $externalUrl
+ message: $message
+ availableActions: $availableActions
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+
+ event = TransactionEvent.objects.get()
+ assert event.psp_reference == psp_reference
+ assert event.type == TransactionEventTypeEnum.CHARGE_SUCCESS.value
+ assert event.amount_value == amount
+ assert event.currency == transaction.currency
+ assert event.created_at == event_time
+ assert event.external_url == external_url
+ assert event.transaction == transaction
+ assert event.app_identifier is None
+ assert event.app is None
+ assert event.user == staff_api_client.user
+
+ transaction.refresh_from_db()
+ assert transaction.available_actions == [TransactionActionEnum.CANCEL.value]
+
+
+def test_transaction_event_report_no_permission(
+ transaction_item_created_by_app,
+ app_api_client,
+):
+ # given
+ transaction_id = to_global_id_or_none(transaction_item_created_by_app)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": Decimal("11.00"),
+ "pspReference": "111-abc",
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query,
+ variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_transaction_event_report_called_by_non_app_owner(
+ transaction_item_created_by_app, app_api_client, permission_manage_payments
+):
+ # given
+ second_app = app_api_client.app
+ second_app.pk = None
+ second_app.identifier = "different-identifier"
+ second_app.save()
+ transaction_item_created_by_app.app_identifier = second_app.identifier
+ transaction_item_created_by_app.app = None
+ transaction_item_created_by_app.save(update_fields=["app_identifier", "app"])
+
+ transaction_id = to_global_id_or_none(transaction_item_created_by_app)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": Decimal("11.00"),
+ "pspReference": "111-abc",
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_transaction_event_report_called_by_non_user_owner(
+ transaction_item_created_by_app, staff_api_client, permission_manage_payments
+):
+ # given
+ transaction_id = to_global_id_or_none(transaction_item_created_by_app)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": Decimal("11.00"),
+ "pspReference": "111-abc",
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_transaction_event_report_event_already_exists(
+ transaction_item_generator, app_api_client, permission_manage_payments, app
+):
+ # given
+ event_time = timezone.now()
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+ message = "Sucesfull charge"
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ event_type = TransactionEventTypeEnum.CHARGE_SUCCESS
+ transaction = transaction_item_generator(app=app, charged_value=amount)
+ transaction.events.update(
+ psp_reference=psp_reference,
+ )
+
+ already_existing_event = transaction.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
+ transaction_id = to_global_id_or_none(transaction)
+ variables = {
+ "id": transaction_id,
+ "type": event_type.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "time": event_time.isoformat(),
+ "externalUrl": external_url,
+ "message": message,
+ "availableActions": [TransactionActionEnum.REFUND.name],
+ }
+
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ time: $time
+ externalUrl: $externalUrl
+ message: $message
+ availableActions: $availableActions
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_report_data = response["data"]["transactionEventReport"]
+ assert transaction_report_data["alreadyProcessed"] is True
+ transaction_event_data = transaction_report_data["transactionEvent"]
+ assert transaction_event_data["id"] == to_global_id_or_none(already_existing_event)
+
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).count()
+ == 1
+ )
+
+
+def test_transaction_event_report_incorrect_amount_for_already_existing(
+ app_api_client, permission_manage_payments, transaction_item_generator, app
+):
+ # given
+ event_time = timezone.now()
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+ message = "Sucesfull charge"
+ psp_reference = "111-abc"
+ already_existing_amount = Decimal("11.00")
+ new_amount = Decimal("12.00")
+ event_type = TransactionEventTypeEnum.CHARGE_SUCCESS
+ transaction = transaction_item_generator(
+ app=app, charged_value=already_existing_amount
+ )
+ transaction.events.update(
+ psp_reference=psp_reference,
+ )
+ transaction_id = to_global_id_or_none(transaction)
+
+ variables = {
+ "id": transaction_id,
+ "type": event_type.name,
+ "amount": new_amount,
+ "pspReference": psp_reference,
+ "time": event_time.isoformat(),
+ "externalUrl": external_url,
+ "message": message,
+ "availableActions": [TransactionActionEnum.REFUND.name],
+ }
+
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ time: $time
+ externalUrl: $externalUrl
+ message: $message
+ availableActions: $availableActions
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ assert already_existing_amount != new_amount
+ transaction_report_data = response["data"]["transactionEventReport"]
+
+ assert len(transaction_report_data["errors"]) == 1
+ error = transaction_report_data["errors"][0]
+ assert error["code"] == TransactionEventReportErrorCode.INCORRECT_DETAILS.name
+ assert error["field"] == "pspReference"
+
+ assert TransactionEvent.objects.count() == 2
+ event = TransactionEvent.objects.filter(
+ type=TransactionEventTypeEnum.CHARGE_FAILURE.value
+ ).first()
+ assert event
+ assert event.include_in_calculations is False
+
+
+@patch(
+ "saleor.graphql.payment.mutations.recalculate_transaction_amounts",
+ wraps=recalculate_transaction_amounts,
+)
+def test_transaction_event_report_calls_amount_recalculations(
+ mocked_recalculation,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ event_time = timezone.now()
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+ message = "Sucesfull charge"
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction = transaction_item_generator(app=app_api_client.app)
+ transaction_id = to_global_id_or_none(transaction)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "time": event_time.isoformat(),
+ "externalUrl": external_url,
+ "message": message,
+ "availableActions": [TransactionActionEnum.REFUND.name],
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ time: $time
+ externalUrl: $externalUrl
+ message: $message
+ availableActions: $availableActions
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ mocked_recalculation.assert_called_once_with(transaction)
+ transaction.refresh_from_db()
+ assert transaction.charged_value == amount
+
+
+def test_transaction_event_updates_order_total_charged(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ current_charged_value = Decimal("20")
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction = transaction_item_generator(app=app_api_client.app, order_id=order.pk)
+ transaction_item_generator(
+ app=app_api_client.app,
+ order_id=order.pk,
+ charged_value=current_charged_value,
+ )
+ transaction_id = to_global_id_or_none(transaction)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ order.refresh_from_db()
+
+ assert order.total_charged.amount == current_charged_value + amount
+ assert order.charge_status == OrderChargeStatusEnum.PARTIAL.value
+
+
+def test_transaction_event_updates_order_total_authorized(
+ app_api_client,
+ permission_manage_payments,
+ order_with_lines,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction = transaction_item_generator(app=app_api_client.app, order_id=order.pk)
+ transaction_item_generator(
+ app=app_api_client.app,
+ order_id=order.pk,
+ authorized_value=order.total.gross.amount,
+ )
+ transaction_id = to_global_id_or_none(transaction)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.AUTHORIZATION_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ order.refresh_from_db()
+
+ assert order.total_authorized.amount == order.total.gross.amount + amount
+ assert order.authorize_status == OrderAuthorizeStatusEnum.FULL.value
+
+
+def test_transaction_event_updates_search_vector(
+ app_api_client,
+ permission_manage_payments,
+ order_with_lines,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction = transaction_item_generator(app=app_api_client.app, order_id=order.pk)
+ transaction_item_generator(
+ app=app_api_client.app,
+ order_id=order.pk,
+ authorized_value=order.total.gross.amount,
+ )
+ transaction_id = to_global_id_or_none(transaction)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.AUTHORIZATION_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ order.refresh_from_db()
+
+ assert order.search_vector
+
+
+def test_transaction_event_report_authorize_event_already_exists(
+ app_api_client, permission_manage_payments, transaction_item_generator
+):
+ # given
+ event_time = timezone.now()
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+ message = "Sucesfull charge"
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ event_type = TransactionEventTypeEnum.AUTHORIZATION_SUCCESS
+ transaction = transaction_item_generator(
+ app=app_api_client.app,
+ authorized_value=amount + Decimal(1),
+ )
+ transaction.events.update(
+ psp_reference="Different psp reference",
+ )
+ transaction_id = to_global_id_or_none(transaction)
+ variables = {
+ "id": transaction_id,
+ "type": event_type.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "time": event_time.isoformat(),
+ "externalUrl": external_url,
+ "message": message,
+ "availableActions": [TransactionActionEnum.REFUND.name],
+ }
+
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ time: $time
+ externalUrl: $externalUrl
+ message: $message
+ availableActions: $availableActions
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_report_data = response["data"]["transactionEventReport"]
+ assert len(transaction_report_data["errors"]) == 1
+ assert transaction_report_data["errors"][0]["field"] == "type"
+ assert (
+ transaction_report_data["errors"][0]["code"]
+ == TransactionEventReportErrorCode.ALREADY_EXISTS.name
+ )
+
+ assert TransactionEvent.objects.count() == 2
+ event = TransactionEvent.objects.filter(
+ type=TransactionEventTypeEnum.AUTHORIZATION_FAILURE.value
+ ).first()
+ assert event
+ assert event.include_in_calculations is False
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
index 2c22fe3976..55514d84fd 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -4,10 +4,12 @@ import graphene
import pytest
from mock import patch
+from .....app.models import App
from .....order import OrderEvents
-from .....payment import TransactionAction
+from .....payment import TransactionAction, TransactionEventType
from .....payment.interface import TransactionActionData
-from .....payment.models import TransactionItem
+from .....payment.models import TransactionEvent, TransactionItem
+from .....webhook.event_types import WebhookEventSyncType
from ....core.enums import TransactionRequestActionErrorCode
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import TransactionActionEnum
@@ -27,6 +29,7 @@ mutation TransactionRequestAction(
id
actions
reference
+ pspReference
type
status
modifiedAt
@@ -78,12 +81,12 @@ def test_transaction_request_charge_action_for_order(
permission_manage_payments,
):
# given
- mocked_is_active.return_value = True
+ mocked_is_active.side_effect = [True, False]
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["charge", "void"],
currency="USD",
order_id=order_with_lines.pk,
@@ -106,20 +109,33 @@ def test_transaction_request_charge_action_for_order(
# then
get_graphql_content(response)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST
+ ).first()
+
assert mocked_is_active.called
+ assert request_event
mocked_payment_action_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CHARGE,
action_value=expected_called_charge_amount,
+ event=request_event,
+ transaction_app_owner=None,
),
channel_slug=order_with_lines.channel.slug,
)
event = order_with_lines.events.first()
- assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED
+ assert event.type == OrderEvents.TRANSACTION_CHARGE_REQUESTED
assert Decimal(event.parameters["amount"]) == expected_called_charge_amount
- assert event.parameters["reference"] == transaction.reference
+ assert event.parameters["reference"] == transaction.psp_reference
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=expected_called_charge_amount,
+ )
@pytest.mark.parametrize(
@@ -142,12 +158,12 @@ def test_transaction_request_refund_action_for_order(
permission_manage_payments,
):
# given
- mocked_is_active.return_value = True
+ mocked_is_active.side_effect = [True, False]
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["refund"],
currency="USD",
order_id=order_with_lines.pk,
@@ -170,12 +186,19 @@ def test_transaction_request_refund_action_for_order(
# then
get_graphql_content(response)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+
+ assert request_event
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,
+ event=request_event,
+ transaction_app_owner=None,
),
channel_slug=order_with_lines.channel.slug,
)
@@ -183,7 +206,13 @@ def test_transaction_request_refund_action_for_order(
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
+ assert event.parameters["reference"] == transaction.psp_reference
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_called_refund_amount,
+ )
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@@ -196,12 +225,12 @@ def test_transaction_request_void_action_for_order(
permission_manage_payments,
):
# given
- mocked_is_active.return_value = True
+ mocked_is_active.side_effect = [True, False]
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["charge", "void"],
currency="USD",
order_id=order_with_lines.pk,
@@ -222,19 +251,31 @@ def test_transaction_request_void_action_for_order(
# then
get_graphql_content(response)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CANCEL_REQUEST,
+ ).first()
+ assert request_event
assert mocked_is_active.called
mocked_payment_action_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.VOID,
action_value=None,
+ event=request_event,
+ transaction_app_owner=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
+ assert event.type == OrderEvents.TRANSACTION_CANCEL_REQUESTED
+ assert event.parameters["reference"] == transaction.psp_reference
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=0,
+ )
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@@ -247,12 +288,12 @@ def test_transaction_request_void_action_for_checkout(
permission_manage_payments,
):
# given
- mocked_is_active.return_value = True
+ mocked_is_active.side_effect = [True, False]
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["charge", "void"],
currency="USD",
checkout_id=checkout.pk,
@@ -273,16 +314,29 @@ def test_transaction_request_void_action_for_checkout(
# then
get_graphql_content(response)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CANCEL_REQUEST,
+ ).first()
+
+ assert request_event
assert mocked_is_active.called
mocked_payment_action_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.VOID,
action_value=None,
+ event=request_event,
+ transaction_app_owner=None,
),
channel_slug=checkout.channel.slug,
)
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=0,
+ )
+
@pytest.mark.parametrize(
"charge_amount, expected_called_charge_amount",
@@ -304,12 +358,12 @@ def test_transaction_request_charge_action_for_checkout(
permission_manage_payments,
):
# given
- mocked_is_active.return_value = True
+ mocked_is_active.side_effect = [True, False]
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["charge", "void"],
currency="USD",
checkout_id=checkout.pk,
@@ -332,16 +386,29 @@ def test_transaction_request_charge_action_for_checkout(
# then
get_graphql_content(response)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST
+ ).first()
+
+ assert request_event
assert mocked_is_active.called
mocked_payment_action_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CHARGE,
action_value=expected_called_charge_amount,
+ event=request_event,
+ transaction_app_owner=None,
),
channel_slug=checkout.channel.slug,
)
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=expected_called_charge_amount,
+ )
+
@pytest.mark.parametrize(
"refund_amount, expected_called_refund_amount",
@@ -363,12 +430,12 @@ def test_transaction_request_refund_action_for_checkout(
permission_manage_payments,
):
# given
- mocked_is_active.return_value = True
+ mocked_is_active.side_effect = [True, False]
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["refund"],
currency="USD",
checkout_id=checkout.pk,
@@ -391,20 +458,33 @@ def test_transaction_request_refund_action_for_checkout(
# then
get_graphql_content(response)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+
+ assert request_event
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,
+ event=request_event,
+ transaction_app_owner=None,
),
channel_slug=checkout.channel.slug,
)
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_called_refund_amount,
+ )
+
@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(
+def test_transaction_action_request_uses_handle_payment_permission(
mocked_payment_action_request,
mocked_is_active,
checkout,
@@ -412,12 +492,12 @@ def test_transaction_request_uses_handle_payment_permission(
permission_manage_payments,
):
# given
- mocked_is_active.return_value = True
+ mocked_is_active.side_effect = [True, False]
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["refund"],
currency="USD",
checkout_id=checkout.pk,
@@ -440,37 +520,670 @@ def test_transaction_request_uses_handle_payment_permission(
# then
get_graphql_content(response)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+
+ assert request_event
assert mocked_is_active.called
mocked_payment_action_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.REFUND,
action_value=refund_amount,
+ event=request_event,
+ transaction_app_owner=None,
),
channel_slug=checkout.channel.slug,
)
+def test_transaction_request_action_missing_permission(
+ app_api_client, order_with_lines
+):
+ # given
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["charge", "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")
-@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
-def test_transaction_request_uses_manage_orders_permission(
+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",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["charge", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=authorization_value,
+ )
+ mocked_is_active.side_effect = [False, 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
+
+
+def transaction_request_webhook(permission_manage_payments):
+ app = App.objects.create(
+ name="Sample app objects",
+ is_active=True,
+ identifier="saleor.app.payment",
+ )
+ app.permissions.set([permission_manage_payments])
+ webhook = app.webhooks.create(
+ name="Request", is_active=True, target_url="http://localhost:8000/endpoint/"
+ )
+
+ return webhook
+
+
+ "charge_amount, expected_called_charge_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_charge_requested")
+def test_transaction_request_charge_for_order(
mocked_payment_action_request,
mocked_is_active,
- order,
+ charge_amount,
+ expected_called_charge_amount,
+ order_with_lines,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+ app,
+):
+ # given
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED
+ )
+ mocked_is_active.return_value = False
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["charge", "void"],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=transaction_request_webhook.app,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.CHARGE.name,
+ "amount": charge_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST,
+ ).first()
+
+ assert request_event
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CHARGE,
+ action_value=expected_called_charge_amount,
+ event=request_event,
+ transaction_app_owner=transaction_request_webhook.app,
+ ),
+ order_with_lines.channel.slug,
+ )
+
+ event = order_with_lines.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CHARGE_REQUESTED
+ assert Decimal(event.parameters["amount"]) == expected_called_charge_amount
+ assert event.parameters["reference"] == transaction.psp_reference
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=expected_called_charge_amount,
+ )
+
+
+ "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_refund_requested")
+def test_transaction_request_refund_for_order(
+ mocked_payment_action_request,
+ mocked_is_active,
+ refund_amount,
+ expected_called_refund_amount,
+ order_with_lines,
app_api_client,
- permission_manage_orders,
+ permission_manage_payments,
+ transaction_request_webhook,
):
# given
- mocked_is_active.return_value = True
+ mocked_is_active.return_value = False
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["refund"],
currency="USD",
- order_id=order.pk,
+ order_id=order_with_lines.pk,
charged_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=transaction_request_webhook.app,
+ )
+
+ 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)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+ assert request_event
+ 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,
+ event=request_event,
+ transaction_app_owner=transaction_request_webhook.app,
+ ),
+ 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.psp_reference
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_called_refund_amount,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_cancelation_requested")
+def test_transaction_request_cancelation_for_order(
+ mocked_payment_action_request,
+ mocked_is_active,
+ order_with_lines,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+):
+ # given
+ mocked_is_active.return_value = False
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED
+ )
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["charge", "void"],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=transaction_request_webhook.app,
+ )
+ 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)
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CANCEL_REQUEST,
+ ).first()
+
+ assert request_event
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CANCEL,
+ action_value=None,
+ event=request_event,
+ transaction_app_owner=transaction_request_webhook.app,
+ ),
+ order_with_lines.channel.slug,
+ )
+
+ event = order_with_lines.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CANCEL_REQUESTED
+ assert event.parameters["reference"] == transaction.psp_reference
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=0,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_cancelation_requested")
+def test_transaction_request_cancelation_for_checkout(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+):
+ # given
+ mocked_is_active.return_value = False
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED
+ )
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["charge", "void"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=transaction_request_webhook.app,
+ )
+ 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)
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CANCEL_REQUEST,
+ ).first()
+
+ assert request_event
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CANCEL,
+ action_value=None,
+ event=request_event,
+ transaction_app_owner=transaction_request_webhook.app,
+ ),
+ checkout.channel.slug,
+ )
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=0,
+ )
+
+
+ "charge_amount, expected_called_charge_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_charge_requested")
+def test_transaction_request_charge_for_checkout(
+ mocked_payment_action_request,
+ mocked_is_active,
+ charge_amount,
+ expected_called_charge_amount,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+):
+ # given
+ mocked_is_active.side_effect = [True, False]
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED
+ )
+
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["charge", "void"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=transaction_request_webhook.app,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "action_type": TransactionActionEnum.CHARGE.name,
+ "amount": charge_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST,
+ ).first()
+
+ assert request_event
+ assert mocked_is_active.called
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CHARGE,
+ action_value=expected_called_charge_amount,
+ event=request_event,
+ transaction_app_owner=transaction_request_webhook.app,
+ ),
+ checkout.channel.slug,
+ )
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=expected_called_charge_amount,
+ )
+
+
+ "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_refund_requested")
+def test_transaction_request_refund_for_checkout(
+ mocked_payment_action_request,
+ mocked_is_active,
+ refund_amount,
+ expected_called_refund_amount,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+):
+ # given
+ mocked_is_active.return_value = False
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ charged_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=transaction_request_webhook.app,
+ )
+
+ 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)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+
+ assert request_event
+ 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,
+ event=request_event,
+ transaction_app_owner=transaction_request_webhook.app,
+ ),
+ checkout.channel.slug,
+ )
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_called_refund_amount,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_refund_when_app_reinstalled(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+):
+ # given
+ refund_amount = Decimal("8.00")
+ expected_called_refund_amount = Decimal("8.00")
+ mocked_is_active.return_value = False
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ charged_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=None,
+ )
+
+ 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)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+
+ assert request_event
+ 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,
+ event=request_event,
+ transaction_app_owner=transaction_request_webhook.app,
+ ),
+ checkout.channel.slug,
+ )
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_called_refund_amount,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_transaction_request_uses_handle_payment_permission(
+ mocked_payment_action_request,
+ mocked_is_active,
+ checkout,
+ app_api_client,
+ permission_manage_payments,
+ transaction_request_webhook,
+):
+ # given
+ mocked_is_active.return_value = False
+
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ checkout_id=checkout.pk,
+ charged_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=transaction_request_webhook.app,
)
refund_amount = Decimal("1")
variables = {
@@ -483,36 +1196,49 @@ def test_transaction_request_uses_manage_orders_permission(
response = app_api_client.post_graphql(
MUTATION_TRANSACTION_REQUEST_ACTION,
variables,
- permissions=[permission_manage_orders],
+ permissions=[permission_manage_payments],
)
# then
get_graphql_content(response)
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST,
+ ).first()
+
+ assert request_event
assert mocked_is_active.called
mocked_payment_action_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.REFUND,
action_value=refund_amount,
+ event=request_event,
+ transaction_app_owner=transaction_request_webhook.app,
),
- channel_slug=order.channel.slug,
+ checkout.channel.slug,
)
-def test_transaction_request_action_missing_permission(
- app_api_client, order_with_lines
+def test_transaction_request_missing_permission(
+ app_api_client, order_with_lines, transaction_request_webhook
):
# given
+ transaction_request_webhook.events.create(
+ event_type=WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED
+ )
+
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["charge", "void"],
currency="USD",
order_id=order_with_lines.pk,
authorized_value=Decimal("10"),
+ app_identifier=transaction_request_webhook.app.identifier,
+ app=transaction_request_webhook.app,
)
variables = {
"id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
@@ -528,21 +1254,31 @@ def test_transaction_request_action_missing_permission(
assert_no_permission(response)
+@patch("saleor.payment.gateway.get_webhooks_for_event")
@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
+def test_transaction_request_missing_event(
+ mocked_is_active,
+ mocked_get_webhooks,
+ staff_api_client,
+ permission_manage_payments,
+ order,
+ app,
):
# given
authorization_value = Decimal("10")
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["charge", "void"],
currency="USD",
order_id=order.pk,
authorized_value=authorization_value,
+ app_identifier=app.identifier,
+ app=app,
)
+
+ mocked_get_webhooks.return_value = []
mocked_is_active.return_value = False
variables = {
@@ -572,3 +1308,8 @@ def test_transaction_request_action_missing_event(
)
assert mocked_is_active.called
+ assert mocked_get_webhooks.called
+ mocked_get_webhooks.assert_called_once_with(
+ event_type=WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED,
+ apps_ids=[app.id],
+ )
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index 27e69d0360..0ae2aa2c28 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -4,12 +4,15 @@ import graphene
import pytest
from .....order import OrderEvents
-from .....order.utils import update_order_authorize_data, update_order_charge_data
-from .....payment import TransactionStatus
+from .....payment import TransactionEventStatus, TransactionEventType
from .....payment.error_codes import TransactionUpdateErrorCode
-from .....payment.models import TransactionItem
+from .....payment.models import TransactionEvent, TransactionItem
+from .....payment.transaction_item_calculations import recalculate_transaction_amounts
+from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...enums import TransactionActionEnum, TransactionStatusEnum
+from ...enums import TransactionActionEnum, TransactionEventStatusEnum
+
+TEST_SERVER_DOMAIN = "testserver.com"
MUTATION_TRANSACTION_UPDATE = """
mutation TransactionUpdate(
@@ -25,11 +28,14 @@ mutation TransactionUpdate(
transaction{
id
actions
- reference
+ pspReference
type
+ name
+ message
status
modifiedAt
createdAt
+ externalUrl
authorizedAmount{
amount
currency
@@ -38,6 +44,10 @@ mutation TransactionUpdate(
currency
amount
}
+ canceledAmount{
+ currency
+ amount
+ }
chargedAmount{
currency
amount
@@ -46,11 +56,34 @@ mutation TransactionUpdate(
currency
amount
}
+ privateMetadata{
+ key
+ value
+ }
+ metadata{
+ key
+ value
+ }
events{
- status
- reference
- name
- createdAt
+ status
+ pspReference
+ name
+ message
+ createdAt
+ externalUrl
+ amount{
+ amount
+ currency
+ }
+ type
+ createdBy{
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
}
}
errors{
@@ -63,23 +96,40 @@ mutation TransactionUpdate(
"""
-def transaction(order_with_lines):
- return TransactionItem.objects.create(
- status="Authorized",
- type="Credit card",
- reference="PSP ref",
- available_actions=["charge", "void"],
- currency="USD",
- order_id=order_with_lines.pk,
- authorized_value=Decimal("10"),
+def test_only_owner_can_update_its_transaction_by_app(
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ app_api_client,
+ external_app,
+):
+ # given
+ transaction = transaction_item_created_by_app
+ transaction.app = None
+ transaction.app_identifier = external_app.identifier
+ transaction.save()
+
+ 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
+ assert_no_permission(response)
+
-def test_transaction_update_status(
- transaction, permission_manage_payments, app_api_client
+def test_transaction_update_status_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
):
# given
+ transaction = transaction_item_created_by_app
status = "Captured for 10$"
variables = {
@@ -99,13 +149,132 @@ def test_transaction_update_status(
content = get_graphql_content(response)
data = content["data"]["transactionUpdate"]["transaction"]
assert data["status"] == status
- assert transaction.status == status
+ assert transaction_item_created_by_app.status == status
+
+
+def test_transaction_update_metadata_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+
+ meta_key = "key-name"
+ meta_value = "key_value"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "metadata": [{"key": meta_key, "value": meta_value}],
+ },
+ }
+
+ # 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 len(data["metadata"]) == 1
+ assert data["metadata"][0]["key"] == meta_key
+ assert data["metadata"][0]["value"] == meta_value
+ assert transaction_item_created_by_app.metadata == {meta_key: meta_value}
+
+
+def test_transaction_update_metadata_incorrect_key_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+
+ meta_key = ""
+ meta_value = "key_value"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "metadata": [{"key": meta_key, "value": meta_value}],
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionUpdate"]["transaction"]
+ errors = content["data"]["transactionUpdate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionUpdateErrorCode.METADATA_KEY_REQUIRED.name
+
+
+def test_transaction_update_private_metadata_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+
+ meta_key = "key-name"
+ meta_value = "key_value"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "privateMetadata": [{"key": meta_key, "value": meta_value}],
+ },
+ }
+
+ # 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 len(data["privateMetadata"]) == 1
+ assert data["privateMetadata"][0]["key"] == meta_key
+ assert data["privateMetadata"][0]["value"] == meta_value
+ assert transaction_item_created_by_app.private_metadata == {meta_key: meta_value}
+
+
+def test_transaction_update_private_metadata_incorrect_key_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+
+ meta_key = ""
+ meta_value = "key_value"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "privateMetadata": [{"key": meta_key, "value": meta_value}],
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionUpdate"]["transaction"]
+ errors = content["data"]["transactionUpdate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionUpdateErrorCode.METADATA_KEY_REQUIRED.name
-def test_transaction_update_type(
- transaction, permission_manage_payments, app_api_client
+def test_transaction_update_type_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
):
# given
+ transaction = transaction_item_created_by_app
type = "New credit card"
variables = {
@@ -125,19 +294,76 @@ def test_transaction_update_type(
content = get_graphql_content(response)
data = content["data"]["transactionUpdate"]["transaction"]
assert data["type"] == type
- assert transaction.type == type
+ assert data["name"] == type
+ assert transaction.name == type
-def test_transaction_update_reference(
- transaction, permission_manage_payments, app_api_client
+def test_transaction_update_name_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
):
# given
- reference = "PSP:123AAA"
+ transaction = transaction_item_created_by_app
+ name = "New credit card"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "name": name,
+ },
+ }
+
+ # 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["name"] == name
+ assert data["type"] == name
+ assert transaction.name == name
+
+
+def test_transaction_update_message_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+ message = "Message"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "message": message,
+ },
+ }
+
+ # 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["message"] == message
+ assert transaction.message == message
+
+
+def test_transaction_update_psp_reference_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ psp_peference = "PSP:123AAA"
+ transaction = transaction_item_created_by_app
variables = {
"id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
"transaction": {
- "reference": reference,
+ "pspReference": psp_peference,
},
}
@@ -150,14 +376,17 @@ def test_transaction_update_reference(
transaction.refresh_from_db()
content = get_graphql_content(response)
data = content["data"]["transactionUpdate"]["transaction"]
- assert data["reference"] == reference
- assert transaction.reference == reference
+ assert data["pspReference"] == psp_peference
+ assert transaction.psp_reference == psp_peference
+ assert transaction.order
+ assert transaction.order.search_vector
-def test_transaction_update_available_actions(
- transaction, permission_manage_payments, app_api_client
+def test_transaction_update_available_actions_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
):
# given
+ transaction = transaction_item_created_by_app
available_actions = [TransactionActionEnum.REFUND.name]
variables = {
@@ -185,20 +414,36 @@ def test_transaction_update_available_actions(
[
("amountAuthorized", "authorizedAmount", "authorized_value", Decimal("12")),
("amountCharged", "chargedAmount", "charged_value", Decimal("13")),
- ("amountVoided", "voidedAmount", "voided_value", Decimal("14")),
+ ("amountCanceled", "canceledAmount", "canceled_value", Decimal("14")),
+ ("amountVoided", "voidedAmount", "canceled_value", Decimal("14")),
("amountRefunded", "refundedAmount", "refunded_value", Decimal("15")),
],
)
-def test_transaction_update_amounts(
+def test_transaction_update_amounts_by_app(
field_name,
response_field,
db_field_name,
value,
- transaction,
permission_manage_payments,
app_api_client,
+ transaction_item_generator,
+ order,
+ app,
):
# given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ current_refunded_value = Decimal("3")
+ current_canceled_value = Decimal("4")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ canceled_value=current_canceled_value,
+ refunded_value=current_refunded_value,
+ )
variables = {
"id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
@@ -216,25 +461,49 @@ def test_transaction_update_amounts(
data = content["data"]["transactionUpdate"]["transaction"]
assert data[response_field]["amount"] == value
assert getattr(transaction, db_field_name) == value
-
-
-def test_transaction_update_for_order_increases_order_total_authorized(
+ provided_amounts = {
+ "authorized_value": current_authorized_value,
+ "charged_value": current_charged_value,
+ "refunded_value": current_refunded_value,
+ "canceled_value": current_canceled_value,
+ "authorize_pending_value": Decimal(0),
+ "charge_pending_value": Decimal(0),
+ "refund_pending_value": Decimal(0),
+ "cancel_pending_value": Decimal(0),
+ }
+ provided_amounts[db_field_name] = value
+ assert sum(
+ [
+ transaction.authorized_value,
+ transaction.charged_value,
+ transaction.refunded_value,
+ transaction.canceled_value,
+ transaction.authorize_pending_value,
+ transaction.charge_pending_value,
+ transaction.refund_pending_value,
+ transaction.cancel_pending_value,
+ ]
+ ) == sum(provided_amounts.values())
+
+
+def test_transaction_update_for_order_increases_order_total_authorized_by_app(
order_with_lines,
permission_manage_payments,
app_api_client,
- transaction,
+ transaction_item_generator,
+ app,
):
# given
- previously_authorized_value = Decimal("90")
- old_transaction = order_with_lines.payment_transactions.create(
- authorized_value=previously_authorized_value, currency=order_with_lines.currency
- )
- update_order_authorize_data(
- order_with_lines,
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ authorized_value=Decimal("10"),
)
- assert (
- order_with_lines.total_authorized_amount
- == previously_authorized_value + transaction.authorized_value
+ previously_authorized_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ authorized_value=previously_authorized_value,
)
authorized_value = transaction.authorized_value + Decimal("10")
@@ -256,9 +525,7 @@ def test_transaction_update_for_order_increases_order_total_authorized(
# then
order_with_lines.refresh_from_db()
- transaction = order_with_lines.payment_transactions.exclude(
- id=old_transaction.id
- ).last()
+ transaction.refresh_from_db()
content = get_graphql_content(response)
data = content["data"]["transactionUpdate"]["transaction"]
@@ -270,21 +537,24 @@ def test_transaction_update_for_order_increases_order_total_authorized(
assert authorized_value == transaction.authorized_value
-def test_transaction_update_for_order_reduces_order_total_authorized(
+def test_transaction_update_for_order_reduces_order_total_authorized_by_app(
order_with_lines,
permission_manage_payments,
app_api_client,
- transaction,
+ transaction_item_generator,
+ app,
):
# given
- previously_authorized_value = Decimal("90")
- old_transaction = order_with_lines.payment_transactions.create(
- authorized_value=previously_authorized_value, currency=order_with_lines.currency
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ authorized_value=Decimal("10"),
)
- update_order_authorize_data(order_with_lines)
- assert (
- order_with_lines.total_authorized_amount
- == previously_authorized_value + transaction.authorized_value
+ previously_authorized_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ authorized_value=previously_authorized_value,
)
authorized_value = transaction.authorized_value - Decimal("5")
@@ -306,9 +576,7 @@ def test_transaction_update_for_order_reduces_order_total_authorized(
# then
order_with_lines.refresh_from_db()
- transaction = order_with_lines.payment_transactions.exclude(
- id=old_transaction.id
- ).last()
+ transaction.refresh_from_db()
content = get_graphql_content(response)
data = content["data"]["transactionUpdate"]["transaction"]
@@ -320,21 +588,24 @@ def test_transaction_update_for_order_reduces_order_total_authorized(
assert authorized_value == transaction.authorized_value
-def test_transaction_update_for_order_reduces_transaction_authorized_amount_to_zero(
+def test_transaction_update_for_order_reduces_transaction_authorized_to_zero_by_app(
order_with_lines,
permission_manage_payments,
app_api_client,
- transaction,
+ app,
+ transaction_item_generator,
):
# given
- previously_authorized_value = Decimal("90")
- old_transaction = order_with_lines.payment_transactions.create(
- authorized_value=previously_authorized_value, currency=order_with_lines.currency
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ authorized_value=Decimal("10"),
)
- update_order_authorize_data(order_with_lines)
- assert (
- order_with_lines.total_authorized_amount
- == previously_authorized_value + transaction.authorized_value
+ previously_authorized_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ authorized_value=previously_authorized_value,
)
authorized_value = Decimal("0")
@@ -356,9 +627,7 @@ def test_transaction_update_for_order_reduces_transaction_authorized_amount_to_z
# then
order_with_lines.refresh_from_db()
- transaction = order_with_lines.payment_transactions.exclude(
- id=old_transaction.id
- ).last()
+ transaction.refresh_from_db()
content = get_graphql_content(response)
data = content["data"]["transactionUpdate"]["transaction"]
@@ -367,19 +636,24 @@ def test_transaction_update_for_order_reduces_transaction_authorized_amount_to_z
assert authorized_value == transaction.authorized_value
-def test_transaction_update_for_order_increases_order_total_charged(
- order_with_lines, permission_manage_payments, app_api_client, transaction
+def test_transaction_update_for_order_increases_order_total_charged_by_app(
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ app,
):
# given
- previously_charged_value = Decimal("90")
- old_transaction = order_with_lines.payment_transactions.create(
- charged_value=previously_charged_value, currency=order_with_lines.currency
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ charged_value=Decimal("10"),
)
-
- update_order_charge_data(order_with_lines)
- assert (
- order_with_lines.total_charged_amount
- == previously_charged_value + transaction.charged_value
+ previously_charged_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ charged_value=previously_charged_value,
)
charged_value = transaction.charged_value + Decimal("10")
@@ -401,9 +675,7 @@ def test_transaction_update_for_order_increases_order_total_charged(
# then
order_with_lines.refresh_from_db()
- transaction = order_with_lines.payment_transactions.exclude(
- id=old_transaction.id
- ).last()
+ transaction.refresh_from_db()
content = get_graphql_content(response)
data = content["data"]["transactionUpdate"]["transaction"]
assert data["chargedAmount"]["amount"] == charged_value
@@ -414,21 +686,24 @@ def test_transaction_update_for_order_increases_order_total_charged(
assert charged_value == transaction.charged_value
-def test_transaction_update_for_order_reduces_order_total_charged(
- order_with_lines, permission_manage_payments, app_api_client, transaction
+def test_transaction_update_for_order_reduces_order_total_charged_by_app(
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ app,
):
# given
- previously_charged_value = Decimal("90")
- old_transaction = order_with_lines.payment_transactions.create(
- charged_value=previously_charged_value, currency=order_with_lines.currency
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ charged_value=Decimal("30"),
)
- transaction.charged_value = Decimal("30")
- transaction.save()
-
- update_order_charge_data(order_with_lines)
- assert (
- order_with_lines.total_charged_amount
- == previously_charged_value + transaction.charged_value
+ previously_charged_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ charged_value=previously_charged_value,
)
charged_value = transaction.charged_value - Decimal("5")
@@ -450,9 +725,7 @@ def test_transaction_update_for_order_reduces_order_total_charged(
# then
order_with_lines.refresh_from_db()
- transaction = order_with_lines.payment_transactions.exclude(
- id=old_transaction.id
- ).last()
+ transaction.refresh_from_db()
content = get_graphql_content(response)
data = content["data"]["transactionUpdate"]["transaction"]
assert data["chargedAmount"]["amount"] == charged_value
@@ -463,21 +736,24 @@ def test_transaction_update_for_order_reduces_order_total_charged(
assert charged_value == transaction.charged_value
-def test_transaction_update_for_order_reduces_transaction_charged_amount_to_zero(
- order_with_lines, permission_manage_payments, app_api_client, transaction
+def test_transaction_update_for_order_reduces_transaction_charged_to_zero_by_app(
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ app,
):
# given
- previously_charged_value = Decimal("90")
- old_transaction = order_with_lines.payment_transactions.create(
- charged_value=previously_charged_value, currency=order_with_lines.currency
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ charged_value=Decimal("30"),
)
- transaction.charged_value = Decimal("30")
- transaction.save()
-
- update_order_charge_data(order_with_lines)
- assert (
- order_with_lines.total_charged_amount
- == previously_charged_value + transaction.charged_value
+ previously_charged_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ charged_value=previously_charged_value,
)
charged_value = Decimal("0")
@@ -499,9 +775,7 @@ def test_transaction_update_for_order_reduces_transaction_charged_amount_to_zero
# then
order_with_lines.refresh_from_db()
- transaction = order_with_lines.payment_transactions.exclude(
- id=old_transaction.id
- ).last()
+ transaction.refresh_from_db()
content = get_graphql_content(response)
data = content["data"]["transactionUpdate"]["transaction"]
assert data["chargedAmount"]["amount"] == charged_value
@@ -509,14 +783,23 @@ def test_transaction_update_for_order_reduces_transaction_charged_amount_to_zero
assert charged_value == transaction.charged_value
-def test_transaction_update_multiple_amounts_provided(
- transaction, permission_manage_payments, app_api_client
+def test_transaction_update_multiple_amounts_provided_by_app(
+ permission_manage_payments, app_api_client, order, transaction_item_generator, app
):
# given
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=app,
+ charged_value=Decimal("1"),
+ authorized_value=Decimal("2"),
+ refunded_value=Decimal("3"),
+ canceled_value=Decimal("4"),
+ )
+
authorized_value = Decimal("10")
charged_value = Decimal("11")
refunded_value = Decimal("12")
- voided_value = Decimal("13")
+ canceled_value = Decimal("13")
variables = {
"id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
@@ -533,8 +816,8 @@ def test_transaction_update_multiple_amounts_provided(
"amount": refunded_value,
"currency": "USD",
},
- "amountVoided": {
- "amount": voided_value,
+ "amountCanceled": {
+ "amount": canceled_value,
"currency": "USD",
},
},
@@ -552,42 +835,21 @@ def test_transaction_update_multiple_amounts_provided(
assert data["authorizedAmount"]["amount"] == authorized_value
assert data["chargedAmount"]["amount"] == charged_value
assert data["refundedAmount"]["amount"] == refunded_value
- assert data["voidedAmount"]["amount"] == voided_value
+ assert data["voidedAmount"]["amount"] == canceled_value
+ assert data["canceledAmount"]["amount"] == canceled_value
+ assert transaction
assert transaction.authorized_value == authorized_value
assert transaction.charged_value == charged_value
- assert transaction.voided_value == voided_value
+ assert transaction.canceled_value == canceled_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
+def test_transaction_update_for_order_missing_permission_by_app(
+ transaction_item_created_by_app, app_api_client
):
# given
+ transaction = transaction_item_created_by_app
status = "Authorized for 10$"
type = "Credit Card"
@@ -611,18 +873,20 @@ def test_transaction_update_for_order_missing_app_permission(
[
("amountAuthorized", "authorized_value"),
("amountCharged", "charged_value"),
- ("amountVoided", "voided_value"),
+ ("amountVoided", "canceled_value"),
+ ("amountCanceled", "canceled_value"),
("amountRefunded", "refunded_value"),
],
)
-def test_transaction_update_incorrect_currency(
+def test_transaction_update_incorrect_currency_by_app(
amount_field_name,
amount_db_field,
- transaction,
+ transaction_item_created_by_app,
permission_manage_payments,
app_api_client,
):
# given
+ transaction = transaction_item_created_by_app
expected_value = Decimal("10")
variables = {
@@ -649,10 +913,14 @@ def test_transaction_update_incorrect_currency(
)
-def test_transaction_update_adds_transaction_event_to_order(
- transaction, order_with_lines, permission_manage_payments, app_api_client
+def test_transaction_update_adds_transaction_event_to_order_by_app(
+ transaction_item_created_by_app,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
):
# given
+ transaction = transaction_item_created_by_app
transaction_status = "PENDING"
transaction_reference = "transaction reference"
transaction_name = "Processing transaction"
@@ -661,8 +929,8 @@ def test_transaction_update_adds_transaction_event_to_order(
"id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
"transaction_event": {
"status": transaction_status,
- "reference": transaction_reference,
- "name": transaction_name,
+ "pspReference": transaction_reference,
+ "message": transaction_name,
},
}
@@ -684,20 +952,24 @@ def test_transaction_update_adds_transaction_event_to_order(
}
-def test_creates_transaction_event_for_order(
- transaction, order_with_lines, permission_manage_payments, app_api_client
+def test_creates_transaction_event_for_order_by_app(
+ transaction_item_created_by_app,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
):
# given
+
transaction = order_with_lines.payment_transactions.first()
- event_status = TransactionStatus.FAILURE
+ event_status = TransactionEventStatus.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,
+ "status": TransactionEventStatusEnum.FAILURE.name,
+ "pspReference": event_reference,
+ "message": event_name,
},
}
@@ -711,14 +983,1497 @@ def test_creates_transaction_event_for_order(
data = content["data"]["transactionUpdate"]["transaction"]
events_data = data["events"]
- assert len(events_data) == 1
- event_data = events_data[0]
+ assert len(events_data) == 2
+ event_data = [
+ event for event in events_data if event["pspReference"] == event_reference
+ ][0]
+ assert event_data["message"] == event_name
assert event_data["name"] == event_name
- assert event_data["status"] == TransactionStatusEnum.FAILURE.name
- assert event_data["reference"] == event_reference
+ assert event_data["status"] == TransactionEventStatusEnum.FAILURE.name
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(app_api_client.app)
- assert transaction.events.count() == 1
- event = transaction.events.first()
- assert event.name == event_name
+ assert transaction.events.count() == 2
+ event = transaction.events.filter(psp_reference=event_reference).first()
+ assert event.message == event_name
assert event.status == event_status
- assert event.reference == event_reference
+ assert event.app_identifier == app_api_client.app.identifier
+ assert event.user is None
+
+
+def test_creates_transaction_event_by_reinstalled_app(
+ transaction_item_created_by_app,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ transaction_item_created_by_app.app = None
+ transaction_item_created_by_app.save()
+
+ transaction = order_with_lines.payment_transactions.first()
+ event_status = TransactionEventStatus.FAILURE
+ event_reference = "PSP-ref"
+ event_name = "Failed authorization"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction_event": {
+ "status": TransactionEventStatusEnum.FAILURE.name,
+ "pspReference": event_reference,
+ "message": event_name,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+
+ assert transaction.events.count() == 2
+ event = transaction.events.filter(psp_reference=event_reference).first()
+ assert event.message == event_name
+ assert event.status == event_status
+ assert event.app_identifier == app_api_client.app.identifier
+ assert event.user is None
+
+
+def test_only_owner_can_update_its_transaction_by_staff(
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ transaction = transaction_item_created_by_app
+
+ status = "Captured for 10$"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "status": status,
+ },
+ }
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_transaction_update_status_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+ status = "Captured for 10$"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "status": status,
+ },
+ }
+
+ # when
+ response = staff_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_item_created_by_user.status == status
+
+
+def test_transaction_update_metadata_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+
+ meta_key = "key-name"
+ meta_value = "key_value"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "metadata": [{"key": meta_key, "value": meta_value}],
+ },
+ }
+
+ # when
+ response = staff_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 len(data["metadata"]) == 1
+ assert data["metadata"][0]["key"] == meta_key
+ assert data["metadata"][0]["value"] == meta_value
+ assert transaction.metadata == {meta_key: meta_value}
+
+
+def test_transaction_update_metadata_incorrect_key_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+
+ meta_key = ""
+ meta_value = "key_value"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "metadata": [{"key": meta_key, "value": meta_value}],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionUpdate"]["transaction"]
+ errors = content["data"]["transactionUpdate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionUpdateErrorCode.METADATA_KEY_REQUIRED.name
+
+
+def test_transaction_update_private_metadata_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+
+ meta_key = "key-name"
+ meta_value = "key_value"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "privateMetadata": [{"key": meta_key, "value": meta_value}],
+ },
+ }
+
+ # when
+ response = staff_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 len(data["privateMetadata"]) == 1
+ assert data["privateMetadata"][0]["key"] == meta_key
+ assert data["privateMetadata"][0]["value"] == meta_value
+ assert transaction.private_metadata == {meta_key: meta_value}
+
+
+def test_transaction_update_private_metadata_incorrect_key_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+
+ meta_key = ""
+ meta_value = "key_value"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "privateMetadata": [{"key": meta_key, "value": meta_value}],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionUpdate"]["transaction"]
+ errors = content["data"]["transactionUpdate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionUpdateErrorCode.METADATA_KEY_REQUIRED.name
+
+
+def test_transaction_update_type_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+ type = "New credit card"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "type": type,
+ },
+ }
+
+ # when
+ response = staff_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 data["name"] == type
+ assert transaction.name == type
+
+
+def test_transaction_update_name_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+ name = "New credit card"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "name": name,
+ },
+ }
+
+ # when
+ response = staff_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"] == name
+ assert data["name"] == name
+ assert transaction.name == name
+
+
+def test_transaction_update_message_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+ message = "Message"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "message": message,
+ },
+ }
+
+ # when
+ response = staff_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["message"] == message
+ assert transaction.message == message
+
+
+def test_transaction_update_psp_reference_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ reference = "PSP:123AAA"
+ transaction = transaction_item_created_by_user
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "pspReference": reference,
+ },
+ }
+
+ # when
+ response = staff_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["pspReference"] == reference
+ assert transaction.psp_reference == reference
+
+
+def test_transaction_update_available_actions_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+ available_actions = [TransactionActionEnum.REFUND.name]
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "availableActions": available_actions,
+ },
+ }
+
+ # when
+ response = staff_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")),
+ ("amountCharged", "chargedAmount", "charged_value", Decimal("13")),
+ ("amountVoided", "voidedAmount", "canceled_value", Decimal("14")),
+ ("amountCanceled", "canceledAmount", "canceled_value", Decimal("14")),
+ ("amountRefunded", "refundedAmount", "refunded_value", Decimal("15")),
+ ],
+)
+def test_transaction_update_amounts_by_staff(
+ field_name,
+ response_field,
+ db_field_name,
+ value,
+ permission_manage_payments,
+ staff_api_client,
+ transaction_item_generator,
+ staff_user,
+):
+ # given
+ transaction = transaction_item_generator(user=staff_user)
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {field_name: {"amount": value, "currency": "USD"}},
+ }
+
+ # when
+ response = staff_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_for_order_increases_order_total_authorized_by_staff(
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+ transaction_item_generator,
+ staff_user,
+):
+ # given
+ previously_authorized_value = Decimal("90")
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ authorized_value=Decimal("10"),
+ )
+ previously_authorized_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ authorized_value=previously_authorized_value,
+ )
+
+ authorized_value = transaction.authorized_value + Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["authorizedAmount"]["amount"] == authorized_value
+ assert (
+ order_with_lines.total_authorized_amount
+ == previously_authorized_value + authorized_value
+ )
+ assert authorized_value == transaction.authorized_value
+
+
+def test_transaction_update_for_order_reduces_order_total_authorized_by_staff(
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+ transaction_item_generator,
+ staff_user,
+):
+ # given
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ authorized_value=Decimal("10"),
+ )
+ previously_authorized_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ authorized_value=previously_authorized_value,
+ )
+
+ authorized_value = transaction.authorized_value - Decimal("5")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["authorizedAmount"]["amount"] == authorized_value
+ assert (
+ order_with_lines.total_authorized_amount
+ == previously_authorized_value + authorized_value
+ )
+ assert authorized_value == transaction.authorized_value
+
+
+def test_transaction_update_for_order_reduces_transaction_authorized_to_zero_by_staff(
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+ transaction_item_created_by_user,
+ transaction_item_generator,
+ staff_user,
+):
+ # given
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ authorized_value=Decimal("10"),
+ )
+ previously_authorized_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ authorized_value=previously_authorized_value,
+ )
+
+ authorized_value = Decimal("0")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["authorizedAmount"]["amount"] == authorized_value
+ assert order_with_lines.total_authorized_amount == previously_authorized_value
+ assert authorized_value == transaction.authorized_value
+
+
+def test_transaction_update_for_order_increases_order_total_charged_by_staff(
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+ transaction_item_generator,
+ staff_user,
+):
+ # given
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ charged_value=Decimal("10"),
+ )
+ previously_charged_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ charged_value=previously_charged_value,
+ )
+ charged_value = transaction.charged_value + Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["chargedAmount"]["amount"] == charged_value
+ assert (
+ order_with_lines.total_charged_amount
+ == previously_charged_value + charged_value
+ )
+ assert charged_value == transaction.charged_value
+
+
+def test_transaction_update_for_order_reduces_order_total_charged_by_staff(
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+ transaction_item_generator,
+ staff_user,
+):
+ # given
+
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ charged_value=Decimal("30"),
+ )
+ previously_charged_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ charged_value=previously_charged_value,
+ )
+ charged_value = transaction.charged_value - Decimal("5")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["chargedAmount"]["amount"] == charged_value
+ assert (
+ order_with_lines.total_charged_amount
+ == previously_charged_value + charged_value
+ )
+ assert charged_value == transaction.charged_value
+
+
+def test_transaction_update_for_order_reduces_transaction_charged_to_zero_by_staff(
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+ transaction_item_generator,
+ staff_user,
+):
+ # given
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ charged_value=Decimal("30"),
+ )
+ previously_charged_value = Decimal("90")
+ transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ charged_value=previously_charged_value,
+ )
+
+ charged_value = Decimal("0")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["chargedAmount"]["amount"] == charged_value
+ assert order_with_lines.total_charged_amount == previously_charged_value
+ assert charged_value == transaction.charged_value
+
+
+def test_transaction_update_multiple_amounts_provided_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+ authorized_value = Decimal("10")
+ charged_value = Decimal("11")
+ refunded_value = Decimal("12")
+ canceled_value = Decimal("13")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ "amountRefunded": {
+ "amount": refunded_value,
+ "currency": "USD",
+ },
+ "amountCanceled": {
+ "amount": canceled_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_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["chargedAmount"]["amount"] == charged_value
+ assert data["refundedAmount"]["amount"] == refunded_value
+ assert data["voidedAmount"]["amount"] == canceled_value
+ assert data["canceledAmount"]["amount"] == canceled_value
+
+ assert transaction
+ assert transaction.authorized_value == authorized_value
+ assert transaction.charged_value == charged_value
+ assert transaction.canceled_value == canceled_value
+ assert transaction.refunded_value == refunded_value
+
+
+def test_transaction_update_for_order_missing_permission_by_staff(
+ transaction_item_created_by_user, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+ 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)
+
+ # then
+ assert_no_permission(response)
+
+
+ "amount_field_name, amount_db_field",
+ [
+ ("amountAuthorized", "authorized_value"),
+ ("amountCharged", "charged_value"),
+ ("amountVoided", "canceled_value"),
+ ("amountCanceled", "canceled_value"),
+ ("amountRefunded", "refunded_value"),
+ ],
+)
+def test_transaction_update_incorrect_currency_by_staff(
+ amount_field_name,
+ amount_db_field,
+ transaction_item_created_by_user,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ transaction = transaction_item_created_by_user
+ 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 = staff_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_by_staff(
+ transaction_item_created_by_user,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ transaction = transaction_item_created_by_user
+ 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,
+ "pspReference": transaction_reference,
+ "message": transaction_name,
+ },
+ }
+
+ # when
+ response = staff_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_by_staff(
+ transaction_item_created_by_user,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+
+ transaction = order_with_lines.payment_transactions.first()
+ event_status = TransactionEventStatus.FAILURE
+ event_reference = "PSP-ref"
+ event_name = "Failed authorization"
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction_event": {
+ "status": TransactionEventStatusEnum.FAILURE.name,
+ "pspReference": event_reference,
+ "name": event_name,
+ },
+ }
+
+ # when
+ response = staff_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) == 2
+ event_data = [
+ event for event in events_data if event["pspReference"] == event_reference
+ ][0]
+ assert event_data["message"] == event_name
+ assert event_data["name"] == event_name
+ assert event_data["status"] == TransactionEventStatusEnum.FAILURE.name
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(staff_api_client.user)
+
+ assert transaction.events.count() == 2
+ event = transaction.events.filter(psp_reference=event_reference).first()
+ assert event.message == event_name
+ assert event.status == event_status
+ assert event.psp_reference == event_reference
+ assert event.app_identifier is None
+ assert event.user == staff_api_client.user
+
+
+def test_transaction_raises_error_when_psp_reference_already_exists_by_staff(
+ transaction_item_generator,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+ staff_user,
+):
+ # given
+ psp_reference = "psp-ref"
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk, user=staff_user, psp_reference=psp_reference
+ )
+ second_transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ user=staff_user,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", second_transaction.pk),
+ "transaction": {
+ "pspReference": psp_reference,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ transaction = content["data"]["transactionUpdate"]["transaction"]
+ errors = content["data"]["transactionUpdate"]["errors"]
+
+ assert not transaction
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionUpdateErrorCode.UNIQUE.name
+ assert error["field"] == "transaction"
+
+ assert order_with_lines.payment_transactions.count() == 2
+ assert TransactionEvent.objects.count() == 0
+
+
+def test_transaction_raises_error_when_psp_reference_already_exists_by_app(
+ transaction_item_generator,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+ app,
+):
+ # given
+
+ psp_reference = "psp-ref"
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk, app=app, psp_reference=psp_reference
+ )
+ second_transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ )
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", second_transaction.pk),
+ "transaction": {
+ "pspReference": psp_reference,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ transaction = content["data"]["transactionUpdate"]["transaction"]
+ errors = content["data"]["transactionUpdate"]["errors"]
+
+ assert not transaction
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionUpdateErrorCode.UNIQUE.name
+ assert error["field"] == "transaction"
+
+ assert order_with_lines.payment_transactions.count() == 2
+ assert TransactionEvent.objects.count() == 0
+
+
+def test_transaction_update_external_url_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "externalUrl": external_url,
+ },
+ }
+
+ # 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["externalUrl"] == external_url
+ assert transaction_item_created_by_app.external_url == external_url
+
+
+def test_transaction_update_external_url_incorrect_url_format_by_app(
+ transaction_item_created_by_app, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_created_by_app
+ external_url = "incorrect"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "externalUrl": external_url,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionUpdate"]["transaction"]
+ errors = content["data"]["transactionUpdate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionUpdateErrorCode.INVALID.name
+
+
+def test_transaction_update_external_url_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "externalUrl": external_url,
+ },
+ }
+
+ # when
+ response = staff_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["externalUrl"] == external_url
+ assert transaction_item_created_by_user.external_url == external_url
+
+
+def test_transaction_update_external_url_incorrect_url_format_by_staff(
+ transaction_item_created_by_user, permission_manage_payments, staff_api_client
+):
+ # given
+ transaction = transaction_item_created_by_user
+ external_url = "incorrect"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "externalUrl": external_url,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ assert not content["data"]["transactionUpdate"]["transaction"]
+ errors = content["data"]["transactionUpdate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionUpdateErrorCode.INVALID.name
+
+
+def test_transaction_update_creates_calculation_event(
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ order,
+ app,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ current_canceled_value = Decimal("3")
+ current_refunded_value = Decimal("4")
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ canceled_value=current_canceled_value,
+ refunded_value=current_refunded_value,
+ )
+ authorized_value = Decimal("20")
+ charged_value = Decimal("17")
+ canceled_value = Decimal("14")
+ refunded_value = Decimal("15")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ "amountRefunded": {
+ "amount": refunded_value,
+ "currency": "USD",
+ },
+ "amountCanceled": {
+ "amount": canceled_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ get_graphql_content(response)
+
+ order.refresh_from_db()
+ transaction = order.payment_transactions.first()
+ assert order.total_authorized.amount == authorized_value
+ assert order.total_charged.amount == charged_value
+
+ assert transaction.authorized_value == authorized_value
+ assert transaction.charged_value == charged_value
+ assert transaction.refunded_value == refunded_value
+ assert transaction.canceled_value == canceled_value
+
+ # 4 existing events and 4 newly created for new amounts
+ assert transaction.events.count() == 8
+
+ authorize_event = transaction.events.filter(
+ type=TransactionEventType.AUTHORIZATION_ADJUSTMENT,
+ amount_value=authorized_value,
+ ).first()
+ assert authorize_event
+
+ charge_event = transaction.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS,
+ amount_value=charged_value - current_charged_value,
+ ).first()
+ assert charge_event
+
+ refund_event = transaction.events.filter(
+ type=TransactionEventType.REFUND_SUCCESS,
+ amount_value=refunded_value - current_refunded_value,
+ ).first()
+ assert refund_event
+
+ cancel_event = transaction.events.filter(
+ type=TransactionEventType.CANCEL_SUCCESS,
+ amount_value=canceled_value - current_canceled_value,
+ ).first()
+ assert cancel_event
+
+
+ "field_name, response_field, db_field_name, value, current_authorized_value, "
+ "current_charged_value, current_canceled_value, current_refunded_value,",
+ [
+ (
+ "amountAuthorized",
+ "authorizedAmount",
+ "authorized_value",
+ Decimal("12"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountAuthorized",
+ "authorizedAmount",
+ "authorized_value",
+ Decimal("12"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ ),
+ (
+ "amountAuthorized",
+ "authorizedAmount",
+ "authorized_value",
+ Decimal("12"),
+ Decimal("0"),
+ Decimal("3"),
+ Decimal("1"),
+ Decimal("0"),
+ ),
+ (
+ "amountAuthorized",
+ "authorizedAmount",
+ "authorized_value",
+ Decimal("12"),
+ Decimal("100"),
+ Decimal("3"),
+ Decimal("1"),
+ Decimal("0"),
+ ),
+ (
+ "amountAuthorized",
+ "authorizedAmount",
+ "authorized_value",
+ Decimal("0"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountAuthorized",
+ "authorizedAmount",
+ "authorized_value",
+ Decimal("1"),
+ Decimal("3"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountCharged",
+ "chargedAmount",
+ "charged_value",
+ Decimal("13"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountCharged",
+ "chargedAmount",
+ "charged_value",
+ Decimal("13"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ ),
+ (
+ "amountCharged",
+ "chargedAmount",
+ "charged_value",
+ Decimal("13"),
+ Decimal("0"),
+ Decimal("200"),
+ Decimal("0"),
+ Decimal("0"),
+ ),
+ (
+ "amountCharged",
+ "chargedAmount",
+ "charged_value",
+ Decimal("0"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountCanceled",
+ "canceledAmount",
+ "canceled_value",
+ Decimal("1"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountCanceled",
+ "canceledAmount",
+ "canceled_value",
+ Decimal("14"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountCanceled",
+ "canceledAmount",
+ "canceled_value",
+ Decimal("14"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ ),
+ (
+ "amountCanceled",
+ "canceledAmount",
+ "canceled_value",
+ Decimal("14"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("100"),
+ ),
+ (
+ "amountCanceled",
+ "canceledAmount",
+ "canceled_value",
+ Decimal("0"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountCanceled",
+ "canceledAmount",
+ "canceled_value",
+ Decimal("1"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountVoided",
+ "voidedAmount",
+ "canceled_value",
+ Decimal("14"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountRefunded",
+ "refundedAmount",
+ "refunded_value",
+ Decimal("15"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountRefunded",
+ "refundedAmount",
+ "refunded_value",
+ Decimal("15"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ ),
+ (
+ "amountRefunded",
+ "refundedAmount",
+ "refunded_value",
+ Decimal("15"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("0"),
+ Decimal("100"),
+ ),
+ (
+ "amountRefunded",
+ "refundedAmount",
+ "refunded_value",
+ Decimal("0"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ (
+ "amountRefunded",
+ "refundedAmount",
+ "refunded_value",
+ Decimal("1"),
+ Decimal("1"),
+ Decimal("2"),
+ Decimal("3"),
+ Decimal("4"),
+ ),
+ ],
+)
+def test_transaction_update_amounts_are_correct(
+ field_name,
+ response_field,
+ db_field_name,
+ value,
+ current_authorized_value,
+ current_charged_value,
+ current_canceled_value,
+ current_refunded_value,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ order,
+ app,
+):
+ # given
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ canceled_value=current_canceled_value,
+ refunded_value=current_refunded_value,
+ )
+ recalculate_transaction_amounts(transaction)
+
+ 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
+ provided_amounts = {
+ "authorized_value": current_authorized_value,
+ "charged_value": current_charged_value,
+ "refunded_value": current_refunded_value,
+ "canceled_value": current_canceled_value,
+ "authorize_pending_value": Decimal(0),
+ "charge_pending_value": Decimal(0),
+ "refund_pending_value": Decimal(0),
+ "cancel_pending_value": Decimal(0),
+ }
+ provided_amounts[db_field_name] = value
+ assert sum(
+ [
+ transaction.authorized_value,
+ transaction.charged_value,
+ transaction.refunded_value,
+ transaction.canceled_value,
+ transaction.authorize_pending_value,
+ transaction.charge_pending_value,
+ transaction.refund_pending_value,
+ transaction.cancel_pending_value,
+ ]
+ ) == sum(provided_amounts.values())
diff --git a/saleor/graphql/payment/tests/queries/test_transaction.py b/saleor/graphql/payment/tests/queries/test_transaction.py
index 006eeda220..2d1b6c7de6 100644
--- a/saleor/graphql/payment/tests/queries/test_transaction.py
+++ b/saleor/graphql/payment/tests/queries/test_transaction.py
@@ -1,8 +1,14 @@
-import graphene
+from decimal import Decimal
+import pytest
+
+from .....payment import TransactionEventStatus, TransactionEventType
from .....payment.models import TransactionEvent
+from ....core.utils import to_global_id_or_none
from ....tests.utils import assert_no_permission, get_graphql_content
+TEST_SERVER_DOMAIN = "testserver.com"
+
TRANSACTION_QUERY = """
query transaction($id: ID!){
transaction(id: $id) {
@@ -17,6 +23,10 @@ TRANSACTION_QUERY = """
currency
amount
}
+ canceledAmount{
+ currency
+ amount
+ }
voidedAmount{
currency
amount
@@ -25,15 +35,60 @@ TRANSACTION_QUERY = """
currency
amount
}
+ authorizePendingAmount{
+ currency
+ amount
+ }
+ chargePendingAmount{
+ currency
+ amount
+ }
+ refundPendingAmount{
+ currency
+ amount
+ }
+ cancelPendingAmount{
+ currency
+ amount
+ }
events{
id
+ createdAt
+ status
+ pspReference
+ name
+ message
+ externalUrl
+ amount{
+ currency
+ amount
+ }
+ type
+ createdBy{
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
}
status
type
+ name
+ message
reference
order {
id
}
+ createdBy{
+ ... on User {
+ id
+ }
+ ... on App {
+ id
+ }
+ }
}
}
"""
@@ -49,33 +104,65 @@ def _assert_transaction_fields(content, transaction_item, event):
data["authorizedAmount"]["amount"] == transaction_item.amount_authorized.amount
)
assert data["refundedAmount"]["amount"] == transaction_item.amount_refunded.amount
- assert data["voidedAmount"]["amount"] == transaction_item.amount_voided.amount
+ assert data["voidedAmount"]["amount"] == transaction_item.amount_canceled.amount
+ assert data["canceledAmount"]["amount"] == transaction_item.amount_canceled.amount
assert data["chargedAmount"]["amount"] == transaction_item.amount_charged.amount
- assert len(data["events"]) == 1
- assert data["events"][0]["id"] == graphene.Node.to_global_id(
- "TransactionEvent", event.id
- )
+ events_data = [e for e in data["events"] if e["type"] == event.type.upper()]
+ assert len(events_data) == 1
+ assert events_data[0]["id"] == to_global_id_or_none(event)
assert data["status"] == transaction_item.status
- assert data["type"] == transaction_item.type
+ assert data["type"] == transaction_item.name
+ assert data["name"] == transaction_item.name
+ assert data["message"] == transaction_item.message
if transaction_item.order_id:
- assert data["order"]["id"] == graphene.Node.to_global_id(
- "Order", transaction_item.order.id
- )
+ assert data["order"]["id"] == to_global_id_or_none(transaction_item.order)
else:
assert data["order"] is None
-def test_transaction_query_by_app(
- app_api_client, transaction_item, permission_manage_payments
+def _assert_transaction_fields_created_by(content, transaction_item, event, created_by):
+ _assert_transaction_fields(content, transaction_item, event)
+ data = content["data"]["transaction"]
+ assert data["createdBy"]["id"] == to_global_id_or_none(created_by)
+
+
+def test_transaction_created_by_app_query_by_app(
+ app_api_client, transaction_item_created_by_app, permission_manage_payments, app
):
# given
- event = TransactionEvent.objects.create(
- transaction=transaction_item, currency=transaction_item.currency
+ event = transaction_item_created_by_app.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
+
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_app)}
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
)
- variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction_item.id)
- }
+ # then
+ content = get_graphql_content(response)
+ _assert_transaction_fields_created_by(
+ content,
+ transaction_item_created_by_app,
+ event,
+ app,
+ )
+
+
+def test_transaction_creted_by_app_query_no_order(
+ app_api_client, transaction_item_created_by_app, permission_manage_payments, app
+):
+ # given
+ transaction_item_created_by_app.order = None
+ transaction_item_created_by_app.save(update_fields=["order"])
+
+ event = transaction_item_created_by_app.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
+
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_app)}
# when
response = app_api_client.post_graphql(
@@ -84,64 +171,340 @@ def test_transaction_query_by_app(
# then
content = get_graphql_content(response)
- _assert_transaction_fields(content, transaction_item, event)
+ _assert_transaction_fields_created_by(
+ content,
+ transaction_item_created_by_app,
+ event,
+ app,
+ )
-def test_transaction_query_no_order(
- app_api_client, transaction_item, permission_manage_payments
+def test_transaction_created_by_app_query_by_staff(
+ staff_api_client, transaction_item_created_by_app, permission_manage_payments, app
):
# given
- transaction_item.order = None
- transaction_item.save(update_fields=["order"])
+ event = transaction_item_created_by_app.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
- event = TransactionEvent.objects.create(
- transaction=transaction_item, currency=transaction_item.currency
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_app)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
)
- variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction_item.id)
- }
+ # then
+ content = get_graphql_content(response)
+ _assert_transaction_fields_created_by(
+ content,
+ transaction_item_created_by_app,
+ event,
+ app,
+ )
+
+
+def test_transaction_create_by_app_query_no_permission(
+ app_api_client, transaction_item_created_by_app
+):
+ # given
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_app)}
+
+ # when
+ response = app_api_client.post_graphql(TRANSACTION_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_transaction_created_by_user_query_by_app(
+ app_api_client,
+ transaction_item_created_by_user,
+ permission_manage_payments,
+ permission_manage_staff,
+):
+ # given
+ event = transaction_item_created_by_user.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
+
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_user)}
# when
response = app_api_client.post_graphql(
- TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
)
# then
content = get_graphql_content(response)
- _assert_transaction_fields(content, transaction_item, event)
+ _assert_transaction_fields_created_by(
+ content,
+ transaction_item_created_by_user,
+ event,
+ transaction_item_created_by_user.user,
+ )
-def test_transaction_query_by_staff(
- staff_api_client, transaction_item, permission_manage_payments
+def test_transaction_creted_by_user_query_no_order(
+ app_api_client,
+ transaction_item_created_by_user,
+ permission_manage_payments,
+ permission_manage_staff,
):
# given
- event = TransactionEvent.objects.create(
- transaction=transaction_item, currency=transaction_item.currency
+ transaction_item_created_by_user.order = None
+ transaction_item_created_by_user.save(update_fields=["order"])
+
+ event = transaction_item_created_by_user.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
+
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_user)}
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ _assert_transaction_fields_created_by(
+ content,
+ transaction_item_created_by_user,
+ event,
+ transaction_item_created_by_user.user,
)
- variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction_item.id)
- }
+
+def test_transaction_created_by_user_query_by_staff(
+ staff_api_client,
+ transaction_item_created_by_user,
+ permission_manage_payments,
+ permission_manage_staff,
+):
+ # given
+ event = transaction_item_created_by_user.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
+
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_user)}
# when
response = staff_api_client.post_graphql(
- TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
)
# then
content = get_graphql_content(response)
- _assert_transaction_fields(content, transaction_item, event)
+ _assert_transaction_fields_created_by(
+ content,
+ transaction_item_created_by_user,
+ event,
+ transaction_item_created_by_user.user,
+ )
-def test_transaction_query_no_permission(app_api_client, transaction_item):
+def test_transaction_create_by_user_query_no_permission(
+ app_api_client, transaction_item_created_by_user
+):
# given
- variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction_item.id)
- }
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_user)}
# when
response = app_api_client.post_graphql(TRANSACTION_QUERY, variables)
# then
assert_no_permission(response)
+
+
+ "db_field, api_field",
+ [
+ ("authorize_pending_value", "authorizePendingAmount"),
+ ("charge_pending_value", "chargePendingAmount"),
+ ("refund_pending_value", "refundPendingAmount"),
+ ("cancel_pending_value", "cancelPendingAmount"),
+ ],
+)
+def test_transaction_with_pending_amount(
+ db_field,
+ api_field,
+ staff_api_client,
+ transaction_item_created_by_user,
+ permission_manage_payments,
+ permission_manage_staff,
+):
+ # given
+ expected_value = Decimal("10.00")
+
+ setattr(transaction_item_created_by_user, db_field, expected_value)
+ transaction_item_created_by_user.save(update_fields=[db_field])
+
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_user)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transaction"]
+ pending_money = data[api_field]
+ assert pending_money["amount"] == expected_value
+
+
+def test_transaction_event_by_user(
+ transaction_item_created_by_user,
+ permission_manage_payments,
+ permission_manage_staff,
+ staff_api_client,
+):
+ # given
+ psp_reference = "psp-ref-123"
+ event = TransactionEvent.objects.create(
+ transaction=transaction_item_created_by_user,
+ psp_reference=psp_reference,
+ message="Sucesfull charge",
+ currency="USD",
+ type=TransactionEventType.CHARGE_SUCCESS,
+ amount_value=Decimal("10.00"),
+ external_url=f"http://`{TEST_SERVER_DOMAIN}/test",
+ user=staff_api_client.user,
+ )
+
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_user)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ events = content["data"]["transaction"]["events"]
+ assert len(events) == 2
+ event_data = [event for event in events if event["pspReference"] == psp_reference][
+ 0
+ ]
+ assert event_data["id"] == to_global_id_or_none(event)
+ assert event_data["createdAt"] == event.created_at.isoformat()
+ assert event_data["status"] == event.status.upper()
+ assert event_data["pspReference"] == event.psp_reference
+ assert event_data["name"] == event.message
+ assert event_data["message"] == event.message
+ assert event_data["externalUrl"] == event.external_url
+ assert event_data["amount"]["amount"] == event.amount_value
+ assert event_data["amount"]["currency"] == event.currency
+ assert event_data["type"] == event.type.upper()
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(staff_api_client.user)
+
+
+def test_transaction_event_by_app(
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ permission_manage_staff,
+ app_api_client,
+):
+ # given
+ psp_reference = "psp-ref-123"
+ event = TransactionEvent.objects.create(
+ transaction=transaction_item_created_by_app,
+ status=TransactionEventStatus.SUCCESS,
+ psp_reference=psp_reference,
+ message="Sucesfull charge",
+ currency="USD",
+ type=TransactionEventType.CHARGE_SUCCESS,
+ amount_value=Decimal("10.00"),
+ external_url=f"http://`{TEST_SERVER_DOMAIN}/test",
+ app_identifier=app_api_client.app.identifier,
+ app=app_api_client.app,
+ )
+
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_app)}
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ events = content["data"]["transaction"]["events"]
+ assert len(events) == 2
+ event_data = [event for event in events if event["pspReference"] == psp_reference][
+ 0
+ ]
+ assert event_data["id"] == to_global_id_or_none(event)
+ assert event_data["createdAt"] == event.created_at.isoformat()
+ assert event_data["status"] == event.status.upper()
+ assert event_data["pspReference"] == event.psp_reference
+ assert event_data["name"] == event.message
+ assert event_data["message"] == event.message
+ assert event_data["externalUrl"] == event.external_url
+ assert event_data["amount"]["amount"] == event.amount_value
+ assert event_data["amount"]["currency"] == event.currency
+ assert event_data["type"] == event.type.upper()
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(app_api_client.app)
+
+
+def test_transaction_event_by_reinstalled_app(
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ permission_manage_staff,
+ app_api_client,
+):
+ # given
+ psp_reference = "psp-ref-123"
+ event = TransactionEvent.objects.create(
+ transaction=transaction_item_created_by_app,
+ status=TransactionEventStatus.SUCCESS,
+ psp_reference=psp_reference,
+ message="Sucesfull charge",
+ currency="USD",
+ type=TransactionEventType.CHARGE_SUCCESS,
+ amount_value=Decimal("10.00"),
+ external_url=f"http://`{TEST_SERVER_DOMAIN}/test",
+ app_identifier=app_api_client.app.identifier,
+ app=None,
+ )
+
+ variables = {"id": to_global_id_or_none(transaction_item_created_by_app)}
+
+ # when
+ response = app_api_client.post_graphql(
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ events = content["data"]["transaction"]["events"]
+ assert len(events) == 2
+ event_data = [event for event in events if event["pspReference"] == psp_reference][
+ 0
+ ]
+ assert event_data["id"] == to_global_id_or_none(event)
+ assert event_data["createdAt"] == event.created_at.isoformat()
+ assert event_data["status"] == event.status.upper()
+ assert event_data["pspReference"] == event.psp_reference
+ assert event_data["name"] == event.message
+ assert event_data["message"] == event.message
+ assert event_data["externalUrl"] == event.external_url
+ assert event_data["amount"]["amount"] == event.amount_value
+ assert event_data["amount"]["currency"] == event.currency
+ assert event_data["type"] == event.type.upper()
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(app_api_client.app)
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index 5ef6194088..f0d5ce7648 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -4,9 +4,18 @@ from graphene import relay
from ...core.exceptions import PermissionDenied
from ...payment import models
from ...permission.enums import OrderPermissions
+from ..account.dataloaders import UserByUserIdLoader
+from ..app.dataloaders import AppByIdLoader, AppsByAppIdentifierLoader
from ..checkout.dataloaders import CheckoutByTokenLoader
from ..core.connection import CountableConnection
-from ..core.descriptions import ADDED_IN_31, ADDED_IN_34, ADDED_IN_36, PREVIEW_FEATURE
+from ..core.descriptions import (
+ ADDED_IN_31,
+ ADDED_IN_34,
+ ADDED_IN_36,
+ ADDED_IN_313,
+ PREVIEW_FEATURE,
+ PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD,
+)
from ..core.fields import JSONString, PermissionsField
from ..core.tracing import traced_resolver
from ..core.types import ModelObjectType, Money, NonNullList
@@ -23,8 +32,9 @@ from .enums import (
OrderAction,
PaymentChargeStatusEnum,
TransactionActionEnum,
+ TransactionEventStatusEnum,
+ TransactionEventTypeEnum,
TransactionKindEnum,
- TransactionStatusEnum,
)
@@ -248,20 +258,108 @@ class PaymentInitialized(graphene.ObjectType):
class TransactionEvent(ModelObjectType[models.TransactionEvent]):
created_at = graphene.DateTime(required=True)
status = graphene.Field(
- TransactionStatusEnum,
+ TransactionEventStatusEnum,
description="Status of transaction's event.",
- required=True,
+ required=False,
+ deprecation_reason=(
+ f"{PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD} Use `type` instead."
+ ),
)
reference = graphene.String(
- description="Reference of transaction's event.", required=True
+ description="Reference of transaction's event.",
+ required=True,
+ deprecation_reason=(
+ f"{PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD}" "Use `pspReference` instead."
+ ),
+ )
+ psp_reference = graphene.String(
+ description="PSP reference of transaction." + ADDED_IN_313, required=True
+ )
+ name = graphene.String(
+ description="Name of the transaction's event.",
+ deprecation_reason=(
+ f"{PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD} Use `message` instead."
+ ),
+ )
+ message = graphene.String(
+ description="Message related to the transaction's event." + ADDED_IN_313,
+ required=True,
+ )
+ external_url = graphene.String(
+ description=(
+ "The url that will allow to redirect user to "
+ "payment provider page with transaction details." + ADDED_IN_313
+ ),
+ required=True,
+ )
+ amount = graphene.Field(
+ Money,
+ required=True,
+ description="The amount related to this event." + ADDED_IN_313,
+ )
+ type = graphene.Field(
+ TransactionEventTypeEnum,
+ description="The type of action related to this event." + ADDED_IN_313,
+ )
+
+ created_by = graphene.Field(
+ "saleor.graphql.core.types.user_or_app.UserOrApp",
+ description=("User or App that created the transaction event." + ADDED_IN_313),
)
- name = graphene.String(description="Name of the transaction's event.")
class Meta:
description = "Represents transaction's event."
interfaces = [relay.Node]
model = models.TransactionEvent
+ @staticmethod
+ def resolve_reference(root: models.TransactionEvent, info):
+ return root.psp_reference or ""
+
+ @staticmethod
+ def resolve_psp_reference(root: models.TransactionEvent, info):
+ return root.psp_reference or ""
+
+ @staticmethod
+ def resolve_external_url(root: models.TransactionEvent, info):
+ return root.external_url or ""
+
+ @staticmethod
+ def resolve_name(root: models.TransactionEvent, info):
+ return root.message or ""
+
+ @staticmethod
+ def resolve_message(root: models.TransactionEvent, info):
+ return root.message or ""
+
+ @staticmethod
+ def resolve_created_by(root: models.TransactionItem, info):
+ """Resolve createdBy.
+
+ Try to fetch the app by db relation first. This cover all apps created manually
+ by staff user and the third-party app that was not re-installed.
+ If the root.app_id is none, we're trying to fetch the app by `app.identifier`.
+ This covers a case when a third-party app was re-installed, but we're still able
+ to determine which one is the owner of the transaction.
+ """
+ if root.app_id:
+ return AppByIdLoader(info.context).load(root.app_id)
+ if root.app_identifier:
+
+ def get_first_app(apps):
+ if apps:
+ return apps[0]
+ return None
+
+ return (
+ AppsByAppIdentifierLoader(info.context)
+ .load(root.app_identifier)
+ .then(get_first_app)
+ )
+ if root.user_id:
+ return UserByUserIdLoader(info.context).load(root.user_id)
+ return None
+
class TransactionItem(ModelObjectType[models.TransactionItem]):
created_at = graphene.DateTime(required=True)
@@ -276,18 +374,93 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
authorized_amount = graphene.Field(
Money, required=True, description="Total amount authorized for this payment."
)
+ authorize_pending_amount = graphene.Field(
+ Money,
+ required=True,
+ description=(
+ "Total amount of ongoing authorization requests for the transaction."
+ + ADDED_IN_313
+ ),
+ )
refunded_amount = graphene.Field(
Money, required=True, description="Total amount refunded for this payment."
)
+ refund_pending_amount = graphene.Field(
+ Money,
+ required=True,
+ description=(
+ "Total amount of ongoing refund requests for the transaction."
+ + ADDED_IN_313
+ ),
+ )
voided_amount = graphene.Field(
- Money, required=True, description="Total amount voided for this payment."
+ Money,
+ required=True,
+ description=("Total amount voided for this payment."),
+ deprecation_reason=(
+ PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD + "Use `canceledAmount` instead."
+ ),
+ )
+
+ canceled_amount = graphene.Field(
+ Money,
+ required=True,
+ description="Total amount canceled for this payment." + ADDED_IN_313,
+ )
+ cancel_pending_amount = graphene.Field(
+ Money,
+ required=True,
+ description=(
+ "Total amount of ongoing cancel requests for the transaction."
+ + ADDED_IN_313
+ ),
)
charged_amount = graphene.Field(
Money, description="Total amount charged 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)
+ charge_pending_amount = graphene.Field(
+ Money,
+ required=True,
+ description=(
+ "Total amount of ongoing charge requests for the transaction."
+ + ADDED_IN_313
+ ),
+ )
+ status = graphene.String(
+ description="Status of transaction.",
+ deprecation_reason=(
+ PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD
+ + " The `status` is not needed. The amounts can be used to define "
+ "the current status of transactions."
+ ),
+ required=True,
+ )
+
+ type = graphene.String(
+ description="Type of transaction.",
+ deprecation_reason=(
+ PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD
+ + " Use `name` or `message` instead."
+ ),
+ required=True,
+ )
+ name = graphene.String(
+ description="Name of the transaction." + ADDED_IN_313, required=True
+ )
+ message = graphene.String(
+ description="Message related to the transaction." + ADDED_IN_313, required=True
+ )
+
+ reference = graphene.String(
+ description="Reference of transaction.",
+ required=True,
+ deprecation_reason=(
+ PREVIEW_FEATURE_DEPRECATED_IN_313_FIELD + "Use `pspReference` instead."
+ ),
+ )
+ psp_reference = graphene.String(
+ description="PSP reference of transaction." + ADDED_IN_313, required=True
+ )
order = graphene.Field(
"saleor.graphql.order.types.Order",
description="The related order." + ADDED_IN_36,
@@ -295,6 +468,17 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
events = NonNullList(
TransactionEvent, required=True, description="List of all transaction's events."
)
+ created_by = graphene.Field(
+ "saleor.graphql.core.types.user_or_app.UserOrApp",
+ description=("User or App that created the transaction." + ADDED_IN_313),
+ )
+ external_url = graphene.String(
+ description=(
+ "The url that will allow to redirect user to "
+ "payment provider page with transaction details." + ADDED_IN_313
+ ),
+ required=True,
+ )
class Meta:
description = (
@@ -311,18 +495,38 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
def resolve_charged_amount(root: models.TransactionItem, _info):
return root.amount_charged
+ @staticmethod
+ def resolve_charge_pending_amount(root: models.TransactionItem, _info):
+ return root.amount_charge_pending
+
@staticmethod
def resolve_authorized_amount(root: models.TransactionItem, _info):
return root.amount_authorized
+ @staticmethod
+ def resolve_authorize_pending_amount(root: models.TransactionItem, _info):
+ return root.amount_authorize_pending
+
@staticmethod
def resolve_voided_amount(root: models.TransactionItem, _info):
- return root.amount_voided
+ return root.amount_canceled
+
+ @staticmethod
+ def resolve_canceled_amount(root: models.TransactionItem, _info):
+ return root.amount_canceled
+
+ @staticmethod
+ def resolve_cancel_pending_amount(root: models.TransactionItem, _info):
+ return root.amount_cancel_pending
@staticmethod
def resolve_refunded_amount(root: models.TransactionItem, _info):
return root.amount_refunded
+ @staticmethod
+ def resolve_refund_pending_amount(root: models.TransactionItem, _info):
+ return root.amount_refund_pending
+
@staticmethod
def resolve_order(root: models.TransactionItem, info):
if not root.order_id:
@@ -332,3 +536,56 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
@staticmethod
def resolve_events(root: models.TransactionItem, info):
return TransactionEventByTransactionIdLoader(info.context).load(root.id)
+
+ @staticmethod
+ def resolve_created_by(root: models.TransactionItem, info):
+ """Resolve createdBy.
+
+ Try to fetch the app by db relation first. This cover all apps created manually
+ by staff user and the third-party app that was not re-installed.
+ If the root.app_id is none, we're trying to fetch the app by `app.identifier`.
+ This covers a case when a third-party app was re-installed, but we're still able
+ to determine which one is the owner of the transaction.
+ """
+
+ if root.app_id:
+ return AppByIdLoader(info.context).load(root.app_id)
+ if root.app_identifier:
+
+ def get_first_app(apps):
+ if apps:
+ return apps[0]
+ return None
+
+ return (
+ AppsByAppIdentifierLoader(info.context)
+ .load(root.app_identifier)
+ .then(get_first_app)
+ )
+ if root.user_id:
+ return UserByUserIdLoader(info.context).load(root.user_id)
+ return None
+
+ @staticmethod
+ def resolve_reference(root: models.TransactionItem, info):
+ return root.psp_reference or ""
+
+ @staticmethod
+ def resolve_psp_reference(root: models.TransactionItem, info):
+ return root.psp_reference or ""
+
+ @staticmethod
+ def resolve_external_url(root: models.TransactionItem, info):
+ return root.external_url or ""
+
+ @staticmethod
+ def resolve_type(root: models.TransactionItem, info) -> str:
+ return root.name or ""
+
+ @staticmethod
+ def resolve_name(root: models.TransactionItem, info) -> str:
+ return root.name or ""
+
+ @staticmethod
+ def resolve_message(root: models.TransactionItem, info) -> str:
+ return root.message or ""
diff --git a/saleor/graphql/payment/utils.py b/saleor/graphql/payment/utils.py
index 38638e3e88..995d83b0fd 100644
--- a/saleor/graphql/payment/utils.py
+++ b/saleor/graphql/payment/utils.py
@@ -1,5 +1,38 @@
-from typing import List
+from typing import TYPE_CHECKING, List, Optional
+
+from ...payment import models as payment_models
+
+if TYPE_CHECKING:
+ from ...account.models import User
+ from ...app.models import App
def metadata_contains_empty_key(metadata_list: List[dict]) -> bool:
return not all([data["key"].strip() for data in metadata_list])
+
+
+def check_if_requestor_has_access(
+ transaction: payment_models.TransactionItem,
+ user: Optional["User"],
+ app: Optional["App"],
+):
+ # Previously we didn't require app/user attached to transaction. We can't
+ # determine which app/user is an owner of the transaction. So for transaction
+ # without attached owner we require only HANDLE_PAYMENTS.
+ if (
+ not transaction.user_id
+ and not transaction.app_identifier
+ and not transaction.app_id
+ ):
+ return True
+
+ if user and transaction.user_id == user.id:
+ return True
+
+ if app:
+ if transaction.app_id == app.id:
+ return True
+
+ if transaction.app_identifier and transaction.app_identifier == app.identifier:
+ return True
+ return False
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index d368d70181..d496511f33 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1884,7 +1884,11 @@ enum WebhookEventTypeEnum {
"""A staff user is deleted."""
STAFF_DELETED
- """An action requested for transaction."""
+ """
+ An action requested for transaction.
+
+ DEPRECATED: this subscription will be removed in Saleor 3.14 (Preview Feature). Use `TRANSACTION_CHARGE_REQUESTED`, `TRANSACTION_REFUND_REQUESTED`, `TRANSACTION_CANCELATION_REQUESTED` instead.
+ """
TRANSACTION_ACTION_REQUEST
"""
@@ -1969,6 +1973,33 @@ enum WebhookEventTypeEnum {
"""Void payment."""
PAYMENT_VOID
+ """
+ Event called when charge has been requested for transaction.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ TRANSACTION_CHARGE_REQUESTED
+
+ """
+ Event called when refund has been requested for transaction.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ TRANSACTION_REFUND_REQUESTED
+
+ """
+ Event called when cancel has been requested for transaction.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ TRANSACTION_CANCELATION_REQUESTED
+
"""
Event called for checkout tax calculation.
@@ -2029,6 +2060,33 @@ enum WebhookEventTypeSyncEnum {
"""Void payment."""
PAYMENT_VOID
+ """
+ Event called when charge has been requested for transaction.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ TRANSACTION_CHARGE_REQUESTED
+
+ """
+ Event called when refund has been requested for transaction.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ TRANSACTION_REFUND_REQUESTED
+
+ """
+ Event called when cancel has been requested for transaction.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ TRANSACTION_CANCELATION_REQUESTED
+
"""
Event called for checkout tax calculation.
@@ -2434,7 +2492,11 @@ enum WebhookEventTypeAsyncEnum {
"""A staff user is deleted."""
STAFF_DELETED
- """An action requested for transaction."""
+ """
+ An action requested for transaction.
+
+ DEPRECATED: this subscription will be removed in Saleor 3.14 (Preview Feature). Use `TRANSACTION_CHARGE_REQUESTED`, `TRANSACTION_REFUND_REQUESTED`, `TRANSACTION_CANCELATION_REQUESTED` instead.
+ """
TRANSACTION_ACTION_REQUEST
"""
@@ -4852,6 +4914,31 @@ type OrderSettings {
When enabled, all non-shippable gift card orders will be fulfilled automatically.
"""
automaticallyFulfillNonShippableGiftCard: Boolean!
+
+ """
+ Determine what strategy will be used to mark the order as paid. Based on the chosen option, the proper object will be created and attached to the order when it's manually marked as paid.
+ `PAYMENT_FLOW` - [default option] creates the `Payment` object.
+ `TRANSACTION_FLOW` - creates the `TransactionItem` object.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ markAsPaidStrategy: MarkAsPaidStrategyEnum!
+}
+
+"""
+Determine the mark as paid strategy for the channel.
+
+ TRANSACTION_FLOW - new orders marked as paid will receive a
+ `TransactionItem` object, that will cover the `order.total`.
+
+ PAYMENT_FLOW - new orders marked as paid will receive a
+ `Payment` object, that will cover the `order.total`.
+"""
+enum MarkAsPaidStrategyEnum {
+ TRANSACTION_FLOW
+ PAYMENT_FLOW
}
"""Represents shipping method postal code rule."""
@@ -9504,23 +9591,79 @@ type TransactionItem implements Node & ObjectWithMetadata @doc(category: "Paymen
"""Total amount authorized for this payment."""
authorizedAmount: Money!
+ """
+ Total amount of ongoing authorization requests for the transaction.
+
+ Added in Saleor 3.13.
+ """
+ authorizePendingAmount: Money!
+
"""Total amount refunded for this payment."""
refundedAmount: Money!
+ """
+ Total amount of ongoing refund requests for the transaction.
+
+ Added in Saleor 3.13.
+ """
+ refundPendingAmount: Money!
+
"""Total amount voided for this payment."""
- voidedAmount: Money!
+ voidedAmount: Money! @deprecated(reason: "This field will be removed in Saleor 3.14 (Preview Feature).Use `canceledAmount` instead.")
+
+ """
+ Total amount canceled for this payment.
+
+ Added in Saleor 3.13.
+ """
+ canceledAmount: Money!
+
+ """
+ Total amount of ongoing cancel requests for the transaction.
+
+ Added in Saleor 3.13.
+ """
+ cancelPendingAmount: Money!
"""Total amount charged for this payment."""
chargedAmount: Money!
+ """
+ Total amount of ongoing charge requests for the transaction.
+
+ Added in Saleor 3.13.
+ """
+ chargePendingAmount: Money!
+
"""Status of transaction."""
- status: String!
+ status: String! @deprecated(reason: "This field will be removed in Saleor 3.14 (Preview Feature). The `status` is not needed. The amounts can be used to define the current status of transactions.")
"""Type of transaction."""
- type: String!
+ type: String! @deprecated(reason: "This field will be removed in Saleor 3.14 (Preview Feature). Use `name` or `message` instead.")
+
+ """
+ Name of the transaction.
+
+ Added in Saleor 3.13.
+ """
+ name: String!
+
+ """
+ Message related to the transaction.
+
+ Added in Saleor 3.13.
+ """
+ message: String!
"""Reference of transaction."""
- reference: String!
+ reference: String! @deprecated(reason: "This field will be removed in Saleor 3.14 (Preview Feature).Use `pspReference` instead.")
+
+ """
+ PSP reference of transaction.
+
+ Added in Saleor 3.13.
+ """
+ pspReference: String!
"""
The related order.
@@ -9531,6 +9674,20 @@ type TransactionItem implements Node & ObjectWithMetadata @doc(category: "Paymen
"""List of all transaction's events."""
events: [TransactionEvent!]!
+
+ """
+ User or App that created the transaction.
+
+ Added in Saleor 3.13.
+ """
+ createdBy: UserOrApp
+
+ """
+ The url that will allow to redirect user to payment provider page with transaction details.
+
+ Added in Saleor 3.13.
+ """
+ externalUrl: String!
}
"""
@@ -9539,12 +9696,15 @@ Represents possible actions on payment transaction.
The following actions are possible:
CHARGE - Represents the charge action.
REFUND - Represents a refund action.
- VOID - Represents a void action.
+ VOID - Represents a void action. This field will be removed
+ in Saleor 3.14 (Preview Feature). Use `CANCEL` instead.
+ CANCEL - Represents a cancel action. Added in Saleor 3.12.
"""
enum TransactionActionEnum {
CHARGE
REFUND
VOID
+ CANCEL
}
"""Represents an order in the shop."""
@@ -9782,8 +9942,22 @@ type Order implements Node & ObjectWithMetadata @doc(category: "Orders") {
"""Amount authorized for the order."""
totalAuthorized: Money!
- """Amount captured by payment."""
- totalCaptured: Money!
+ """Amount captured for the order."""
+ totalCaptured: Money! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `totalCharged` instead.")
+
+ """
+ Amount charged for the order.
+
+ Added in Saleor 3.13.
+ """
+ totalCharged: Money!
+
+ """
+ Amount canceled for the order.
+
+ Added in Saleor 3.13.
+ """
+ totalCanceled: Money!
"""
List of events associated with the order.
@@ -9853,6 +10027,92 @@ type Order implements Node & ObjectWithMetadata @doc(category: "Orders") {
Added in Saleor 3.11.
"""
checkoutId: ID
+
+ """
+ List of granted refunds.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ grantedRefunds: [OrderGrantedRefund!]!
+
+ """
+ Total amount of granted refund.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ totalGrantedRefund: Money!
+
+ """
+ Total refund amount for the order.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ totalRefunded: Money!
+
+ """
+ Total amount of ongoing refund requests for the order's transactions.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ totalRefundPending: Money!
+
+ """
+ Total amount of ongoing authorize requests for the order's transactions.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ totalAuthorizePending: Money!
+
+ """
+ Total amount of ongoing charge requests for the order's transactions.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ totalChargePending: Money!
+
+ """
+ Total amount of ongoing cancel requests for the order's transactions.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ totalCancelPending: Money!
+
+ """
+ The difference amount between granted refund and the amounts that are pending and refunded.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ totalRemainingGrant: Money!
}
"""An enumeration."""
@@ -10275,16 +10535,17 @@ enum PaymentChargeStatusEnum {
Determine a current authorize status for order.
We treat the order as fully authorized when the sum of authorized and charged funds
- cover the order.total.
+ cover the `order.total`-`order.totalGrantedRefund`.
We treat the order as partially authorized when the sum of authorized and charged
- funds covers only part of the order.total
+ funds covers only part of the `order.total`-`order.totalGrantedRefund`.
We treat the order as not authorized when the sum of authorized and charged funds is
0.
NONE - the funds are not authorized
- PARTIAL - the funds that are authorized or charged don't cover fully the order's
- total
- FULL - the funds that are authorized or charged fully cover the order's total
+ PARTIAL - the funds that are authorized and charged don't cover fully the
+ `order.total`-`order.totalGrantedRefund`
+ FULL - the funds that are authorized and charged fully cover the
+ `order.total`-`order.totalGrantedRefund`
"""
enum OrderAuthorizeStatusEnum {
NONE
@@ -10295,15 +10556,22 @@ enum OrderAuthorizeStatusEnum {
"""
Determine the current charge status for the order.
- We treat the order as overcharged when the charged amount is bigger that order.total
- We treat the order as fully charged when the charged amount is equal to order.total.
- We treat the order as partially charged when the charged amount covers only part of
- the order.total
+ An order is considered overcharged when the sum of the
+ transactionItem's charge amounts exceeds the value of
+ `order.total` - `order.totalGrantedRefund`.
+ If the sum of the transactionItem's charge amounts equals
+ `order.total` - `order.totalGrantedRefund`, we consider the order to be fully
+ charged.
+ If the sum of the transactionItem's charge amounts covers a part of the
+ `order.total` - `order.totalGrantedRefund`, we treat the order as partially charged.
NONE - the funds are not charged.
- PARTIAL - the funds that are charged don't cover the order's total
- FULL - the funds that are charged fully cover the order's total
- OVERCHARGED - the charged funds are bigger than order's total
+ PARTIAL - the funds that are charged don't cover the
+ `order.total`-`order.totalGrantedRefund`
+ FULL - the funds that are charged fully cover the
+ `order.total`-`order.totalGrantedRefund`
+ OVERCHARGED - the charged funds are bigger than the
+ `order.total`-`order.totalGrantedRefund`
"""
enum OrderChargeStatusEnum {
NONE
@@ -10537,13 +10805,13 @@ type OrderEvent implements Node @doc(category: "Orders") {
discount: OrderEventDiscountObject
"""The status of payment's transaction."""
- status: TransactionStatus
+ status: TransactionStatus @deprecated(reason: "This field will be removed in Saleor 3.14 (Preview Feature).Use `TransactionEvent` to track the status of `TransactionItem`.")
"""The reference of payment's transaction."""
reference: String
}
-"""An enumeration."""
+"""The different order event types."""
enum OrderEventsEnum {
DRAFT_CREATED
DRAFT_CREATED_FROM_REPLACE
@@ -10574,9 +10842,20 @@ enum OrderEventsEnum {
PAYMENT_VOIDED
PAYMENT_FAILED
TRANSACTION_EVENT
+ TRANSACTION_CHARGE_REQUESTED
+
+ """
+ This field will be removed in Saleor 3.14 (Preview Feature). Use `TRANSACTION_CHARGE_REQUESTED` instead.
+ """
TRANSACTION_CAPTURE_REQUESTED
TRANSACTION_REFUND_REQUESTED
+
+ """
+ This field will be removed in Saleor 3.14 (Preview Feature). Use `TRANSACTION_CANCEL_REQUESTED` instead.
+ """
TRANSACTION_VOID_REQUESTED
+ TRANSACTION_CANCEL_REQUESTED
+ TRANSACTION_MARK_AS_PAID_FAILED
INVOICE_REQUESTED
INVOICE_GENERATED
INVOICE_UPDATED
@@ -10643,7 +10922,14 @@ type OrderEventDiscountObject {
oldAmount: Money
}
-"""An enumeration."""
+"""
+Represents a status of payment transaction.
+
+ The following statuses are possible:
+ SUCCESS - Represents a sucess action.
+ FAILURE - Represents a failure action.
+ PENDING - Represents a pending action.
+"""
enum TransactionStatus {
PENDING
SUCCESS
@@ -10726,6 +11012,7 @@ enum OrderErrorCode {
ORDER_NO_SHIPPING_ADDRESS
PAYMENT_ERROR
PAYMENT_MISSING
+ TRANSACTION_ERROR
REQUIRED
SHIPPING_METHOD_NOT_APPLICABLE
SHIPPING_METHOD_REQUIRED
@@ -10738,7 +11025,6 @@ enum OrderErrorCode {
DUPLICATED_INPUT_ITEM
NOT_AVAILABLE_IN_CHANNEL
CHANNEL_INACTIVE
- MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK
}
"""An enumeration."""
@@ -10747,6 +11033,37 @@ enum AddressTypeEnum {
SHIPPING
}
+"""
+The details of granted refund.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type OrderGrantedRefund {
+ id: ID!
+
+ """Time of creation."""
+ createdAt: DateTime!
+
+ """Time of last update."""
+ updatedAt: DateTime!
+
+ """Refund amount."""
+ amount: Money!
+
+ """Reason of the refund."""
+ reason: String
+
+ """
+ User who performed the action. Requires of of the following permissions: MANAGE_USERS, MANAGE_STAFF, OWNER.
+ """
+ user: User
+
+ """App that performed the action."""
+ app: App
+}
+
"""Represents transaction's event."""
type TransactionEvent implements Node @doc(category: "Payments") {
"""The ID of the object."""
@@ -10754,23 +11071,109 @@ type TransactionEvent implements Node @doc(category: "Payments") {
createdAt: DateTime!
"""Status of transaction's event."""
- status: TransactionStatus!
+ status: TransactionStatus @deprecated(reason: "This field will be removed in Saleor 3.14 (Preview Feature). Use `type` instead.")
"""Reference of transaction's event."""
- reference: String!
+ reference: String! @deprecated(reason: "This field will be removed in Saleor 3.14 (Preview Feature).Use `pspReference` instead.")
+
+ """
+ PSP reference of transaction.
+
+ Added in Saleor 3.13.
+ """
+ pspReference: String!
"""Name of the transaction's event."""
- name: String
-}
+ name: String @deprecated(reason: "This field will be removed in Saleor 3.14 (Preview Feature). Use `message` instead.")
-type CheckoutCountableConnection {
- """Pagination data for this connection."""
- pageInfo: PageInfo!
- edges: [CheckoutCountableEdge!]!
+ """
+ Message related to the transaction's event.
+
+ Added in Saleor 3.13.
+ """
+ message: String!
- """A total count of items in the collection."""
- totalCount: Int
-}
+ """
+ The url that will allow to redirect user to payment provider page with transaction details.
+
+ Added in Saleor 3.13.
+ """
+ externalUrl: String!
+
+ """
+ The amount related to this event.
+
+ Added in Saleor 3.13.
+ """
+ amount: Money!
+
+ """
+ The type of action related to this event.
+
+ Added in Saleor 3.13.
+ """
+ type: TransactionEventTypeEnum
+
+ """
+ User or App that created the transaction event.
+
+ Added in Saleor 3.13.
+ """
+ createdBy: UserOrApp
+}
+
+"""
+Represents possible event types.
+
+ Added in Saleor 3.12.
+
+ The following types are possible:
+ AUTHORIZATION_SUCCESS - represents success authorization.
+ AUTHORIZATION_FAILURE - represents failure authorization.
+ AUTHORIZATION_ADJUSTMENT - represents authorization adjustment.
+ AUTHORIZATION_REQUEST - represents authorization request.
+ CHARGE_SUCCESS - represents success charge.
+ CHARGE_FAILURE - represents failure charge.
+ CHARGE_BACK - represents chargeback.
+ CHARGE_REQUEST - represents charge request.
+ REFUND_SUCCESS - represents success refund.
+ REFUND_FAILURE - represents failure refund.
+ REFUND_REVERSE - represents reverse refund.
+ REFUND_REQUEST - represents refund request.
+ CANCEL_SUCCESS - represents success cancel.
+ CANCEL_FAILURE - represents failure cancel.
+ CANCEL_REQUEST - represents cancel request.
+ INFO - represents info event.
+"""
+enum TransactionEventTypeEnum {
+ AUTHORIZATION_SUCCESS
+ AUTHORIZATION_FAILURE
+ AUTHORIZATION_ADJUSTMENT
+ AUTHORIZATION_REQUEST
+ CHARGE_SUCCESS
+ CHARGE_FAILURE
+ CHARGE_BACK
+ CHARGE_REQUEST
+ REFUND_SUCCESS
+ REFUND_FAILURE
+ REFUND_REVERSE
+ REFUND_REQUEST
+ CANCEL_SUCCESS
+ CANCEL_FAILURE
+ CANCEL_REQUEST
+ INFO
+}
+
+union UserOrApp = User | App
+
+type CheckoutCountableConnection {
+ """Pagination data for this connection."""
+ pageInfo: PageInfo!
+ edges: [CheckoutCountableEdge!]!
+
+ """A total count of items in the collection."""
+ totalCount: Int
+}
type CheckoutCountableEdge {
"""The item at the end of the edge."""
@@ -13496,11 +13899,13 @@ type Mutation {
): PaymentCheckBalance @doc(category: "Payments")
"""
- Create transaction for checkout or order. Requires the following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS.
+ Create transaction for checkout or order.
Added in Saleor 3.4.
- Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ 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.
"""
transactionCreate(
"""The ID of the checkout or order."""
@@ -13514,11 +13919,13 @@ type Mutation {
): TransactionCreate @doc(category: "Payments")
"""
- Create transaction for checkout or order. Requires the following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS.
+ Create transaction for checkout or order.
Added in Saleor 3.4.
Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires the following permissions: OWNER and HANDLE_PAYMENTS.
"""
transactionUpdate(
"""The ID of the transaction."""
@@ -13538,7 +13945,7 @@ type Mutation {
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.
+ Requires one of the following permissions: HANDLE_PAYMENTS.
"""
transactionRequestAction(
"""Determines the action type."""
@@ -13553,6 +13960,45 @@ type Mutation {
id: ID!
): TransactionRequestAction @doc(category: "Payments")
+ """
+ Report the event for the transaction.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires the following permissions: OWNER and HANDLE_PAYMENTS.
+ """
+ transactionEventReport(
+ """The amount of the event to report."""
+ amount: PositiveDecimal!
+
+ """List of all possible actions for the transaction"""
+ availableActions: [TransactionActionEnum!]
+
+ """
+ The url that will allow to redirect user to payment provider page with event details.
+ """
+ externalUrl: String
+
+ """The ID of the transaction."""
+ id: ID!
+
+ """The message related to the event."""
+ message: String
+
+ """PSP Reference of the event to report."""
+ pspReference: String!
+
+ """
+ The time of the event to report. If not provide, the current time will be used.
+ """
+ time: DateTime
+
+ """Current status of the event to report."""
+ type: TransactionEventTypeEnum!
+ ): TransactionEventReport @doc(category: "Payments")
+
"""
Creates a new page.
@@ -13927,6 +14373,40 @@ type Mutation {
order: ID!
): FulfillmentReturnProducts @doc(category: "Orders")
+ """
+ Adds granted refund to the order.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ orderGrantRefundCreate(
+ """ID of the order."""
+ id: ID!
+
+ """Fields required to create a granted refund for the order."""
+ input: OrderGrantRefundCreateInput!
+ ): OrderGrantRefundCreate @doc(category: "Orders")
+
+ """
+ Updates granted refund.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+ Requires one of the following permissions: MANAGE_ORDERS.
+ """
+ orderGrantRefundUpdate(
+ """ID of the granted refund."""
+ id: ID!
+
+ """Fields required to update a granted refund."""
+ input: OrderGrantRefundUpdateInput!
+ ): OrderGrantRefundUpdate @doc(category: "Orders")
+
"""
Create order lines for an order.
@@ -19754,11 +20234,13 @@ input MoneyInput {
}
"""
-Create transaction for checkout or order. Requires the following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS.
+Create transaction for checkout or order.
Added in Saleor 3.4.
-Note: this API is currently in Feature Preview and can be subject to changes at later point.
+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.
"""
type TransactionCreate @doc(category: "Payments") {
transaction: TransactionItem
@@ -19785,18 +20267,52 @@ enum TransactionCreateErrorCode {
NOT_FOUND
INCORRECT_CURRENCY
METADATA_KEY_REQUIRED
+ UNIQUE
}
input TransactionCreateInput @doc(category: "Payments") {
- """Status of the transaction."""
- status: String!
+ """
+ Status of the transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). The `status` is not needed. The amounts can be used to define the current status of transactions.
+ """
+ status: String
+
+ """
+ Payment type used for this transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). Use `name` and `message` instead.
+ """
+ type: String
+
+ """
+ Payment name of the transaction.
+
+ Added in Saleor 3.13.
+ """
+ name: String
- """Payment type used for this transaction."""
- type: String!
+ """
+ The message of the transaction.
+
+ Added in Saleor 3.13.
+ """
+ message: String
- """Reference of the transaction."""
+ """
+ Reference of the transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). Use `pspReference` instead.
+ """
reference: String
+ """
+ PSP Reference of the transaction.
+
+ Added in Saleor 3.13.
+ """
+ pspReference: String
+
"""List of all possible actions for the transaction"""
availableActions: [TransactionActionEnum!]
@@ -19809,33 +20325,79 @@ input TransactionCreateInput @doc(category: "Payments") {
"""Amount refunded by this transaction."""
amountRefunded: MoneyInput
- """Amount voided by this transaction."""
+ """
+ Amount voided by this transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). Use `amountCanceled` instead.
+ """
amountVoided: MoneyInput
+ """
+ Amount canceled by this transaction.
+
+ Added in Saleor 3.13.
+ """
+ amountCanceled: MoneyInput
+
"""Payment public metadata."""
metadata: [MetadataInput!]
"""Payment private metadata."""
privateMetadata: [MetadataInput!]
+
+ """
+ The url that will allow to redirect user to payment provider page with transaction event details.
+
+ Added in Saleor 3.13.
+ """
+ externalUrl: String
}
input TransactionEventInput @doc(category: "Payments") {
- """Current status of the payment transaction."""
- status: TransactionStatus!
+ """
+ Current status of the payment transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). Status will be calculated by Saleor.
+ """
+ status: TransactionStatus
- """Reference of the transaction."""
+ """
+ Reference of the transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). Use `pspReference` instead.
+ """
reference: String
- """Name of the transaction."""
+ """
+ PSP Reference related to this action.
+
+ Added in Saleor 3.13.
+ """
+ pspReference: String
+
+ """
+ Name of the transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). Use `message` instead. `name` field will be added to `message`.
+ """
name: String
+
+ """
+ The message related to the event.
+
+ Added in Saleor 3.13.
+ """
+ message: String
}
"""
-Create transaction for checkout or order. Requires the following permissions: AUTHENTICATED_APP and HANDLE_PAYMENTS.
+Create transaction for checkout or order.
Added in Saleor 3.4.
Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+Requires the following permissions: OWNER and HANDLE_PAYMENTS.
"""
type TransactionUpdate @doc(category: "Payments") {
transaction: TransactionItem
@@ -19862,18 +20424,52 @@ enum TransactionUpdateErrorCode {
NOT_FOUND
INCORRECT_CURRENCY
METADATA_KEY_REQUIRED
+ UNIQUE
}
input TransactionUpdateInput @doc(category: "Payments") {
- """Status of the transaction."""
+ """
+ Status of the transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). The `status` is not needed. The amounts can be used to define the current status of transactions.
+ """
status: String
- """Payment type used for this transaction."""
+ """
+ Payment type used for this transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). Use `name` and `message` instead.
+ """
type: String
- """Reference of the transaction."""
+ """
+ Payment name of the transaction.
+
+ Added in Saleor 3.13.
+ """
+ name: String
+
+ """
+ The message of the transaction.
+
+ Added in Saleor 3.13.
+ """
+ message: String
+
+ """
+ Reference of the transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). Use `pspReference` instead.
+ """
reference: String
+ """
+ PSP Reference of the transaction.
+
+ Added in Saleor 3.13.
+ """
+ pspReference: String
+
"""List of all possible actions for the transaction"""
availableActions: [TransactionActionEnum!]
@@ -19886,14 +20482,32 @@ input TransactionUpdateInput @doc(category: "Payments") {
"""Amount refunded by this transaction."""
amountRefunded: MoneyInput
- """Amount voided by this transaction."""
+ """
+ Amount voided by this transaction.
+
+ DEPRECATED: this field will be removed in Saleor 3.14 (Preview Feature). Use `amountCanceled` instead.
+ """
amountVoided: MoneyInput
+ """
+ Amount canceled by this transaction.
+
+ Added in Saleor 3.13.
+ """
+ amountCanceled: MoneyInput
+
"""Payment public metadata."""
metadata: [MetadataInput!]
"""Payment private metadata."""
privateMetadata: [MetadataInput!]
+
+ """
+ The url that will allow to redirect user to payment provider page with transaction event details.
+
+ Added in Saleor 3.13.
+ """
+ externalUrl: String
}
"""
@@ -19903,7 +20517,7 @@ 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.
+Requires one of the following permissions: HANDLE_PAYMENTS.
"""
type TransactionRequestAction @doc(category: "Payments") {
transaction: TransactionItem
@@ -19931,6 +20545,51 @@ enum TransactionRequestActionErrorCode {
MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK
}
+"""
+Report the event for the transaction.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+Requires the following permissions: OWNER and HANDLE_PAYMENTS.
+"""
+type TransactionEventReport @doc(category: "Payments") {
+ """Defines if the reported event hasn't been processed earlier."""
+ alreadyProcessed: Boolean
+
+ """The transaction related to the reported event."""
+ transaction: TransactionItem
+
+ """
+ The event assigned to this report. if `alreadyProcessed` is set to `true`, the previously processed event will be returned.
+ """
+ transactionEvent: TransactionEvent
+ errors: [TransactionEventReportError!]!
+}
+
+type TransactionEventReportError {
+ """
+ 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: TransactionEventReportErrorCode!
+}
+
+"""An enumeration."""
+enum TransactionEventReportErrorCode {
+ INVALID
+ GRAPHQL_ERROR
+ NOT_FOUND
+ INCORRECT_DETAILS
+ ALREADY_EXISTS
+}
+
"""
Creates a new page.
@@ -20685,6 +21344,106 @@ input OrderReturnFulfillmentLineInput @doc(category: "Orders") {
replace: Boolean = false
}
+"""
+Adds granted refund to the order.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+Requires one of the following permissions: MANAGE_ORDERS.
+"""
+type OrderGrantRefundCreate @doc(category: "Orders") {
+ """Order which has assigned new grant refund."""
+ order: Order
+
+ """Created granted refund."""
+ grantedRefund: OrderGrantedRefund
+ errors: [OrderGrantRefundCreateError!]!
+}
+
+type OrderGrantRefundCreateError {
+ """
+ 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: OrderGrantRefundCreateErrorCode!
+}
+
+"""An enumeration."""
+enum OrderGrantRefundCreateErrorCode {
+ GRAPHQL_ERROR
+ NOT_FOUND
+}
+
+input OrderGrantRefundCreateInput {
+ """Amount of the granted refund."""
+ amount: Decimal!
+
+ """Reason of the granted refund."""
+ reason: String
+}
+
+"""
+Custom Decimal implementation.
+
+Returns Decimal as a float in the API,
+parses float to the Decimal on the way back.
+"""
+scalar Decimal
+
+"""
+Updates granted refund.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+
+Requires one of the following permissions: MANAGE_ORDERS.
+"""
+type OrderGrantRefundUpdate @doc(category: "Orders") {
+ """Order which has assigned updated grant refund."""
+ order: Order
+
+ """Created granted refund."""
+ grantedRefund: OrderGrantedRefund
+ errors: [OrderGrantRefundUpdateError!]!
+ orderGrantedRefund: OrderGrantedRefund
+}
+
+type OrderGrantRefundUpdateError {
+ """
+ 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: OrderGrantRefundUpdateErrorCode!
+}
+
+"""An enumeration."""
+enum OrderGrantRefundUpdateErrorCode {
+ GRAPHQL_ERROR
+ NOT_FOUND
+ REQUIRED
+}
+
+input OrderGrantRefundUpdateInput {
+ """Amount of the granted refund."""
+ amount: Decimal
+
+ """Reason of the granted refund."""
+ reason: String
+}
+
"""
Create order lines for an order.
@@ -22816,6 +23575,17 @@ input OrderSettingsInput {
When enabled, all non-shippable gift card orders will be fulfilled automatically. By defualt set to True.
"""
automaticallyFulfillNonShippableGiftCard: Boolean
+
+ """
+ Determine what strategy will be used to mark the order as paid. Based on the chosen option, the proper object will be created and attached to the order when it's manually marked as paid.
+ `PAYMENT_FLOW` - [default option] creates the `Payment` object.
+ `TRANSACTION_FLOW` - creates the `TransactionItem` object.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ markAsPaidStrategy: MarkAsPaidStrategyEnum
}
"""
@@ -26930,7 +27700,7 @@ Event sent when transaction action is requested.
Added in Saleor 3.4.
-Note: this API is currently in Feature Preview and can be subject to changes at later point.
+DEPRECATED: this subscription will be removed in Saleor 3.14 (Preview Feature). Use `TransactionChargeRequested`, `TransactionRefundRequested`, `TransactionCancelationRequested` instead.
"""
type TransactionActionRequest implements Event {
"""Time of the event."""
@@ -26945,22 +27715,10 @@ type TransactionActionRequest implements Event {
"""The application receiving the webhook."""
recipient: App
- """
- 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.
- """
+ """Look up a transaction."""
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.
- """
+ """Requested action data."""
action: TransactionAction!
}
@@ -27469,6 +28227,87 @@ type PaymentListGateways implements Event {
checkout: Checkout
}
+"""
+Event sent when transaction cancelation is requested.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionCancelationRequested implements Event {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """Look up a transaction."""
+ transaction: TransactionItem
+
+ """Requested action data."""
+ action: TransactionAction!
+}
+
+"""
+Event sent when transaction charge is requested.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionChargeRequested implements Event {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """Look up a transaction."""
+ transaction: TransactionItem
+
+ """Requested action data."""
+ action: TransactionAction!
+}
+
+"""
+Event sent when transaction refund is requested.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionRefundRequested implements Event {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """Look up a transaction."""
+ transaction: TransactionItem
+
+ """Requested action data."""
+ action: TransactionAction!
+}
+
"""
Filter shipping methods for order.
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index b23ea633ae..f339a14528 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -442,6 +442,7 @@ class OrderSettingsUpdate(BaseMutation):
automatically_fulfill_non_shippable_gift_card=(
channel.automatically_fulfill_non_shippable_gift_card
),
+ mark_as_paid_strategy=channel.order_mark_as_paid_strategy,
)
return OrderSettingsUpdate(order_settings=order_settings)
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index 1a37708d34..a8a0a0c5f9 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -1332,6 +1332,7 @@ ORDER_SETTINGS_UPDATE_MUTATION = """
orderSettings {
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
+ markAsPaidStrategy
}
}
}
diff --git a/saleor/graphql/tests/queries/fragments.py b/saleor/graphql/tests/queries/fragments.py
index 620b6f9fc8..70cec347af 100644
--- a/saleor/graphql/tests/queries/fragments.py
+++ b/saleor/graphql/tests/queries/fragments.py
@@ -438,3 +438,38 @@ fragment PaymentDetails on Payment {
gateway
}
"""
+
+
+TRANSACTION_ITEM_DETAILS = """
+fragment TransactionFragment on TransactionItem {
+ id
+ createdAt
+ actions
+ authorizedAmount {
+ currency
+ amount
+ }
+ refundedAmount {
+ currency
+ amount
+ }
+ voidedAmount {
+ currency
+ amount
+ }
+ chargedAmount {
+ currency
+ amount
+ }
+ events {
+ id
+ }
+ status
+ type
+ pspReference
+ reference
+ order {
+ id
+ }
+}
+"""
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index 3b69c2bad1..6b780d9b28 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -1,7 +1,13 @@
import graphene
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
-from ..core.descriptions import ADDED_IN_36, ADDED_IN_38, ADDED_IN_312, PREVIEW_FEATURE
+from ..core.descriptions import (
+ ADDED_IN_36,
+ ADDED_IN_38,
+ ADDED_IN_312,
+ ADDED_IN_313,
+ PREVIEW_FEATURE,
+)
from ..core.utils import str_to_enum
checkout_updated_event_enum_description = (
@@ -152,6 +158,9 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventAsyncType.STAFF_DELETED: "A staff user is deleted.",
WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST: (
"An action requested for transaction."
+ + "\n\nDEPRECATED: this subscription will be removed in Saleor 3.14 "
+ + "(Preview Feature). Use `TRANSACTION_CHARGE_REQUESTED`, "
+ + "`TRANSACTION_REFUND_REQUESTED`, `TRANSACTION_CANCELATION_REQUESTED` instead."
),
WebhookEventAsyncType.TRANSACTION_ITEM_METADATA_UPDATED: (
"Transaction item metadata is updated." + ADDED_IN_38 + PREVIEW_FEATURE
@@ -195,6 +204,21 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventSyncType.ORDER_CALCULATE_TAXES: (
"Event called for order tax calculation." + ADDED_IN_36 + PREVIEW_FEATURE
),
+ WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED: (
+ "Event called when charge has been requested for transaction."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED: (
+ "Event called when refund has been requested for transaction."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED: (
+ "Event called when cancel has been requested for transaction."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
}
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 3c6193e7ae..6ea3f635ed 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -36,6 +36,7 @@ from ..core.descriptions import (
ADDED_IN_310,
ADDED_IN_311,
ADDED_IN_312,
+ ADDED_IN_313,
PREVIEW_FEATURE,
)
from ..core.scalars import PositiveDecimal
@@ -1528,27 +1529,17 @@ class TransactionAction(SubscriptionObjectType, AbstractType):
return None
-class TransactionActionRequest(SubscriptionObjectType):
+class TransactionActionBase(AbstractType):
transaction = graphene.Field(
TransactionItem,
- description="Look up a transaction." + ADDED_IN_34 + PREVIEW_FEATURE,
+ description="Look up a transaction.",
)
action = graphene.Field(
TransactionAction,
required=True,
- description="Requested action data." + ADDED_IN_34 + PREVIEW_FEATURE,
+ description="Requested action data.",
)
- class Meta:
- root_type = None
- enable_dry_run = False
- interfaces = (Event,)
- description = (
- "Event sent when transaction action is requested."
- + ADDED_IN_34
- + PREVIEW_FEATURE
- )
-
@staticmethod
def resolve_transaction(root, _info: ResolveInfo):
_, transaction_action_data = root
@@ -1562,6 +1553,56 @@ class TransactionActionRequest(SubscriptionObjectType):
return transaction_action_data
+class TransactionActionRequest(TransactionActionBase, SubscriptionObjectType):
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent when transaction action is requested."
+ + ADDED_IN_34
+ + "\n\nDEPRECATED: this subscription will be removed in Saleor 3.14 "
+ + "(Preview Feature). Use `TransactionChargeRequested`, "
+ + "`TransactionRefundRequested`, `TransactionCancelationRequested` instead."
+ )
+
+
+class TransactionChargeRequested(TransactionActionBase, SubscriptionObjectType):
+ class Meta:
+ interfaces = (Event,)
+ root_type = None
+ enable_dry_run = False
+ description = (
+ "Event sent when transaction charge is requested."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ )
+
+
+class TransactionRefundRequested(TransactionActionBase, SubscriptionObjectType):
+ class Meta:
+ interfaces = (Event,)
+ root_type = None
+ enable_dry_run = False
+ description = (
+ "Event sent when transaction refund is requested."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ )
+
+
+class TransactionCancelationRequested(TransactionActionBase, SubscriptionObjectType):
+ class Meta:
+ interfaces = (Event,)
+ root_type = None
+ enable_dry_run = False
+ description = (
+ "Event sent when transaction cancelation is requested."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ )
+
+
class TransactionItemMetadataUpdated(SubscriptionObjectType):
transaction = graphene.Field(
TransactionItem,
@@ -1793,6 +1834,7 @@ class CalculateTaxes(SubscriptionObjectType):
+ PREVIEW_FEATURE
)
+ @staticmethod
def resolve_tax_base(root, _info: ResolveInfo):
_, tax_base = root
return tax_base
@@ -2078,6 +2120,11 @@ WEBHOOK_TYPES_MAP = {
WebhookEventSyncType.PAYMENT_CONFIRM: PaymentConfirmEvent,
WebhookEventSyncType.PAYMENT_PROCESS: PaymentProcessEvent,
WebhookEventSyncType.PAYMENT_LIST_GATEWAYS: PaymentListGateways,
+ WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED: (
+ TransactionCancelationRequested
+ ),
+ WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED: TransactionChargeRequested,
+ WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED: TransactionRefundRequested,
WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS: (OrderFilterShippingMethods),
WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS: (
CheckoutFilterShippingMethods
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
index d10e26eaeb..a5a758bbad 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
@@ -328,7 +328,7 @@ def async_subscription_webhooks_with_root_objects(
voucher,
warehouse,
translated_attribute,
- transaction_item,
+ transaction_item_created_by_app,
product_media_image,
):
events = WebhookEventAsyncType
@@ -547,7 +547,7 @@ def async_subscription_webhooks_with_root_objects(
events.STAFF_DELETED: [subscription_staff_deleted_webhook, staff_user],
events.TRANSACTION_ITEM_METADATA_UPDATED: [
subscription_transaction_item_metadata_updated_webhook,
- transaction_item,
+ transaction_item_created_by_app,
],
events.TRANSLATION_CREATED: [
subscription_translation_created_webhook,
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index d94d576c26..85e6855ce1 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -115,8 +115,11 @@ class OrderEvents:
TRANSACTION_EVENT = "transaction_event"
TRANSACTION_CAPTURE_REQUESTED = "transaction_capture_requested"
+ TRANSACTION_CHARGE_REQUESTED = "transaction_charge_requested"
TRANSACTION_REFUND_REQUESTED = "transaction_refund_requested"
TRANSACTION_VOID_REQUESTED = "transaction_void_requested"
+ TRANSACTION_CANCEL_REQUESTED = "transaction_cancel_requested"
+ TRANSACTION_MARK_AS_PAID_FAILED = "transaction_mark_as_paid_failed"
EXTERNAL_SERVICE_NOTIFICATION = "external_service_notification"
@@ -171,9 +174,12 @@ class OrderEvents:
(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"),
+ (TRANSACTION_CHARGE_REQUESTED, "The charge requested for transaction"),
+ (TRANSACTION_CAPTURE_REQUESTED, "The capture requested for transaction"),
+ (TRANSACTION_REFUND_REQUESTED, "The refund requested for transaction"),
+ (TRANSACTION_VOID_REQUESTED, "The void requested for transaction"),
+ (TRANSACTION_CANCEL_REQUESTED, "The cancel requested for transaction"),
+ (TRANSACTION_MARK_AS_PAID_FAILED, "The mark as paid failed for transaction"),
(INVOICE_REQUESTED, "An invoice was requested"),
(INVOICE_GENERATED, "An invoice was generated"),
(INVOICE_UPDATED, "An invoice was updated"),
@@ -221,16 +227,17 @@ class OrderAuthorizeStatus:
"""Determine a current authorize status for order.
We treat the order as fully authorized when the sum of authorized and charged funds
- cover the order.total.
+ cover the `order.total`-`order.totalGrantedRefund`.
We treat the order as partially authorized when the sum of authorized and charged
- funds covers only part of the order.total
+ funds covers only part of the `order.total`-`order.totalGrantedRefund`.
We treat the order as not authorized when the sum of authorized and charged funds is
0.
NONE - the funds are not authorized
- PARTIAL - the funds that are authorized or charged don't cover fully the order's
- total
- FULL - the funds that are authorized or charged fully cover the order's total
+ PARTIAL - the funds that are authorized and charged don't cover fully the
+ `order.total`-`order.totalGrantedRefund`
+ FULL - the funds that are authorized and charged fully cover the
+ `order.total`-`order.totalGrantedRefund`
"""
NONE = "none"
@@ -241,12 +248,12 @@ class OrderAuthorizeStatus:
(NONE, "The funds are not authorized"),
(
PARTIAL,
- "The funds that are authorized or charged don't cover fully the order's "
+ "The funds that are authorized and charged don't cover fully the order's "
"total",
),
(
FULL,
- "The funds that are authorized or charged fully cover the order's total",
+ "The funds that are authorized and charged fully cover the order's total",
),
]
@@ -254,15 +261,22 @@ class OrderAuthorizeStatus:
class OrderChargeStatus:
"""Determine the current charge status for the order.
- We treat the order as overcharged when the charged amount is bigger that order.total
- We treat the order as fully charged when the charged amount is equal to order.total.
- We treat the order as partially charged when the charged amount covers only part of
- the order.total
+ An order is considered overcharged when the sum of the
+ transactionItem's charge amounts exceeds the value of
+ `order.total` - `order.totalGrantedRefund`.
+ If the sum of the transactionItem's charge amounts equals
+ `order.total` - `order.totalGrantedRefund`, we consider the order to be fully
+ charged.
+ If the sum of the transactionItem's charge amounts covers a part of the
+ `order.total` - `order.totalGrantedRefund`, we treat the order as partially charged.
NONE - the funds are not charged.
- PARTIAL - the funds that are charged don't cover the order's total
- FULL - the funds that are charged fully cover the order's total
- OVERCHARGED - the charged funds are bigger than order's total
+ PARTIAL - the funds that are charged don't cover the
+ `order.total`-`order.totalGrantedRefund`
+ FULL - the funds that are charged fully cover the
+ `order.total`-`order.totalGrantedRefund`
+ OVERCHARGED - the charged funds are bigger than the
+ `order.total`-`order.totalGrantedRefund`
"""
NONE = "none"
@@ -271,10 +285,10 @@ class OrderChargeStatus:
OVERCHARGED = "overcharged"
CHOICES = [
- (NONE, "The funds are not charged."),
- (PARTIAL, "The funds that are charged, don't cover the order's total"),
- (FULL, "The funds that are charged fully cover the order's total"),
- (OVERCHARGED, "The charged funds are bigger than order's total"),
+ (NONE, "The order is not charged."),
+ (PARTIAL, "The order is partially charged"),
+ (FULL, "The order is fully charged"),
+ (OVERCHARGED, "The order is overcharged"),
]
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index c520c8f4a5..2815075792 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -22,10 +22,9 @@ from ..payment import (
TransactionKind,
gateway,
)
-from ..payment.gateway import request_refund_action
from ..payment.interface import RefundData
-from ..payment.models import Payment, Transaction, TransactionItem
-from ..payment.utils import create_payment
+from ..payment.models import Payment, Transaction
+from ..payment.utils import create_payment, create_transaction_for_order
from ..warehouse.management import (
deallocate_stock,
deallocate_stock_for_order,
@@ -63,6 +62,7 @@ from .utils import (
update_order_authorize_data,
update_order_charge_data,
update_order_status,
+ updates_amounts_for_order,
)
if TYPE_CHECKING:
@@ -499,7 +499,37 @@ def approve_fulfillment(
return fulfillment
-def mark_order_as_paid(
+def mark_order_as_paid_with_transaction(
+ order: "Order",
+ request_user: User,
+ app: Optional["App"],
+ manager: "PluginsManager",
+ external_reference: Optional[str] = None,
+):
+ """Mark order as paid.
+
+ Allows to create a transaction for an order.
+ """
+ with transaction.atomic():
+ create_transaction_for_order(
+ order=order,
+ user=request_user,
+ app=app,
+ psp_reference=external_reference,
+ charged_value=order.total.gross.amount,
+ )
+ updates_amounts_for_order(order)
+ events.order_manually_marked_as_paid_event(
+ order=order,
+ user=request_user,
+ app=app,
+ transaction_reference=external_reference,
+ )
+ call_event(manager.order_fully_paid, order)
+ call_event(manager.order_updated, order)
+
+
+def mark_order_as_paid_with_payment(
order: "Order",
request_user: User,
app: Optional["App"],
@@ -561,6 +591,10 @@ def clean_mark_order_as_paid(order: "Order"):
raise PaymentError(
"Orders with payments can not be manually marked as paid.",
)
+ if order.payment_transactions.exists():
+ raise PaymentError(
+ "Orders with transactions can not be manually marked as paid.",
+ )
def _decrease_stocks(order_lines_info, manager, allow_stock_to_be_exceeded=False):
@@ -1034,7 +1068,6 @@ 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",
@@ -1059,7 +1092,6 @@ 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,
@@ -1376,7 +1408,6 @@ 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",
@@ -1413,13 +1444,12 @@ def create_fulfillments_for_returned_products(
)
total_refund_amount = None
with traced_atomic_transaction():
- if refund and (payment or transactions):
+ if refund and payment:
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,
@@ -1502,7 +1532,6 @@ def _process_refund(
app: Optional["App"],
order: "Order",
payment: Optional[Payment],
- transactions: Optional[List[TransactionItem]],
order_lines_to_refund: List[OrderLineInfo],
fulfillment_lines_to_refund: List[FulfillmentLineData],
amount: Optional[Decimal],
@@ -1524,45 +1553,30 @@ def _process_refund(
# provided.
if refund_shipping_costs:
amount += order.shipping_price_gross_amount
- if amount:
- 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.charged_value, amount)
- request_refund_action(
- transaction_item,
- manager,
- refund_value=amount,
- channel_slug=order.channel.slug,
+ if amount and payment:
+ amount = min(payment.captured_amount, amount)
+ gateway.refund(
+ payment,
+ manager,
+ amount=amount,
+ channel_slug=order.channel.slug,
+ refund_data=refund_data,
+ )
+
+ transaction.on_commit(
+ lambda: events.payment_refunded_event(
+ order=order,
user=user,
app=app,
+ amount=amount, # type: ignore
+ payment=payment, # type: ignore
)
- elif payment:
- amount = min(payment.captured_amount, amount)
- gateway.refund(
- payment,
- manager,
- amount=amount,
- channel_slug=order.channel.slug,
- refund_data=refund_data,
- )
-
- 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 c9e30d57e0..f5765ea337 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -21,6 +21,7 @@ class OrderErrorCode(Enum):
ORDER_NO_SHIPPING_ADDRESS = "order_no_shipping_address"
PAYMENT_ERROR = "payment_error"
PAYMENT_MISSING = "payment_missing"
+ TRANSACTION_ERROR = "transaction_error"
REQUIRED = "required"
SHIPPING_METHOD_NOT_APPLICABLE = "shipping_method_not_applicable"
SHIPPING_METHOD_REQUIRED = "shipping_method_required"
@@ -33,6 +34,14 @@ 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"
- )
+
+
+class OrderGrantRefundCreateErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ NOT_FOUND = "not_found"
+
+
+class OrderGrantRefundUpdateErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ NOT_FOUND = "not_found"
+ REQUIRED = "required"
diff --git a/saleor/order/events.py b/saleor/order/events.py
index 945ebe9fcd..de80e2c6e0 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -34,7 +34,7 @@ def _get_payment_data(amount: Optional[Decimal], payment: Payment) -> Dict:
}
-def event_transaction_capture_requested(
+def event_transaction_charge_requested(
order_id: "UUID",
reference: str,
amount: Decimal,
@@ -43,7 +43,7 @@ def event_transaction_capture_requested(
):
return OrderEvent.objects.create(
order_id=order_id,
- type=OrderEvents.TRANSACTION_CAPTURE_REQUESTED,
+ type=OrderEvents.TRANSACTION_CHARGE_REQUESTED,
user=user,
app=app,
parameters={
@@ -72,12 +72,12 @@ def event_transaction_refund_requested(
)
-def event_transaction_void_requested(
+def event_transaction_cancel_requested(
order_id: "UUID", reference: str, user: Optional[User], app: Optional[App]
):
return OrderEvent.objects.create(
order_id=order_id,
- type=OrderEvents.TRANSACTION_VOID_REQUESTED,
+ type=OrderEvents.TRANSACTION_CANCEL_REQUESTED,
user=user,
app=app,
parameters={
@@ -483,16 +483,30 @@ def payment_failed_event(
)
+def transaction_mark_order_as_paid_failed_event(
+ order: Order, user: Optional[User], app: Optional[App], message: str
+):
+ parameters = {"message": message}
+
+ return OrderEvent.objects.create(
+ order=order,
+ type=OrderEvents.TRANSACTION_MARK_AS_PAID_FAILED,
+ user=user,
+ app=app,
+ parameters=parameters,
+ )
+
+
def transaction_event(
*,
order: Order,
user: Optional[User],
app: Optional[App],
reference: str,
- status: str,
- name: str
+ status: Optional[str],
+ message: str
) -> OrderEvent:
- parameters = {"message": name, "reference": reference, "status": status}
+ parameters = {"message": message, "reference": reference, "status": status}
return OrderEvent.objects.create(
order=order,
type=OrderEvents.TRANSACTION_EVENT,
diff --git a/saleor/order/migrations/0162_order_granted_refund.py b/saleor/order/migrations/0162_order_granted_refund.py
new file mode 100644
index 0000000000..17272c1e13
--- /dev/null
+++ b/saleor/order/migrations/0162_order_granted_refund.py
@@ -0,0 +1,176 @@
+from decimal import Decimal
+from django.db import migrations, models
+import django.db.models.deletion
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("app", "0020_app_is_installed"),
+ ("account", "0076_fill_empty_passwords"),
+ ("order", "0161_merge_20221219_1838"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="OrderGrantedRefund",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "created_at",
+ models.DateTimeField(
+ default=django.utils.timezone.now, editable=False
+ ),
+ ),
+ ("updated_at", models.DateTimeField(auto_now=True, db_index=True)),
+ (
+ "amount_value",
+ models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ ("currency", models.CharField(max_length=3)),
+ ("reason", models.TextField(blank=True, default="")),
+ (
+ "app",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="app.app",
+ ),
+ ),
+ (
+ "order",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="granted_refunds",
+ to="order.order",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="account.user",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("created_at", "id"),
+ },
+ ),
+ 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_CHARGE_REQUESTED", "transaction_charge_requested"),
+ ("TRANSACTION_CAPTURE_REQUESTED", "transaction_capture_requested"),
+ ("TRANSACTION_REFUND_REQUESTED", "transaction_refund_requested"),
+ ("TRANSACTION_VOID_REQUESTED", "transaction_void_requested"),
+ ("TRANSACTION_CANCEL_REQUESTED", "transaction_cancel_requested"),
+ (
+ "TRANSACTION_MARK_AS_PAID_FAILED",
+ "transaction_mark_as_paid_failed",
+ ),
+ ("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,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="order",
+ name="authorize_status",
+ field=models.CharField(
+ choices=[
+ ("none", "The funds are not authorized"),
+ (
+ "partial",
+ "The funds that are authorized and charged don't cover fully "
+ "the order's total",
+ ),
+ (
+ "full",
+ "The funds that are authorized and charged fully cover the "
+ "order's total",
+ ),
+ ],
+ db_index=True,
+ default="none",
+ max_length=32,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="order",
+ name="charge_status",
+ field=models.CharField(
+ choices=[
+ ("none", "The order is not charged."),
+ ("partial", "The order is partially charged"),
+ ("full", "The order is fully charged"),
+ ("overcharged", "The order is overcharged"),
+ ],
+ db_index=True,
+ default="none",
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0163_order_events_rename_transaction_events.py b/saleor/order/migrations/0163_order_events_rename_transaction_events.py
new file mode 100644
index 0000000000..fe6579a1a1
--- /dev/null
+++ b/saleor/order/migrations/0163_order_events_rename_transaction_events.py
@@ -0,0 +1,28 @@
+from django.db import migrations
+from django.apps import apps as registry
+from django.db.models.signals import post_migrate
+
+from .tasks.saleor3_13 import (
+ order_events_rename_transaction_capture_events_task,
+ order_events_rename_transaction_void_events_task,
+)
+
+
+def rename_order_events(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ order_events_rename_transaction_void_events_task.delay()
+ order_events_rename_transaction_capture_events_task.delay()
+
+ sender = registry.get_app_config("order")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0162_order_granted_refund"),
+ ]
+ operations = [
+ migrations.RunPython(
+ rename_order_events, reverse_code=migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/order/migrations/tasks/saleor3_13.py b/saleor/order/migrations/tasks/saleor3_13.py
new file mode 100644
index 0000000000..9853226efa
--- /dev/null
+++ b/saleor/order/migrations/tasks/saleor3_13.py
@@ -0,0 +1,37 @@
+from ....celeryconf import app
+from ...models import OrderEvent
+
+from django.db.models import QuerySet
+
+# Batch size of size 1000 is about 1MB memory usage in task
+BATCH_SIZE = 1000
+
+
+def update_type_to_transaction_cancel_requested(qs: QuerySet[OrderEvent]):
+ qs.update(type="transaction_cancel_requested")
+
+
+def order_events_rename_transaction_void_events_task():
+ qs = OrderEvent.objects.filter(type="transaction_void_requested").order_by("-pk")
+ ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
+ qs = qs.filter(pk__in=ids)
+
+ if ids:
+ update_type_to_transaction_cancel_requested(qs)
+ order_events_rename_transaction_void_events_task.delay()
+
+
+def update_type_to_transaction_charge_requested(qs: QuerySet[OrderEvent]):
+ qs.update(type="transaction_charge_requested")
+
+
+def order_events_rename_transaction_capture_events_task():
+ qs = OrderEvent.objects.filter(type="transaction_capture_requested").order_by("-pk")
+ ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
+ qs = qs.filter(pk__in=ids)
+
+ if ids:
+ update_type_to_transaction_charge_requested(qs)
+ order_events_rename_transaction_capture_events_task.delay()
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 055d9e85d7..231278cc14 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -792,3 +792,37 @@ class OrderEvent(models.Model):
def __repr__(self):
return f"{self.__class__.__name__}(type={self.type!r}, user={self.user!r})"
+
+
+class OrderGrantedRefund(models.Model):
+ """Model used to store granted refund for the order."""
+
+ created_at = models.DateTimeField(default=now, editable=False)
+ updated_at = models.DateTimeField(auto_now=True, editable=False, db_index=True)
+
+ amount_value = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal("0"),
+ )
+ amount = MoneyField(amount_field="amount_value", currency_field="currency")
+ currency = models.CharField(
+ max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
+ )
+ reason = models.TextField(blank=True, default="")
+ user = models.ForeignKey(
+ settings.AUTH_USER_MODEL,
+ blank=True,
+ null=True,
+ on_delete=models.SET_NULL,
+ related_name="+",
+ )
+ app = models.ForeignKey(
+ App, related_name="+", on_delete=models.SET_NULL, null=True, blank=True
+ )
+ order = models.ForeignKey(
+ Order, related_name="granted_refunds", on_delete=models.CASCADE
+ )
+
+ class Meta:
+ ordering = ("created_at", "id")
diff --git a/saleor/order/search.py b/saleor/order/search.py
index 003f3b06a4..e0d5e2d232 100644
--- a/saleor/order/search.py
+++ b/saleor/order/search.py
@@ -34,6 +34,7 @@ def prepare_order_search_vector_value(
"payments",
"discounts",
"lines",
+ "payment_transactions__events",
)
search_vectors = [
NoValidationSearchVector(Value(str(order.number)), config="simple", weight="A")
@@ -75,9 +76,46 @@ def prepare_order_search_vector_value(
search_vectors += generate_order_payments_search_vector_value(order)
search_vectors += generate_order_discounts_search_vector_value(order)
search_vectors += generate_order_lines_search_vector_value(order)
+ search_vectors += generate_order_transactions_search_vector_value(order)
return search_vectors
+def generate_order_transactions_search_vector_value(
+ order: "Order",
+) -> List[NoValidationSearchVector]:
+ transaction_vectors = []
+ for transaction in order.payment_transactions.all()[
+ : settings.SEARCH_ORDERS_MAX_INDEXED_TRANSACTIONS
+ ]:
+ transaction_vectors.append(
+ NoValidationSearchVector(
+ Value(graphene.Node.to_global_id("TransactionItem", transaction.id)),
+ config="simple",
+ weight="D",
+ )
+ )
+ if transaction.psp_reference:
+ transaction_vectors.append(
+ NoValidationSearchVector(
+ Value(transaction.psp_reference),
+ config="simple",
+ weight="D",
+ )
+ )
+ for event in transaction.events.all()[
+ : settings.SEARCH_ORDERS_MAX_INDEXED_TRANSACTIONS
+ ]:
+ if event.psp_reference:
+ transaction_vectors.append(
+ NoValidationSearchVector(
+ Value(event.psp_reference),
+ config="simple",
+ weight="D",
+ )
+ )
+ return transaction_vectors
+
+
def generate_order_payments_search_vector_value(
order: "Order",
) -> List[NoValidationSearchVector]:
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index 3106f29c13..f7c623b8b3 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -4,17 +4,24 @@ from unittest.mock import patch
import pytest
from prices import Money, TaxedMoney
+from ...channel import MarkAsPaidStrategy
from ...giftcard import GiftCardEvents
from ...giftcard.models import GiftCard, GiftCardEvent
from ...order.fetch import OrderLineInfo, fetch_order_info
-from ...payment import ChargeStatus, PaymentError, TransactionKind
+from ...payment import ChargeStatus, PaymentError, TransactionEventType, TransactionKind
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
from ...product.models import DigitalContent
from ...product.tests.utils import create_image
from ...tests.utils import flush_post_commit_hooks
from ...warehouse.models import Allocation, Stock
-from .. import FulfillmentStatus, OrderEvents, OrderStatus
+from .. import (
+ FulfillmentStatus,
+ OrderAuthorizeStatus,
+ OrderChargeStatus,
+ OrderEvents,
+ OrderStatus,
+)
from ..actions import (
automatically_fulfill_digital_lines,
cancel_fulfillment,
@@ -22,7 +29,8 @@ from ..actions import (
clean_mark_order_as_paid,
fulfill_order_lines,
handle_fully_paid_order,
- mark_order_as_paid,
+ mark_order_as_paid_with_payment,
+ mark_order_as_paid_with_transaction,
order_refunded,
)
from ..models import Fulfillment, OrderLine
@@ -269,9 +277,9 @@ def test_handle_fully_paid_order_gift_cards_not_created(
send_notification_mock.assert_not_called
-def test_mark_as_paid(admin_user, draft_order):
+def test_mark_as_paid_with_payment(admin_user, draft_order):
manager = get_plugins_manager()
- mark_order_as_paid(draft_order, admin_user, None, manager)
+ mark_order_as_paid_with_payment(draft_order, admin_user, None, manager)
payment = draft_order.payments.last()
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
assert payment.captured_amount == draft_order.total.gross.amount
@@ -281,10 +289,10 @@ def test_mark_as_paid(admin_user, draft_order):
assert transactions[0].kind == TransactionKind.EXTERNAL
-def test_mark_as_paid_with_external_reference(admin_user, draft_order):
+def test_mark_as_paid_with_external_reference_with_payment(admin_user, draft_order):
external_reference = "transaction_id"
manager = get_plugins_manager()
- mark_order_as_paid(
+ mark_order_as_paid_with_payment(
draft_order, admin_user, None, manager, external_reference=external_reference
)
payment = draft_order.payments.last()
@@ -304,7 +312,7 @@ def test_mark_as_paid_no_billing_address(admin_user, draft_order):
manager = get_plugins_manager()
with pytest.raises(Exception):
- mark_order_as_paid(draft_order, admin_user, None, manager)
+ mark_order_as_paid_with_payment(draft_order, admin_user, None, manager)
def test_clean_mark_order_as_paid(payment_txn_preauth):
@@ -313,6 +321,52 @@ def test_clean_mark_order_as_paid(payment_txn_preauth):
clean_mark_order_as_paid(order)
+def test_mark_as_paid_with_transaction(admin_user, draft_order):
+ # given
+ manager = get_plugins_manager()
+ channel = draft_order.channel
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
+ # when
+ mark_order_as_paid_with_transaction(draft_order, admin_user, None, manager)
+
+ # then
+ draft_order.refresh_from_db()
+ assert not draft_order.payments.exists()
+ transaction = draft_order.payment_transactions.get()
+
+ assert transaction.charged_value == draft_order.total.gross.amount
+ assert draft_order.authorize_status == OrderAuthorizeStatus.FULL
+ assert draft_order.charge_status == OrderChargeStatus.FULL
+ assert draft_order.total_charged.amount == transaction.charged_value
+
+ transaction_event = transaction.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
+ assert transaction_event.amount_value == draft_order.total.gross.amount
+ assert transaction_event.type == TransactionEventType.CHARGE_SUCCESS
+
+
+def test_mark_as_paid_with_external_reference_with_transaction(admin_user, draft_order):
+ # given
+ external_reference = "transaction_id"
+ manager = get_plugins_manager()
+ channel = draft_order.channel
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
+ # when
+ mark_order_as_paid_with_transaction(
+ draft_order, admin_user, None, manager, external_reference=external_reference
+ )
+
+ # then
+ assert not draft_order.payments.exists()
+ transaction = draft_order.payment_transactions.get()
+ assert transaction.psp_reference == external_reference
+
+
def test_cancel_fulfillment(fulfilled_order, warehouse):
fulfillment = fulfilled_order.fulfillments.first()
line_1, line_2 = fulfillment.lines.all()
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 5e9cb28d05..ea8069f130 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,7 +40,6 @@ 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
@@ -119,7 +118,6 @@ 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(),
@@ -196,7 +194,6 @@ 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(),
@@ -289,7 +286,6 @@ 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(),
@@ -400,7 +396,6 @@ 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)
@@ -459,7 +454,6 @@ 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(),
@@ -602,7 +596,6 @@ 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(),
@@ -675,7 +668,6 @@ def test_create_return_fulfillment_only_order_lines_with_old_ids(
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
diff --git a/saleor/order/tests/test_order_actions_refund_products.py b/saleor/order/tests/test_order_actions_refund_products.py
index 63b0f87920..29ceb947d6 100644
--- a/saleor/order/tests/test_order_actions_refund_products.py
+++ b/saleor/order/tests/test_order_actions_refund_products.py
@@ -41,7 +41,6 @@ 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(),
@@ -108,7 +107,6 @@ 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(),
@@ -170,7 +168,6 @@ 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(),
@@ -229,7 +226,6 @@ 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/order/tests/test_order_search.py b/saleor/order/tests/test_order_search.py
index ac1deaa4ca..2ffe8ddb04 100644
--- a/saleor/order/tests/test_order_search.py
+++ b/saleor/order/tests/test_order_search.py
@@ -54,6 +54,9 @@ def test_prepare_order_search_vector_value(
payment_dummy.psp_reference = psp_reference
payment_dummy.save(update_fields=["psp_reference"])
+ transaction = order.payment_transactions.create(psp_reference="ABC")
+ transaction.events.create(psp_reference="event-psp-reference")
+
# when
search_vector = prepare_order_search_vector_value(order)
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 731c649c18..f7ef47433d 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -3,6 +3,7 @@ from functools import wraps
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, cast
import graphene
+from django.db.models import QuerySet
from django.utils import timezone
from prices import Money, TaxedMoney
@@ -50,12 +51,13 @@ from . import (
events,
)
from .fetch import OrderLineInfo
-from .models import Order, OrderLine
+from .models import Order, OrderGrantedRefund, OrderLine
if TYPE_CHECKING:
from ..app.models import App
from ..channel.models import Channel
from ..checkout.fetch import CheckoutInfo
+ from ..payment.models import Payment, TransactionItem
from ..plugins.manager import PluginsManager
@@ -861,92 +863,169 @@ def remove_discount_from_order_line(order_line: OrderLine, order: "Order"):
)
-def update_order_charge_status(order: Order):
+def update_order_charge_status(order: Order, granted_refund_amount: Decimal):
"""Update the current charge status for the order.
- We treat the order as overcharged when the charged amount is bigger that order.total
- We treat the order as fully charged when the charged amount is equal to order.total.
+ We treat the order as overcharged when the charged amount is bigger that
+ order.total - order granted refund
+ We treat the order as fully charged when the charged amount is equal to
+ order.total - order granted refund.
We treat the order as partially charged when the charged amount covers only part of
- the order.total
+ the order.total - order granted refund
We treat the order as not charged when the charged amount is 0.
"""
total_charged = order.total_charged_amount or Decimal("0")
total_charged = quantize_price(total_charged, order.currency)
- total_gross = order.total_gross_amount or Decimal(0)
- total_gross = quantize_price(total_gross, order.currency)
+ current_total_gross = order.total_gross_amount - granted_refund_amount
+ current_total_gross = max(current_total_gross, Decimal("0"))
+ current_total_gross = quantize_price(
+ current_total_gross - granted_refund_amount, order.currency
+ )
- if total_charged <= 0:
+ if total_charged == current_total_gross:
+ order.charge_status = OrderChargeStatus.FULL
+ elif total_charged <= Decimal(0):
order.charge_status = OrderChargeStatus.NONE
- elif total_charged < total_gross:
+ elif total_charged < current_total_gross:
order.charge_status = OrderChargeStatus.PARTIAL
- elif total_charged == total_gross:
- order.charge_status = OrderChargeStatus.FULL
else:
order.charge_status = OrderChargeStatus.OVERCHARGED
-def _update_order_total_charged(order: Order):
- order.total_charged_amount = (
- sum(order.payments.values_list("captured_amount", flat=True)) or 0
- )
- order.total_charged_amount += sum(
- order.payment_transactions.values_list("charged_value", flat=True)
- )
+def _update_order_total_charged(
+ order: Order,
+ order_payments: QuerySet["Payment"],
+ order_transactions: Iterable["TransactionItem"],
+):
+ order.total_charged_amount = sum(
+ order_payments.values_list("captured_amount", flat=True)
+ ) or Decimal(0)
+ order.total_charged_amount += sum([tr.charged_value for tr in order_transactions])
-def update_order_charge_data(order: Order, with_save=True):
- _update_order_total_charged(order)
- update_order_charge_status(order)
+def update_order_charge_data(
+ order: Order,
+ order_payments: Optional[QuerySet["Payment"]] = None,
+ order_transactions: Optional[QuerySet["TransactionItem"]] = None,
+ order_granted_refunds: Optional[QuerySet["OrderGrantedRefund"]] = None,
+ with_save=True,
+):
+ if order_payments is None:
+ order_payments = order.payments.all()
+ if order_transactions is None:
+ order_transactions = order.payment_transactions.all()
+ if order_granted_refunds is None:
+ order_granted_refunds = order.granted_refunds.all()
+ granted_refund_amount = sum(
+ [refund.amount.amount for refund in order_granted_refunds]
+ )
+ _update_order_total_charged(
+ order, order_payments=order_payments, order_transactions=order_transactions
+ )
+ update_order_charge_status(order, granted_refund_amount)
if with_save:
order.save(
update_fields=["total_charged_amount", "charge_status", "updated_at"]
)
-def _update_order_total_authorized(order: Order):
+def _update_order_total_authorized(
+ order: Order,
+ order_payments: QuerySet["Payment"],
+ order_transactions: QuerySet["TransactionItem"],
+):
order.total_authorized_amount = get_total_authorized(
- order.payments.all(), order.currency
+ order_payments, order.currency
).amount
- order.total_authorized_amount += (
- sum(order.payment_transactions.values_list("authorized_value", flat=True)) or 0
+ order.total_authorized_amount += sum(
+ [tr.authorized_value for tr in order_transactions]
)
-def update_order_authorize_status(order: Order):
+def update_order_authorize_status(order: Order, granted_refund_amount: Decimal):
"""Update the current authorize status for the order.
- We treat the order as fully authorized when the sum of authorized and charged funds
- cover the order.total.
- We treat the order as partially authorized when the sum of authorized and charged
- funds covers only part of the order.total
- We treat the order as not authorized when the sum of authorized and charged funds is
- 0.
+ The order is fully authorized when total_authorized or total_charged funds
+ cover the order.total - order granted refunds
+ The order is partially authorized when total_authorized or total_charged
+ funds cover only part of the order.total - order granted refunds
+ The order is not authorized when total_authorized and total_charged funds are 0.
"""
total_covered = (
- order.total_authorized_amount + order.total_charged_amount or Decimal("0")
- )
+ order.total_authorized_amount + order.total_charged_amount
+ ) or Decimal(0)
total_covered = quantize_price(total_covered, order.currency)
- total_gross = order.total_gross_amount or Decimal("0")
- total_gross = quantize_price(total_gross, order.currency)
+ current_total_gross = order.total_gross_amount - granted_refund_amount
+ current_total_gross = max(current_total_gross, Decimal("0"))
+ current_total_gross = quantize_price(current_total_gross, order.currency)
- if total_covered == 0:
+ if total_covered == Decimal(0) and order.total.gross.amount == Decimal(0):
+ order.authorize_status = OrderAuthorizeStatus.FULL
+ elif total_covered == Decimal(0):
order.authorize_status = OrderAuthorizeStatus.NONE
- elif total_covered >= total_gross:
+ elif total_covered >= current_total_gross:
order.authorize_status = OrderAuthorizeStatus.FULL
else:
order.authorize_status = OrderAuthorizeStatus.PARTIAL
-def update_order_authorize_data(order: Order, with_save=True):
- _update_order_total_authorized(order)
- update_order_authorize_status(order)
+def update_order_authorize_data(
+ order: Order,
+ order_payments: Optional[QuerySet["Payment"]] = None,
+ order_transactions: Optional[QuerySet["TransactionItem"]] = None,
+ order_granted_refunds: Optional[QuerySet["OrderGrantedRefund"]] = None,
+ with_save=True,
+):
+ if order_payments is None:
+ order_payments = order.payments.all()
+ if order_transactions is None:
+ order_transactions = order.payment_transactions.all()
+ if order_granted_refunds is None:
+ order_granted_refunds = order.granted_refunds.all()
+ granted_refund_amount = sum(
+ [refund.amount.amount for refund in order_granted_refunds]
+ )
+ _update_order_total_authorized(
+ order, order_payments=order_payments, order_transactions=order_transactions
+ )
+ update_order_authorize_status(order, granted_refund_amount)
if with_save:
order.save(
update_fields=["total_authorized_amount", "authorize_status", "updated_at"]
)
+def updates_amounts_for_order(order: Order, save: bool = True):
+ order_payments = order.payments.all()
+ order_transactions = order.payment_transactions.all()
+ order_granted_refunds = order.granted_refunds.all()
+ update_order_charge_data(
+ order=order,
+ order_payments=order_payments,
+ order_transactions=order_transactions,
+ order_granted_refunds=order_granted_refunds,
+ with_save=False,
+ )
+ update_order_authorize_data(
+ order=order,
+ order_payments=order_payments,
+ order_transactions=order_transactions,
+ order_granted_refunds=order_granted_refunds,
+ with_save=False,
+ )
+ if save:
+ order.save(
+ update_fields=[
+ "total_charged_amount",
+ "charge_status",
+ "updated_at",
+ "total_authorized_amount",
+ "authorize_status",
+ ]
+ )
+
+
def update_order_display_gross_prices(order: "Order"):
"""Update Order's `display_gross_prices` DB field.
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 6b004239d2..6d8a970176 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -149,32 +149,29 @@ class TransactionAction:
The following actions are possible:
CHARGE - Represents the charge action.
REFUND - Represents a refund action.
- VOID - Represents a void action.
+ VOID - Represents a void action. This field will be removed
+ in Saleor 3.14 (Preview Feature). Use `CANCEL` instead.
+ CANCEL - Represents a cancel action. Added in Saleor 3.12.
"""
CHARGE = "charge"
REFUND = "refund"
VOID = "void"
+ CANCEL = "cancel"
CHOICES = [
(CHARGE, "Charge payment"),
(REFUND, "Refund payment"),
(VOID, "Void payment"),
+ (CANCEL, "Cancel payment"),
]
-class TransactionStatus:
- PENDING = "pending"
- SUCCESS = "success"
- FAILURE = "failure"
-
- CHOICES = [(PENDING, "Pending"), (SUCCESS, "Success"), (FAILURE, "Failure")]
-
-
class TransactionEventType:
"""Represents possible event types.
Added in Saleor 3.12.
+
The following types are possible:
AUTHORIZATION_SUCCESS - represents success authorization.
AUTHORIZATION_FAILURE - represents failure authorization.
@@ -229,3 +226,23 @@ class TransactionEventType:
(CANCEL_REQUEST, "Represents cancel request"),
(INFO, "Represents an info event"),
]
+
+
+class TransactionEventStatus:
+ """Represents a status of payment transaction.
+
+ The following statuses are possible:
+ SUCCESS - Represents a sucess action.
+ FAILURE - Represents a failure action.
+ PENDING - Represents a pending action.
+ """
+
+ 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 5697f14a5d..ff94397a8f 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -27,6 +27,7 @@ class TransactionCreateErrorCode(Enum):
NOT_FOUND = "not_found"
INCORRECT_CURRENCY = "incorrect_currency"
METADATA_KEY_REQUIRED = "metadata_key_required"
+ UNIQUE = "unique"
class TransactionUpdateErrorCode(Enum):
@@ -35,6 +36,7 @@ class TransactionUpdateErrorCode(Enum):
NOT_FOUND = "not_found"
INCORRECT_CURRENCY = "incorrect_currency"
METADATA_KEY_REQUIRED = "metadata_key_required"
+ UNIQUE = "unique"
class TransactionRequestActionErrorCode(Enum):
@@ -44,3 +46,11 @@ class TransactionRequestActionErrorCode(Enum):
MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK = (
"missing_transaction_action_request_webhook"
)
+
+
+class TransactionEventReportErrorCode(Enum):
+ INVALID = "invalid"
+ GRAPHQL_ERROR = "graphql_error"
+ NOT_FOUND = "not_found"
+ INCORRECT_DETAILS = "incorrect_details"
+ ALREADY_EXISTS = "already_exists"
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 065764a0dc..e1a827d45d 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -7,9 +7,9 @@ from ..app.models import App
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
from ..order.events import (
- event_transaction_capture_requested,
+ event_transaction_cancel_requested,
+ event_transaction_charge_requested,
event_transaction_refund_requested,
- event_transaction_void_requested,
)
from ..payment.interface import (
CustomerSource,
@@ -17,11 +17,14 @@ from ..payment.interface import (
RefundData,
TransactionActionData,
)
+from ..webhook.event_types import WebhookEventSyncType
+from ..webhook.utils import get_webhooks_for_event
from . import GatewayError, PaymentError, TransactionAction, TransactionKind
-from .models import Payment, Transaction, TransactionItem
+from .models import Payment, Transaction, TransactionEvent, TransactionItem
from .utils import (
clean_authorize,
clean_capture,
+ create_failed_transaction_event,
create_payment_information,
create_transaction,
gateway_postprocess,
@@ -81,6 +84,7 @@ def request_charge_action(
transaction: TransactionItem,
manager: "PluginsManager",
charge_value: Optional[Decimal],
+ request_event: TransactionEvent,
channel_slug: str,
user: Optional[User],
app: Optional[App],
@@ -88,17 +92,24 @@ def request_charge_action(
if charge_value is None:
charge_value = transaction.authorized_value
- _request_payment_action(
+ transaction_action_data = _create_transaction_data(
transaction=transaction,
- manager=manager,
action_type=TransactionAction.CHARGE,
action_value=charge_value,
+ request_event=request_event,
+ )
+ _request_payment_action(
+ transaction_action_data=transaction_action_data,
+ manager=manager,
channel_slug=channel_slug,
+ event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED,
+ transaction_request_func=manager.transaction_charge_requested,
+ plugin_func_name="transaction_charge_requested",
)
if order_id := transaction.order_id:
- event_transaction_capture_requested(
+ event_transaction_charge_requested(
order_id=order_id,
- reference=transaction.reference,
+ reference=transaction.psp_reference or "",
amount=quantize_price(charge_value, transaction.currency),
user=user,
app=app,
@@ -109,6 +120,7 @@ def request_refund_action(
transaction: TransactionItem,
manager: "PluginsManager",
refund_value: Optional[Decimal],
+ request_event: TransactionEvent,
channel_slug: str,
user: Optional[User],
app: Optional[App],
@@ -116,61 +128,131 @@ def request_refund_action(
if refund_value is None:
refund_value = transaction.charged_value
- _request_payment_action(
+ transaction_action_data = _create_transaction_data(
transaction=transaction,
- manager=manager,
action_type=TransactionAction.REFUND,
action_value=refund_value,
+ request_event=request_event,
+ )
+ _request_payment_action(
+ transaction_action_data=transaction_action_data,
+ manager=manager,
channel_slug=channel_slug,
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,
+ transaction_request_func=manager.transaction_refund_requested,
+ plugin_func_name="transaction_refund_requested",
)
+
if order_id := transaction.order_id:
event_transaction_refund_requested(
order_id=order_id,
- reference=transaction.reference,
+ reference=transaction.psp_reference or "",
amount=quantize_price(refund_value, transaction.currency),
user=user,
app=app,
)
-def request_void_action(
+def request_cancelation_action(
transaction: TransactionItem,
manager: "PluginsManager",
+ cancel_value: Optional[Decimal],
+ request_event: TransactionEvent,
channel_slug: str,
user: Optional[User],
app: Optional[App],
+ action: str,
):
- _request_payment_action(
+ transaction_action_data = _create_transaction_data(
transaction=transaction,
+ action_type=action,
+ action_value=cancel_value,
+ request_event=request_event,
+ )
+ _request_payment_action(
+ transaction_action_data=transaction_action_data,
manager=manager,
- action_type=TransactionAction.VOID,
- action_value=None,
channel_slug=channel_slug,
+ event_type=WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED,
+ transaction_request_func=manager.transaction_cancelation_requested,
+ plugin_func_name="transaction_cancelation_requested",
)
+
if order_id := transaction.order_id:
- event_transaction_void_requested(
- order_id=order_id, reference=transaction.reference, user=user, app=app
+ event_transaction_cancel_requested(
+ order_id=order_id,
+ reference=transaction.psp_reference or "",
+ user=user,
+ app=app,
)
-def _request_payment_action(
+def _create_transaction_data(
transaction: TransactionItem,
- manager: "PluginsManager",
- action_type: str,
+ action_type: "str",
action_value: Optional[Decimal],
- channel_slug: str,
+ request_event: TransactionEvent,
):
- payment_data = TransactionActionData(
- transaction=transaction, action_type=action_type, action_value=action_value
+ app_owner = None
+ if transaction.app_id:
+ app_owner = transaction.app
+ elif transaction.app_identifier:
+ app_owner = App.objects.filter(identifier=transaction.app_identifier).first()
+
+ return TransactionActionData(
+ transaction=transaction,
+ action_type=action_type,
+ action_value=action_value,
+ event=request_event,
+ transaction_app_owner=app_owner,
)
- event_active = manager.is_event_active_for_any_plugin(
+
+
+def _request_payment_action(
+ transaction_action_data: "TransactionActionData",
+ manager: "PluginsManager",
+ channel_slug: str,
+ event_type: str,
+ transaction_request_func: Callable[[TransactionActionData, str], None],
+ plugin_func_name: str,
+):
+ transaction_action_request_event_active = manager.is_event_active_for_any_plugin(
"transaction_action_request", channel_slug=channel_slug
)
- if not event_active:
+
+ transaction_request_event_active = manager.is_event_active_for_any_plugin(
+ plugin_func_name, channel_slug=channel_slug
+ )
+
+ webhooks = None
+ if transaction_action_data.transaction_app_owner:
+ webhooks = get_webhooks_for_event(
+ event_type=event_type,
+ apps_ids=[transaction_action_data.transaction_app_owner.pk],
+ )
+
+ if (
+ not transaction_action_request_event_active
+ and not transaction_request_event_active
+ and not webhooks
+ ):
+ create_failed_transaction_event(
+ transaction_action_data.event,
+ cause="No app or plugin is configured to handle payment action requests.",
+ )
raise PaymentError(
"No app or plugin is configured to handle payment action requests."
)
- manager.transaction_action_request(payment_data, channel_slug=channel_slug)
+
+ if transaction_request_event_active or webhooks:
+ # This if can be dropped in future releases as VOID will be dropped.
+ if transaction_action_data.action_type == TransactionAction.VOID:
+ transaction_action_data.action_type = TransactionAction.CANCEL
+ transaction_request_func(transaction_action_data, channel_slug)
+ else:
+ manager.transaction_action_request(
+ transaction_action_data, channel_slug=channel_slug
+ )
@raise_payment_error
diff --git a/saleor/payment/gateways/np_atobarai/tests/conftest.py b/saleor/payment/gateways/np_atobarai/tests/conftest.py
index 6cdbaf0eb7..626aee36c3 100644
--- a/saleor/payment/gateways/np_atobarai/tests/conftest.py
+++ b/saleor/payment/gateways/np_atobarai/tests/conftest.py
@@ -162,7 +162,6 @@ 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 1e8dc25b68..4ad87b9071 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -1,13 +1,17 @@
from dataclasses import InitVar, dataclass, field
+from datetime import datetime
from decimal import Decimal
from enum import Enum
from functools import cached_property
-from typing import Any, Callable, Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
from ..order import FulfillmentLineData
from ..order.fetch import OrderLineInfo
-from ..payment.models import TransactionItem
+from ..payment.models import TransactionEvent, TransactionItem
+from . import TransactionEventType
+if TYPE_CHECKING:
+ from ..app.models import App
JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
@@ -16,9 +20,27 @@ JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
class TransactionActionData:
action_type: str
transaction: TransactionItem
+ event: "TransactionEvent"
+ transaction_app_owner: Optional["App"]
action_value: Optional[Decimal] = None
+@dataclass
+class TransactionRequestEventResponse:
+ psp_reference: str
+ type: "TransactionEventType"
+ amount: Optional[Decimal] = None
+ time: Optional[datetime] = None
+ external_url: Optional[str] = ""
+ message: Optional[str] = ""
+
+
+@dataclass
+class TransactionRequestResponse:
+ psp_reference: str
+ event: Optional["TransactionRequestEventResponse"] = None
+
+
@dataclass
class TransactionData:
token: str
diff --git a/saleor/payment/migrations/0039_transactionevent_currency.py b/saleor/payment/migrations/0039_transactionevent_currency.py
index 78d34a124c..9a5f33c343 100644
--- a/saleor/payment/migrations/0039_transactionevent_currency.py
+++ b/saleor/payment/migrations/0039_transactionevent_currency.py
@@ -1,18 +1,25 @@
from django.db import migrations
-from django.apps import apps as registry
-from django.db.models.signals import post_migrate
+from django.db.models import F, OuterRef, QuerySet, Subquery
-from .tasks.saleor3_12 import (
- set_default_currency_for_transaction_event_task,
-)
+
+def set_default_currency_for_transaction_event(qs: QuerySet):
+ qs.update(currency=F("transaction_currency"))
def set_default_currency_for_transaction_event_migration(apps, _schema_editor):
- def on_migrations_complete(sender=None, **kwargs):
- set_default_currency_for_transaction_event_task.delay()
+ TransactionItem = apps.get_model("payment", "TransactionItem")
+ TransactionEvent = apps.get_model("payment", "TransactionEvent")
+
+ transaction_item = TransactionItem.objects.filter(
+ pk=OuterRef("transaction")
+ ).values("currency")
+ qs = (
+ TransactionEvent.objects.filter(currency__isnull=True)
+ .order_by("-pk")
+ .annotate(transaction_currency=Subquery(transaction_item))
+ )
- sender = registry.get_app_config("payment")
- post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+ set_default_currency_for_transaction_event(qs)
class Migration(migrations.Migration):
diff --git a/saleor/payment/migrations/0040_migrate_renamed_fields.py b/saleor/payment/migrations/0040_migrate_renamed_fields.py
index 6e4233dd10..4e46a57a6c 100644
--- a/saleor/payment/migrations/0040_migrate_renamed_fields.py
+++ b/saleor/payment/migrations/0040_migrate_renamed_fields.py
@@ -1,26 +1,74 @@
-from django.apps import apps as registry
from django.db import migrations
-from django.db.models.signals import post_migrate
+from django.db.models import F, Q, QuerySet
-from .tasks.saleor3_12 import (
- transaction_event_migrate_name_to_message_task,
- transaction_event_migrate_reference_to_psp_reference_task,
- transaction_item_migrate_reference_to_psp_reference_task,
- transaction_item_migrate_type_to_name_task,
- transaction_item_migrate_voided_to_canceled_task,
-)
+
+def transaction_item_migrate_type_to_name(qs: QuerySet):
+ qs.update(name=F("type"))
+
+
+def transaction_item_migrate_type_to_name_task(transaction_item):
+ qs = transaction_item.objects.filter(
+ (Q(name__isnull=True) & Q(type__isnull=False)) | (Q(name="") & ~Q(type=""))
+ ).order_by("-pk")
+
+ transaction_item_migrate_type_to_name(qs)
+
+
+def transaction_item_migrate_reference_to_psp_reference(qs: QuerySet):
+ qs.update(psp_reference=F("reference"))
+
+
+def transaction_item_migrate_reference_to_psp_reference_task(transaction_item):
+ qs = transaction_item.objects.filter(psp_reference__isnull=True).order_by("-pk")
+
+ transaction_item_migrate_reference_to_psp_reference(qs)
+
+
+def transaction_item_migrate_voided_to_canceled(qs: QuerySet):
+ qs.update(canceled_value=F("voided_value"))
+
+
+def transaction_item_migrate_voided_to_canceled_task(transaction_item):
+ qs = transaction_item.objects.filter(~Q(canceled_value=F("voided_value"))).order_by(
+ "-pk"
+ )
+
+ transaction_item_migrate_voided_to_canceled(qs)
+
+
+def transaction_event_migrate_name_to_message(qs: QuerySet):
+ qs.update(message=F("name"))
+
+
+def transaction_event_migrate_name_to_message_task(transaction_event):
+ qs = transaction_event.objects.filter(
+ (Q(message__isnull=True) & Q(name__isnull=False))
+ | (Q(message="") & ~Q(name=""))
+ ).order_by("-pk")
+
+ transaction_event_migrate_name_to_message(qs)
+
+
+def transaction_event_migrate_reference_to_psp_reference(qs: QuerySet):
+ qs.update(psp_reference=F("reference"))
+
+
+def transaction_event_migrate_reference_to_psp_reference_task(transaction_event):
+ qs = transaction_event.objects.filter(~Q(psp_reference=F("reference"))).order_by(
+ "-pk"
+ )
+
+ transaction_event_migrate_reference_to_psp_reference(qs)
def migrate_data_for_renamed_fields(apps, _schema_editor):
- def on_migrations_complete(sender=None, **kwargs):
- transaction_event_migrate_name_to_message_task.delay()
- transaction_event_migrate_reference_to_psp_reference_task.delay()
- transaction_item_migrate_reference_to_psp_reference_task.delay()
- transaction_item_migrate_type_to_name_task.delay()
- transaction_item_migrate_voided_to_canceled_task.delay()
-
- sender = registry.get_app_config("payment")
- post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+ TransactionItem = apps.get_model("payment", "TransactionItem")
+ TransactionEvent = apps.get_model("payment", "TransactionEvent")
+ transaction_event_migrate_name_to_message_task(TransactionEvent)
+ transaction_event_migrate_reference_to_psp_reference_task(TransactionEvent)
+ transaction_item_migrate_reference_to_psp_reference_task(TransactionItem)
+ transaction_item_migrate_type_to_name_task(TransactionItem)
+ transaction_item_migrate_voided_to_canceled_task(TransactionItem)
class Migration(migrations.Migration):
diff --git a/saleor/payment/migrations/0041_add_calculation_transaction_events.py b/saleor/payment/migrations/0041_add_calculation_transaction_events.py
index c4cb6fc08e..a7ed70727d 100644
--- a/saleor/payment/migrations/0041_add_calculation_transaction_events.py
+++ b/saleor/payment/migrations/0041_add_calculation_transaction_events.py
@@ -1,24 +1,148 @@
+from decimal import Decimal
+
from django.db import migrations
-from django.apps import apps as registry
-from django.db.models.signals import post_migrate
+from django.db.models import Case, Exists, F, Func, OuterRef, Q, Subquery, When
+
+
+def create_transaction_events(transaction_event, transactions_qs, type):
+ transaction_events = []
+ for pk, amount, amount_sum, currency in transactions_qs:
+ amount_sum = 0 if not amount_sum else amount_sum
+ transaction_events.append(
+ transaction_event(
+ transaction_id=pk,
+ type=type,
+ amount_value=amount - amount_sum,
+ currency=currency,
+ include_in_calculations=True,
+ message="Manual adjustment of the transaction.",
+ )
+ )
+ if transaction_events:
+ transaction_event.objects.bulk_create(transaction_events)
+
+
+def _get_events(transaction_event, type):
+ return (
+ transaction_event.objects.filter(
+ transaction=OuterRef("pk"), type=type, include_in_calculations=True
+ )
+ .annotate(amount_sum=Func(F("amount_value"), function="Sum"))
+ .values("amount_sum")
+ )
+
+
+def create_event_for_authorized(transaction_event, transaction_qs):
+ transaction_events = []
+
+ for pk, amount, currency in transaction_qs:
+ transaction_events.append(
+ transaction_event(
+ transaction_id=pk,
+ type="authorization_success",
+ amount_value=amount,
+ currency=currency,
+ include_in_calculations=True,
+ message="Manual adjustment of the transaction.",
+ )
+ )
+ if transaction_events:
+ transaction_event.objects.bulk_create(transaction_events)
+
+
+def create_event_for_authorized_task(transaction_item, transaction_event):
+ authorize_events = transaction_event.objects.filter(
+ Q(transaction=OuterRef("pk"))
+ & (Q(type="authorization_success") | Q(type="authorization_adjustment"))
+ & Q(include_in_calculations=True)
+ )
+ qs = (
+ transaction_item.objects.filter(
+ ~Q(authorized_value=Decimal(0)),
+ ~Exists(authorize_events),
+ )
+ .order_by("-pk")
+ .values_list("id", "authorized_value", "currency")
+ )
+
+ create_event_for_authorized(transaction_event, qs)
+
+
+def create_event_for_charged_task(transaction_item, transaction_event):
+ type = "charge_success"
+ events = _get_events(transaction_event, type)
+ qs = (
+ (
+ transaction_item.objects.filter(~Q(charged_value=Decimal(0)))
+ .annotate(
+ amount_sum_temp=Subquery(events),
+ amount_sum=Case(
+ When(amount_sum_temp__isnull=True, then=Decimal(0)),
+ default=F("amount_sum_temp"),
+ ),
+ )
+ .filter(charged_value__gt=F("amount_sum"))
+ )
+ .order_by("-pk")
+ .values_list("id", "charged_value", "amount_sum", "currency")
+ )
+
+ create_transaction_events(transaction_event, qs, type)
+
+
+def create_event_for_refunded_task(transaction_item, transaction_event):
+ type = "refund_success"
+ events = _get_events(transaction_event, type)
+ qs = (
+ (
+ transaction_item.objects.filter(~Q(refunded_value=Decimal(0)))
+ .annotate(
+ amount_sum_temp=Subquery(events),
+ amount_sum=Case(
+ When(amount_sum_temp__isnull=True, then=Decimal(0)),
+ default=F("amount_sum_temp"),
+ ),
+ )
+ .filter(refunded_value__gt=F("amount_sum"))
+ )
+ .order_by("-pk")
+ .values_list("id", "refunded_value", "amount_sum", "currency")
+ )
+
+ create_transaction_events(transaction_event, qs, type)
+
+
+def create_event_for_canceled_task(transaction_item, transaction_event):
+ type = "cancel_success"
+ events = _get_events(transaction_event, type)
+ # voided_value instead of canceled_value cause some data may not be migrated yet
+ qs = (
+ (
+ transaction_item.objects.filter(~Q(voided_value=Decimal(0)))
+ .annotate(
+ amount_sum_temp=Subquery(events),
+ amount_sum=Case(
+ When(amount_sum_temp__isnull=True, then=Decimal(0)),
+ default=F("amount_sum_temp"),
+ ),
+ )
+ .filter(voided_value__gt=F("amount_sum"))
+ )
+ .order_by("-pk")
+ .values_list("id", "voided_value", "amount_sum", "currency")
+ )
-from .tasks.saleor3_12 import (
- create_event_for_authorized_task,
- create_event_for_canceled_task,
- create_event_for_charged_task,
- create_event_for_refunded_task,
-)
+ create_transaction_events(transaction_event, qs, type)
-def create_transaction_events(apps, schema_editor):
- def on_migrations_complete(sender=None, **kwargs):
- create_event_for_authorized_task.delay()
- create_event_for_canceled_task.delay()
- create_event_for_charged_task.delay()
- create_event_for_refunded_task.delay()
+def create_transaction_events_migration(apps, schema_editor):
+ TransactionItem = apps.get_model("payment", "TransactionItem")
+ TransactionEvent = apps.get_model("payment", "TransactionEvent")
- sender = registry.get_app_config("payment")
- post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+ create_event_for_authorized_task(TransactionItem, TransactionEvent)
+ create_event_for_canceled_task(TransactionItem, TransactionEvent)
+ create_event_for_charged_task(TransactionItem, TransactionEvent)
+ create_event_for_refunded_task(TransactionItem, TransactionEvent)
class Migration(migrations.Migration):
@@ -27,5 +151,7 @@ class Migration(migrations.Migration):
]
operations = [
- migrations.RunPython(create_transaction_events, migrations.RunPython.noop),
+ migrations.RunPython(
+ create_transaction_events_migration, migrations.RunPython.noop
+ ),
]
diff --git a/saleor/payment/migrations/0042_alter_transactionitem_available_actions.py b/saleor/payment/migrations/0042_alter_transactionitem_available_actions.py
new file mode 100644
index 0000000000..32446e4b72
--- /dev/null
+++ b/saleor/payment/migrations/0042_alter_transactionitem_available_actions.py
@@ -0,0 +1,30 @@
+# Generated by Django 3.2.18 on 2023-03-15 07:36
+
+import django.contrib.postgres.fields
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0041_add_calculation_transaction_events"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="transactionitem",
+ name="available_actions",
+ field=django.contrib.postgres.fields.ArrayField(
+ base_field=models.CharField(
+ choices=[
+ ("charge", "Charge payment"),
+ ("refund", "Refund payment"),
+ ("void", "Void payment"),
+ ("cancel", "Cancel payment"),
+ ],
+ max_length=128,
+ ),
+ default=list,
+ size=None,
+ ),
+ ),
+ ]
diff --git a/saleor/payment/migrations/0043_drop_from_state_renamed_fields.py b/saleor/payment/migrations/0043_drop_from_state_renamed_fields.py
new file mode 100644
index 0000000000..5a0f866f07
--- /dev/null
+++ b/saleor/payment/migrations/0043_drop_from_state_renamed_fields.py
@@ -0,0 +1,72 @@
+from decimal import Decimal
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0042_alter_transactionitem_available_actions"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ database_operations=[
+ migrations.AlterField(
+ model_name="transactionevent",
+ name="name",
+ field=models.CharField(
+ blank=True, default="", max_length=512, null=True
+ ),
+ ),
+ migrations.AlterField(
+ model_name="transactionevent",
+ name="reference",
+ field=models.CharField(
+ blank=True, default="", max_length=512, null=True
+ ),
+ ),
+ migrations.AlterField(
+ model_name="transactionitem",
+ name="reference",
+ field=models.CharField(
+ blank=True, default="", max_length=512, null=True
+ ),
+ ),
+ migrations.AlterField(
+ model_name="transactionitem",
+ name="type",
+ field=models.CharField(
+ blank=True, default="", max_length=512, null=True
+ ),
+ ),
+ migrations.AlterField(
+ model_name="transactionitem",
+ name="voided_value",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12, null=True
+ ),
+ ),
+ ],
+ state_operations=[
+ migrations.RemoveField(
+ model_name="transactionevent",
+ name="name",
+ ),
+ migrations.RemoveField(
+ model_name="transactionevent",
+ name="reference",
+ ),
+ migrations.RemoveField(
+ model_name="transactionitem",
+ name="reference",
+ ),
+ migrations.RemoveField(
+ model_name="transactionitem",
+ name="type",
+ ),
+ migrations.RemoveField(
+ model_name="transactionitem",
+ name="voided_value",
+ ),
+ ],
+ )
+ ]
diff --git a/saleor/payment/migrations/0044_transactionevent_currency.py b/saleor/payment/migrations/0044_transactionevent_currency.py
new file mode 100644
index 0000000000..8951f74496
--- /dev/null
+++ b/saleor/payment/migrations/0044_transactionevent_currency.py
@@ -0,0 +1,28 @@
+from django.db import migrations
+
+
+# This data migration is handled in the 0039 with celery tasks.
+# 0039 is due to zero-downtime policy, this migration is to ensure
+# that we can change currency to non-nullable.
+def set_default_currency_for_transaction_event(apps, schema_editor):
+ TransactionItem = apps.get_model("payment", "TransactionItem")
+ TransactionEvent = apps.get_model("payment", "TransactionEvent")
+
+ for currency in (
+ TransactionItem.objects.values_list("currency", flat=True).distinct().order_by()
+ ):
+ TransactionEvent.objects.filter(
+ currency=None, transaction__currency=currency
+ ).update(currency=currency)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0043_drop_from_state_renamed_fields"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ set_default_currency_for_transaction_event, migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/payment/migrations/0045_alter_transactionevent_currency.py b/saleor/payment/migrations/0045_alter_transactionevent_currency.py
new file mode 100644
index 0000000000..d6eff085ca
--- /dev/null
+++ b/saleor/payment/migrations/0045_alter_transactionevent_currency.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0044_transactionevent_currency"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="transactionevent",
+ name="currency",
+ field=models.CharField(max_length=3),
+ ),
+ ]
diff --git a/saleor/payment/migrations/tasks/saleor3_12.py b/saleor/payment/migrations/tasks/saleor3_12.py
deleted file mode 100644
index bb3e22c80e..0000000000
--- a/saleor/payment/migrations/tasks/saleor3_12.py
+++ /dev/null
@@ -1,262 +0,0 @@
-from decimal import Decimal
-
-from django.db.models import (
- Case,
- Exists,
- F,
- Func,
- OuterRef,
- Subquery,
- Q,
- QuerySet,
- When,
-)
-
-from ....celeryconf import app
-from ...models import TransactionEvent, TransactionItem
-
-# Batch size of 1000 is about ~20MB of memory usage in task
-BATCH_SIZE = 1000
-
-
-def create_transaction_events(transactions_qs, type):
- transaction_events = []
- for pk, amount, amount_sum, currency in transactions_qs:
- amount_sum = 0 if not amount_sum else amount_sum
- transaction_events.append(
- TransactionEvent(
- transaction_id=pk,
- type=type,
- amount_value=amount - amount_sum,
- currency=currency,
- include_in_calculations=True,
- message="Manual adjustment of the transaction.",
- )
- )
- if transaction_events:
- TransactionEvent.objects.bulk_create(transaction_events)
-
-
-def _get_events(type):
- return (
- TransactionEvent.objects.filter(
- transaction=OuterRef("pk"), type=type, include_in_calculations=True
- )
- .annotate(amount_sum=Func(F("amount_value"), function="Sum"))
- .values("amount_sum")
- )
-
-
-def create_event_for_authorized(transaction_qs):
- transaction_events = []
-
- for pk, amount, currency in transaction_qs:
- transaction_events.append(
- TransactionEvent(
- transaction_id=pk,
- type="authorization_success",
- amount_value=amount,
- currency=currency,
- include_in_calculations=True,
- message="Manual adjustment of the transaction.",
- )
- )
- if transaction_events:
- TransactionEvent.objects.bulk_create(transaction_events)
-
-
-def create_event_for_authorized_task():
- authorize_events = TransactionEvent.objects.filter(
- Q(transaction=OuterRef("pk"))
- & (Q(type="authorization_success") | Q(type="authorization_adjustment"))
- & Q(include_in_calculations=True)
- )
- qs = TransactionItem.objects.filter(
- ~Q(authorized_value=Decimal(0)),
- ~Exists(authorize_events),
- ).order_by("-pk")
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids).values_list("id", "authorized_value", "currency")
-
- if ids:
- create_event_for_authorized(qs)
- create_event_for_authorized_task.delay()
-
-
-def create_event_for_charged_task():
- type = "charge_success"
- events = _get_events(type)
- qs = (
- TransactionItem.objects.filter(~Q(charged_value=Decimal(0)))
- .annotate(
- amount_sum_temp=Subquery(events),
- amount_sum=Case(
- When(amount_sum_temp__isnull=True, then=Decimal(0)),
- default=F("amount_sum_temp"),
- ),
- )
- .filter(charged_value__gt=F("amount_sum"))
- ).order_by("-pk")
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids).values_list(
- "id", "charged_value", "amount_sum", "currency"
- )
-
- if ids:
- create_transaction_events(qs, type)
- create_event_for_charged_task.delay()
-
-
-def create_event_for_refunded_task():
- type = "refund_success"
- events = _get_events(type)
- qs = (
- TransactionItem.objects.filter(~Q(refunded_value=Decimal(0)))
- .annotate(
- amount_sum_temp=Subquery(events),
- amount_sum=Case(
- When(amount_sum_temp__isnull=True, then=Decimal(0)),
- default=F("amount_sum_temp"),
- ),
- )
- .filter(refunded_value__gt=F("amount_sum"))
- ).order_by("-pk")
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids).values_list(
- "id", "refunded_value", "amount_sum", "currency"
- )
-
- if ids:
- create_transaction_events(qs, type)
- create_event_for_refunded_task.delay()
-
-
-def create_event_for_canceled_task():
- type = "cancel_success"
- events = _get_events(type)
- # voided_value instead of canceled_value cause some data may not be migrated yet
- qs = (
- TransactionItem.objects.filter(~Q(voided_value=Decimal(0)))
- .annotate(
- amount_sum_temp=Subquery(events),
- amount_sum=Case(
- When(amount_sum_temp__isnull=True, then=Decimal(0)),
- default=F("amount_sum_temp"),
- ),
- )
- .filter(voided_value__gt=F("amount_sum"))
- ).order_by("-pk")
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids).values_list(
- "id", "voided_value", "amount_sum", "currency"
- )
-
- if ids:
- create_transaction_events(qs, type)
- create_event_for_canceled_task.delay()
-
-
-def transaction_item_migrate_type_to_name(qs: QuerySet):
- qs.update(name=F("type"))
-
-
-def transaction_item_migrate_type_to_name_task():
- qs = TransactionItem.objects.filter(
- (Q(name__isnull=True) & Q(type__isnull=False)) | (Q(name="") & ~Q(type=""))
- ).order_by("-pk")
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids)
-
- if ids:
- transaction_item_migrate_type_to_name(qs)
- transaction_item_migrate_type_to_name_task.delay()
-
-
-def transaction_item_migrate_reference_to_psp_reference(qs: QuerySet):
- qs.update(psp_reference=F("reference"))
-
-
-def transaction_item_migrate_reference_to_psp_reference_task():
- qs = TransactionItem.objects.filter(psp_reference__isnull=True).order_by("-pk")
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids)
-
- if ids:
- transaction_item_migrate_reference_to_psp_reference(qs)
- transaction_item_migrate_reference_to_psp_reference_task.delay()
-
-
-def transaction_item_migrate_voided_to_canceled(qs: QuerySet):
- qs.update(canceled_value=F("voided_value"))
-
-
-def transaction_item_migrate_voided_to_canceled_task():
- qs = TransactionItem.objects.filter(~Q(canceled_value=F("voided_value"))).order_by(
- "-pk"
- )
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids)
-
- if ids:
- transaction_item_migrate_voided_to_canceled(qs)
- transaction_item_migrate_voided_to_canceled_task.delay()
-
-
-def transaction_event_migrate_name_to_message(qs: QuerySet):
- qs.update(message=F("name"))
-
-
-def transaction_event_migrate_name_to_message_task():
- qs = TransactionEvent.objects.filter(
- (Q(message__isnull=True) & Q(name__isnull=False))
- | (Q(message="") & ~Q(name=""))
- ).order_by("-pk")
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids)
-
- if ids:
- transaction_event_migrate_name_to_message(qs)
- transaction_event_migrate_name_to_message_task.delay()
-
-
-def transaction_event_migrate_reference_to_psp_reference(qs: QuerySet):
- qs.update(psp_reference=F("reference"))
-
-
-def transaction_event_migrate_reference_to_psp_reference_task():
- qs = TransactionEvent.objects.filter(~Q(psp_reference=F("reference"))).order_by(
- "-pk"
- )
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids)
-
- if ids:
- transaction_event_migrate_reference_to_psp_reference(qs)
- transaction_event_migrate_reference_to_psp_reference_task.delay()
-
-
-def set_default_currency_for_transaction_event(qs: QuerySet):
- qs.update(currency=F("transaction_currency"))
-
-
-def set_default_currency_for_transaction_event_task():
- transaction_item = TransactionItem.objects.filter(
- pk=OuterRef("transaction")
- ).values("currency")
- qs = TransactionEvent.objects.filter(currency__isnull=True).order_by("-pk")
- ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
- qs = qs.filter(pk__in=ids).annotate(transaction_currency=Subquery(transaction_item))
-
- if ids:
- set_default_currency_for_transaction_event(qs)
- set_default_currency_for_transaction_event_task.delay()
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 8d2467c0ee..79214f6e39 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -21,9 +21,9 @@ from . import (
CustomPaymentChoices,
StorePaymentMethod,
TransactionAction,
+ TransactionEventStatus,
TransactionEventType,
TransactionKind,
- TransactionStatus,
)
@@ -31,8 +31,6 @@ 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, null=True, default="")
- type = models.CharField(max_length=512, blank=True, default="")
- reference = models.CharField(max_length=512, blank=True, default="")
name = models.CharField(max_length=512, blank=True, null=True, default="")
message = models.CharField(max_length=512, blank=True, null=True, default="")
psp_reference = models.CharField(max_length=512, blank=True, null=True)
@@ -65,12 +63,6 @@ class TransactionItem(ModelWithMetadata):
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"),
- )
amount_canceled = MoneyField(
amount_field="canceled_value", currency_field="currency"
)
@@ -164,26 +156,18 @@ class TransactionEvent(models.Model):
created_at = models.DateTimeField(default=timezone.now)
status = models.CharField(
max_length=128,
- choices=TransactionStatus.CHOICES,
- default=TransactionStatus.SUCCESS,
+ choices=TransactionEventStatus.CHOICES,
+ default=TransactionEventStatus.SUCCESS,
blank=True,
null=True,
)
- reference = models.CharField(max_length=512, blank=True, default="")
psp_reference = models.CharField(max_length=512, blank=True, null=True)
-
- name = models.CharField(max_length=512, blank=True, default="")
message = models.CharField(max_length=512, blank=True, null=True, default="")
-
transaction = models.ForeignKey(
TransactionItem, related_name="events", on_delete=models.CASCADE
)
external_url = models.URLField(blank=True, null=True)
- currency = models.CharField(
- max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
- null=True,
- blank=True,
- )
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH)
type = models.CharField(
max_length=128,
choices=TransactionEventType.CHOICES,
@@ -430,7 +414,9 @@ class Transaction(models.Model):
action_required_data = JSONField(
blank=True, default=dict, encoder=DjangoJSONEncoder
)
- currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH)
+ currency = models.CharField(
+ max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
+ )
amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
diff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.py
index 96b65e7140..961aa5ecea 100644
--- a/saleor/payment/tests/test_gateway.py
+++ b/saleor/payment/tests/test_gateway.py
@@ -10,10 +10,15 @@ from .. import (
CustomPaymentChoices,
PaymentError,
TransactionAction,
+ TransactionEventType,
TransactionKind,
gateway,
)
-from ..gateway import request_charge_action, request_refund_action, request_void_action
+from ..gateway import (
+ request_cancelation_action,
+ request_charge_action,
+ request_refund_action,
+)
from ..interface import GatewayResponse, TransactionActionData
from ..models import TransactionItem
from ..utils import create_payment_information
@@ -328,21 +333,26 @@ def test_list_gateways(fake_payment_interface):
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
-def test_request_capture_action_missing_active_event(
+def test_request_charge_action_missing_active_event(
mocked_is_active, order, staff_user
):
# given
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_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")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ mocked_is_active.return_value = False
# when & then
with pytest.raises(PaymentError):
@@ -353,26 +363,32 @@ def test_request_capture_action_missing_active_event(
channel_slug=order.channel.slug,
user=staff_user,
app=None,
+ request_event=requested_event,
)
@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
+def test_request_charge_action_with_transaction_action_request(
+ mocked_transaction_request, mocked_is_active, order, staff_user
):
# given
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_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")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ mocked_is_active.side_effect = [True, False]
# when
request_charge_action(
@@ -382,43 +398,105 @@ def test_request_capture_action_on_order(
channel_slug=order.channel.slug,
user=staff_user,
app=None,
+ request_event=requested_event,
)
# then
assert mocked_is_active.called
- mocked_transaction_action_request.assert_called_once_with(
+ mocked_transaction_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CHARGE,
action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
),
channel_slug=order.channel.slug,
)
event = order.events.first()
- assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED
+ assert event.type == OrderEvents.TRANSACTION_CHARGE_REQUESTED
assert Decimal(event.parameters["amount"]) == action_value
- assert event.parameters["reference"] == transaction.reference
+ assert event.parameters["reference"] == transaction.psp_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
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_request_charge_action_on_order(
+ mocked_transaction_request, mocked_is_active, order, staff_user
):
# given
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_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")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ mocked_is_active.side_effect = [False, True]
+
+ # when
+ request_charge_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ charge_value=action_value,
+ channel_slug=order.channel.slug,
+ user=staff_user,
+ app=None,
+ request_event=requested_event,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CHARGE,
+ action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
+ ),
+ order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CHARGE_REQUESTED
+ assert Decimal(event.parameters["amount"]) == action_value
+ assert event.parameters["reference"] == transaction.psp_reference
+ assert event.user == staff_user
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_request_charge_action_by_app(
+ mocked_transaction_request, mocked_is_active, order, app
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ mocked_is_active.side_effect = [False, True]
# when
request_charge_action(
@@ -428,43 +506,51 @@ def test_request_capture_action_by_app(
channel_slug=order.channel.slug,
user=None,
app=app,
+ request_event=requested_event,
)
# then
assert mocked_is_active.called
- mocked_transaction_action_request.assert_called_once_with(
+ mocked_transaction_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CHARGE,
action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
),
- channel_slug=order.channel.slug,
+ order.channel.slug,
)
event = order.events.first()
- assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED
+ assert event.type == OrderEvents.TRANSACTION_CHARGE_REQUESTED
assert Decimal(event.parameters["amount"]) == action_value
- assert event.parameters["reference"] == transaction.reference
+ assert event.parameters["reference"] == transaction.psp_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
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_request_charge_action_on_checkout(
+ mocked_transaction_request, mocked_is_active, checkout, staff_user
):
# given
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_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")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ mocked_is_active.side_effect = [False, True]
# when
request_charge_action(
@@ -474,17 +560,20 @@ def test_request_capture_action_on_checkout(
channel_slug=checkout.channel.slug,
user=staff_user,
app=None,
+ request_event=requested_event,
)
# then
assert mocked_is_active.called
- mocked_transaction_action_request.assert_called_once_with(
+ mocked_transaction_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CHARGE,
action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
),
- channel_slug=checkout.channel.slug,
+ checkout.channel.slug,
)
@@ -495,15 +584,20 @@ def test_request_refund_action_missing_active_event(
# given
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["refund"],
currency="USD",
order_id=order.pk,
charged_value=Decimal("10"),
)
- mocked_is_active.return_value = False
action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ )
+ mocked_is_active.return_value = False
# when & then
with pytest.raises(PaymentError):
@@ -514,26 +608,32 @@ def test_request_refund_action_missing_active_event(
channel_slug=order.channel.slug,
user=staff_user,
app=None,
+ request_event=requested_event,
)
@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
+def test_request_refund_action_with_transaction_action_request(
+ mocked_transaction_request, mocked_is_active, order, staff_user
):
# given
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["refund"],
currency="USD",
order_id=order.pk,
charged_value=Decimal("10"),
)
- mocked_is_active.return_value = True
action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ )
+ mocked_is_active.side_effect = [True, False]
# when
request_refund_action(
@@ -543,15 +643,18 @@ def test_request_refund_action_on_order(
channel_slug=order.channel.slug,
user=staff_user,
app=None,
+ request_event=requested_event,
)
# then
assert mocked_is_active.called
- mocked_transaction_action_request.assert_called_once_with(
+ mocked_transaction_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.REFUND,
action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
),
channel_slug=order.channel.slug,
)
@@ -559,27 +662,86 @@ def test_request_refund_action_on_order(
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.parameters["reference"] == transaction.psp_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")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
+def test_request_refund_action_on_order(
+ mocked_transaction_request, mocked_is_active, order, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ charged_value=Decimal("10"),
+ )
+ action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ )
+ mocked_is_active.side_effect = [False, True]
+
+ # when
+ request_refund_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ refund_value=action_value,
+ channel_slug=order.channel.slug,
+ user=staff_user,
+ app=None,
+ request_event=requested_event,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
+ ),
+ 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.psp_reference
+ assert event.user == staff_user
+
+
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
def test_request_refund_action_by_app(
- mocked_transaction_action_request, mocked_is_active, order, app
+ mocked_transaction_request, mocked_is_active, order, app
):
# given
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["refund"],
currency="USD",
order_id=order.pk,
charged_value=Decimal("10"),
)
- mocked_is_active.return_value = True
action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ )
+ mocked_is_active.side_effect = [False, True]
# when
request_refund_action(
@@ -589,44 +751,52 @@ def test_request_refund_action_by_app(
channel_slug=order.channel.slug,
user=None,
app=app,
+ request_event=requested_event,
)
# then
assert mocked_is_active.called
- mocked_transaction_action_request.assert_called_once_with(
+ mocked_transaction_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.REFUND,
action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
),
- channel_slug=order.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.parameters["reference"] == transaction.psp_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")
+@patch("saleor.plugins.manager.PluginsManager.transaction_refund_requested")
def test_request_refund_action_on_checkout(
- mocked_transaction_action_request, mocked_is_active, checkout, staff_user
+ mocked_transaction_request, mocked_is_active, checkout, staff_user
):
# given
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["refund"],
currency="USD",
checkout_id=checkout.pk,
charged_value=Decimal("10"),
)
- mocked_is_active.return_value = True
action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ )
+ mocked_is_active.side_effect = [False, True]
# when
request_refund_action(
@@ -636,167 +806,257 @@ def test_request_refund_action_on_checkout(
channel_slug=checkout.channel.slug,
user=staff_user,
app=None,
+ request_event=requested_event,
)
# then
assert mocked_is_active.called
- mocked_transaction_action_request.assert_called_once_with(
+ mocked_transaction_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
action_type=TransactionAction.REFUND,
action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
),
- channel_slug=checkout.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):
+def test_request_cancelation_action_missing_active_event(
+ mocked_is_active, order, staff_user
+):
# given
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["capture", "void"],
currency="USD",
order_id=order.pk,
authorized_value=Decimal("10"),
)
+ requested_event = transaction.events.create(
+ currency=transaction.currency,
+ type=TransactionEventType.CANCEL_REQUEST,
+ )
+
mocked_is_active.return_value = False
# when & then
with pytest.raises(PaymentError):
- request_void_action(
+ request_cancelation_action(
transaction=transaction,
manager=get_plugins_manager(),
+ cancel_value=None,
channel_slug=order.channel.slug,
user=staff_user,
app=None,
+ request_event=requested_event,
+ action=TransactionAction.CANCEL,
)
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_cancelation_requested")
+def test_request_cancelation_action_on_order(
+ mocked_transaction_request, mocked_is_active, order, staff_user
+):
+ # given
+ transaction = TransactionItem.objects.create(
+ status="Authorized",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ )
+ requested_event = transaction.events.create(
+ currency=transaction.currency,
+ type=TransactionEventType.CANCEL_REQUEST,
+ )
+ mocked_is_active.side_effect = [False, True]
+
+ # when
+ request_cancelation_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ cancel_value=None,
+ channel_slug=order.channel.slug,
+ user=staff_user,
+ app=None,
+ request_event=requested_event,
+ action=TransactionAction.CANCEL,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CANCEL,
+ action_value=None,
+ event=requested_event,
+ transaction_app_owner=None,
+ ),
+ order.channel.slug,
+ )
+
+ event = order.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CANCEL_REQUESTED
+ assert event.parameters["reference"] == transaction.psp_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_on_order(
- mocked_transaction_action_request, mocked_is_active, order, staff_user
+def test_request_cancelation_action_with_transaction_action_request(
+ mocked_transaction_request, mocked_is_active, order, staff_user
):
# given
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["capture", "void"],
currency="USD",
order_id=order.pk,
authorized_value=Decimal("10"),
)
- mocked_is_active.return_value = True
+ requested_event = transaction.events.create(
+ currency=transaction.currency, type=TransactionEventType.CANCEL_REQUEST
+ )
+ mocked_is_active.side_effect = [True, False]
# when
- request_void_action(
+ request_cancelation_action(
transaction=transaction,
manager=get_plugins_manager(),
+ cancel_value=None,
channel_slug=order.channel.slug,
user=staff_user,
app=None,
+ request_event=requested_event,
+ action=TransactionAction.CANCEL,
)
# then
assert mocked_is_active.called
- mocked_transaction_action_request.assert_called_once_with(
+ mocked_transaction_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
- action_type=TransactionAction.VOID,
+ action_type=TransactionAction.CANCEL,
action_value=None,
+ event=requested_event,
+ transaction_app_owner=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.type == OrderEvents.TRANSACTION_CANCEL_REQUESTED
+ assert event.parameters["reference"] == transaction.psp_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
+@patch("saleor.plugins.manager.PluginsManager.transaction_cancelation_requested")
+def test_request_cancelation_action_by_app(
+ mocked_transaction_request, mocked_is_active, order, app
):
# given
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["capture", "void"],
currency="USD",
order_id=order.pk,
authorized_value=Decimal("10"),
)
- mocked_is_active.return_value = True
+ requested_event = transaction.events.create(
+ currency=transaction.currency, type=TransactionEventType.CANCEL_REQUEST
+ )
+ mocked_is_active.side_effect = [False, True]
# when
- request_void_action(
+ request_cancelation_action(
transaction=transaction,
manager=get_plugins_manager(),
+ cancel_value=None,
channel_slug=order.channel.slug,
user=None,
app=app,
+ request_event=requested_event,
+ action=TransactionAction.CANCEL,
)
# then
assert mocked_is_active.called
- mocked_transaction_action_request.assert_called_once_with(
+ mocked_transaction_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
- action_type=TransactionAction.VOID,
+ action_type=TransactionAction.CANCEL,
action_value=None,
+ event=requested_event,
+ transaction_app_owner=None,
),
- channel_slug=order.channel.slug,
+ order.channel.slug,
)
event = order.events.first()
- assert event.type == OrderEvents.TRANSACTION_VOID_REQUESTED
- assert event.parameters["reference"] == transaction.reference
+ assert event.type == OrderEvents.TRANSACTION_CANCEL_REQUESTED
+ assert event.parameters["reference"] == transaction.psp_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
+@patch("saleor.plugins.manager.PluginsManager.transaction_cancelation_requested")
+def test_request_cancelation_action_on_checkout(
+ mocked_transaction_request, mocked_is_active, checkout, staff_user
):
# given
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["capture", "void"],
currency="USD",
checkout_id=checkout.pk,
authorized_value=Decimal("10"),
)
- mocked_is_active.return_value = True
+ requested_event = transaction.events.create(
+ currency=transaction.currency,
+ type=TransactionEventType.CANCEL_REQUEST,
+ )
+ mocked_is_active.side_effect = [False, True]
# when
- request_void_action(
+ request_cancelation_action(
transaction=transaction,
manager=get_plugins_manager(),
+ cancel_value=None,
channel_slug=checkout.channel.slug,
user=staff_user,
app=None,
+ request_event=requested_event,
+ action=TransactionAction.CANCEL,
)
# then
assert mocked_is_active.called
- mocked_transaction_action_request.assert_called_once_with(
+ mocked_transaction_request.assert_called_once_with(
TransactionActionData(
transaction=transaction,
- action_type=TransactionAction.VOID,
+ action_type=TransactionAction.CANCEL,
action_value=None,
+ event=requested_event,
+ transaction_app_owner=None,
),
- channel_slug=checkout.channel.slug,
+ checkout.channel.slug,
)
diff --git a/saleor/payment/tests/test_transaction_item_calculations.py b/saleor/payment/tests/test_transaction_item_calculations.py
new file mode 100644
index 0000000000..5155313ec4
--- /dev/null
+++ b/saleor/payment/tests/test_transaction_item_calculations.py
@@ -0,0 +1,1626 @@
+from datetime import timedelta
+from decimal import Decimal
+from typing import Callable, List
+
+import pytest
+from django.utils import timezone
+
+from .. import TransactionEventType
+from ..models import TransactionEvent, TransactionItem
+from ..transaction_item_calculations import recalculate_transaction_amounts
+
+
+def transaction_events_generator() -> (
+ Callable[
+ [List[str], List[str], List[Decimal], TransactionItem], List[TransactionEvent]
+ ]
+):
+ def factory(
+ psp_references: List[str],
+ types: List[str],
+ amounts: List[Decimal],
+ transaction: TransactionItem,
+ ):
+ return TransactionEvent.objects.bulk_create(
+ TransactionEvent(
+ transaction=transaction,
+ psp_reference=reference,
+ type=event_type,
+ amount_value=amount,
+ include_in_calculations=True,
+ currency=transaction.currency,
+ )
+ for reference, event_type, amount in zip(psp_references, types, amounts)
+ )
+
+ return factory
+
+
+def _assert_amounts(
+ transaction: TransactionItem,
+ authorized_value=Decimal("0"),
+ charged_value=Decimal("0"),
+ refunded_value=Decimal("0"),
+ canceled_value=Decimal("0"),
+ authorize_pending_value=Decimal("0"),
+ charge_pending_value=Decimal("0"),
+ refund_pending_value=Decimal("0"),
+ cancel_pending_value=Decimal("0"),
+):
+ assert sum(
+ [
+ transaction.authorized_value,
+ transaction.charged_value,
+ transaction.refunded_value,
+ transaction.canceled_value,
+ transaction.authorize_pending_value,
+ transaction.charge_pending_value,
+ transaction.refund_pending_value,
+ transaction.cancel_pending_value,
+ ]
+ ) == sum(
+ [
+ authorized_value,
+ charged_value,
+ refunded_value,
+ canceled_value,
+ authorize_pending_value,
+ charge_pending_value,
+ refund_pending_value,
+ cancel_pending_value,
+ ]
+ )
+ assert transaction.authorized_value == authorized_value
+ assert transaction.charged_value == charged_value
+ assert transaction.refunded_value == refunded_value
+ assert transaction.canceled_value == canceled_value
+ assert transaction.authorize_pending_value == authorize_pending_value
+ assert transaction.charge_pending_value == charge_pending_value
+ assert transaction.refund_pending_value == refund_pending_value
+ assert transaction.cancel_pending_value == cancel_pending_value
+
+
+def test_with_only_authorize_success_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorized_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ ],
+ amounts=[
+ authorized_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(transaction, authorized_value=authorized_value)
+
+
+def test_with_only_authorize_request_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorize_pending_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ ],
+ amounts=[
+ authorize_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(transaction, authorize_pending_value=authorize_pending_value)
+
+
+def test_with_only_authorize_failure_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorize_pending_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ ],
+ amounts=[
+ authorize_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, authorize_pending_value=Decimal("0"), authorized_value=Decimal("0")
+ )
+
+
+def test_with_authorize_request_and_success_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorize_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ ],
+ amounts=[authorize_value, authorize_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ authorize_pending_value=Decimal("0"),
+ authorized_value=authorize_value,
+ )
+
+
+def test_with_authorize_request_and_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorize_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ ],
+ amounts=[authorize_value, authorize_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, authorize_pending_value=Decimal("0"), authorized_value=Decimal("0")
+ )
+
+
+def test_with_authorize_success_and_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorize_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ ],
+ amounts=[authorize_value, authorize_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, authorize_pending_value=Decimal("0"), authorized_value=Decimal("0")
+ )
+
+
+def test_with_authorize_success_and_older_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorize_value = Decimal("11.00")
+ events = transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ ],
+ amounts=[authorize_value, authorize_value],
+ )
+ failure_event = events[1]
+ assert failure_event.type == TransactionEventType.AUTHORIZATION_FAILURE
+ failure_event.created_at = timezone.now() - timedelta(minutes=5)
+ failure_event.save()
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ authorize_pending_value=Decimal("0"),
+ authorized_value=authorize_value,
+ )
+
+
+def test_with_authorize_adjustment(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorize_value = Decimal("11.00")
+ authorize_adjustment_value = Decimal("100")
+ events = transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "2", "3", "4"],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_ADJUSTMENT,
+ TransactionEventType.AUTHORIZATION_ADJUSTMENT,
+ ],
+ amounts=[
+ authorize_value,
+ authorize_value,
+ authorize_adjustment_value,
+ authorize_value,
+ ],
+ )
+
+ # set the newest time for adjustment event
+ adjustment_event = events[2]
+ assert adjustment_event.type == TransactionEventType.AUTHORIZATION_ADJUSTMENT
+ adjustment_event.created_at = timezone.now() + timedelta(minutes=5)
+ adjustment_event.save()
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ authorize_pending_value=Decimal("0"),
+ authorized_value=authorize_adjustment_value,
+ )
+
+
+def test_with_authorize_request_and_success_events_different_psp_references(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ first_authorize_value = Decimal("11.00")
+ second_authorize_value = Decimal("12.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "2", "2"],
+ types=[
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ ],
+ amounts=[first_authorize_value, second_authorize_value, second_authorize_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ authorize_pending_value=first_authorize_value,
+ authorized_value=second_authorize_value,
+ )
+
+
+def test_with_only_charge_success_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ charged_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.CHARGE_SUCCESS,
+ ],
+ amounts=[
+ charged_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(transaction, charged_value=charged_value)
+
+
+def test_with_only_charge_request_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ charge_pending_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.CHARGE_REQUEST,
+ ],
+ amounts=[
+ charge_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(transaction, charge_pending_value=charge_pending_value)
+
+
+def test_with_only_charge_failure_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ charge_pending_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+ amounts=[
+ charge_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, charge_pending_value=Decimal("0"), charged_value=Decimal("0")
+ )
+
+
+def test_with_charge_request_and_success_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ charge_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.CHARGE_SUCCESS,
+ ],
+ amounts=[charge_value, charge_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ charge_pending_value=Decimal("0"),
+ charged_value=charge_value,
+ )
+
+
+def test_with_charge_request_and_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ charge_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+ amounts=[charge_value, charge_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, charge_pending_value=Decimal("0"), charged_value=Decimal("0")
+ )
+
+
+def test_with_charge_success_and_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ charge_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+ amounts=[charge_value, charge_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, charge_pending_value=Decimal("0"), charged_value=Decimal("0")
+ )
+
+
+def test_with_charge_success_and_older_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ charge_value = Decimal("11.00")
+ events = transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+ amounts=[charge_value, charge_value],
+ )
+ failure_event = events[1]
+ assert failure_event.type == TransactionEventType.CHARGE_FAILURE
+ failure_event.created_at = timezone.now() - timedelta(minutes=5)
+ failure_event.save()
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ charge_pending_value=Decimal("0"),
+ charged_value=charge_value,
+ )
+
+
+def test_with_charge_request_and_success_events_different_psp_references(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ first_charge_value = Decimal("11.00")
+ second_charge_value = Decimal("12.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "2", "2"],
+ types=[
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.CHARGE_SUCCESS,
+ ],
+ amounts=[first_charge_value, second_charge_value, second_charge_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ charge_pending_value=first_charge_value,
+ charged_value=second_charge_value,
+ )
+
+
+def test_with_charge_back(transaction_item_generator, transaction_events_generator):
+ # given
+ transaction = transaction_item_generator()
+ first_charge_value = Decimal("11.00")
+ second_charge_value = Decimal("12.00")
+ charge_back_value = Decimal("10.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "2", "3"],
+ types=[
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_BACK,
+ ],
+ amounts=[first_charge_value, second_charge_value, charge_back_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ charge_pending_value=Decimal("0"),
+ charged_value=first_charge_value + second_charge_value - charge_back_value,
+ )
+
+
+def test_with_only_refund_success_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ refunded_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+ amounts=[
+ refunded_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(transaction, refunded_value=refunded_value)
+
+
+def test_with_only_refund_request_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ refund_pending_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.REFUND_REQUEST,
+ ],
+ amounts=[
+ refund_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(transaction, refund_pending_value=refund_pending_value)
+
+
+def test_with_only_refund_failure_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ refund_pending_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.REFUND_FAILURE,
+ ],
+ amounts=[
+ refund_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, refund_pending_value=Decimal("0"), refunded_value=Decimal("0")
+ )
+
+
+def test_with_refund_request_and_success_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ refund_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+ amounts=[refund_value, refund_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ refund_pending_value=Decimal("0"),
+ refunded_value=refund_value,
+ )
+
+
+def test_with_refund_request_and_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ refund_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_FAILURE,
+ ],
+ amounts=[refund_value, refund_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, refund_pending_value=Decimal("0"), refunded_value=Decimal("0")
+ )
+
+
+def test_with_refund_success_and_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ refund_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_FAILURE,
+ ],
+ amounts=[refund_value, refund_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, refund_pending_value=Decimal("0"), refunded_value=Decimal("0")
+ )
+
+
+def test_with_refund_success_and_older_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ refund_value = Decimal("11.00")
+ events = transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_FAILURE,
+ ],
+ amounts=[refund_value, refund_value],
+ )
+ failure_event = events[1]
+ assert failure_event.type == TransactionEventType.REFUND_FAILURE
+ failure_event.created_at = timezone.now() - timedelta(minutes=5)
+ failure_event.save()
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ refund_pending_value=Decimal("0"),
+ refunded_value=refund_value,
+ )
+
+
+def test_with_refund_request_and_success_events_different_psp_references(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ first_refund_value = Decimal("11.00")
+ second_refund_value = Decimal("12.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "2", "2"],
+ types=[
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+ amounts=[first_refund_value, second_refund_value, second_refund_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ refund_pending_value=first_refund_value,
+ refunded_value=second_refund_value,
+ )
+
+
+def test_with_refund_reverse(transaction_item_generator, transaction_events_generator):
+ # given
+ transaction = transaction_item_generator()
+ first_refund_value = Decimal("11.00")
+ second_refund_value = Decimal("12.00")
+ reverse_refund = Decimal("10.00")
+ charged_value = Decimal("40")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "2", "3", "4"],
+ types=[
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_REVERSE,
+ TransactionEventType.CHARGE_SUCCESS,
+ ],
+ amounts=[
+ first_refund_value,
+ second_refund_value,
+ reverse_refund,
+ charged_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ refund_pending_value=Decimal("0"),
+ charged_value=charged_value
+ - first_refund_value
+ - second_refund_value
+ + reverse_refund,
+ refunded_value=first_refund_value + second_refund_value - reverse_refund,
+ )
+
+
+def test_with_only_cancel_success_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ canceled_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.CANCEL_SUCCESS,
+ ],
+ amounts=[
+ canceled_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(transaction, canceled_value=canceled_value)
+
+
+def test_with_only_cancel_request_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ cancel_pending_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.CANCEL_REQUEST,
+ ],
+ amounts=[
+ cancel_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(transaction, cancel_pending_value=cancel_pending_value)
+
+
+def test_with_only_cancel_failure_event(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ cancel_pending_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.CANCEL_FAILURE,
+ ],
+ amounts=[
+ cancel_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, cancel_pending_value=Decimal("0"), canceled_value=Decimal("0")
+ )
+
+
+def test_with_cancel_request_and_success_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ cancel_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.CANCEL_REQUEST,
+ TransactionEventType.CANCEL_SUCCESS,
+ ],
+ amounts=[cancel_value, cancel_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ cancel_pending_value=Decimal("0"),
+ canceled_value=cancel_value,
+ )
+
+
+def test_with_cancel_request_and_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ cancel_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.CANCEL_REQUEST,
+ TransactionEventType.CANCEL_FAILURE,
+ ],
+ amounts=[cancel_value, cancel_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, cancel_pending_value=Decimal("0"), canceled_value=Decimal("0")
+ )
+
+
+def test_with_cancel_success_and_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ cancel_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.CANCEL_FAILURE,
+ ],
+ amounts=[cancel_value, cancel_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, cancel_pending_value=Decimal("0"), canceled_value=Decimal("0")
+ )
+
+
+def test_with_cancel_success_and_older_failure_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ cancel_value = Decimal("11.00")
+ events = transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "1"],
+ types=[
+ TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.CANCEL_FAILURE,
+ ],
+ amounts=[cancel_value, cancel_value],
+ )
+ failure_event = events[1]
+ assert failure_event.type == TransactionEventType.CANCEL_FAILURE
+ failure_event.created_at = timezone.now() - timedelta(minutes=5)
+ failure_event.save()
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ cancel_pending_value=Decimal("0"),
+ canceled_value=cancel_value,
+ )
+
+
+def test_with_cancel_request_and_success_events_different_psp_references(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ first_cancel_value = Decimal("11.00")
+ second_cancel_value = Decimal("12.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "2", "2"],
+ types=[
+ TransactionEventType.CANCEL_REQUEST,
+ TransactionEventType.CANCEL_REQUEST,
+ TransactionEventType.CANCEL_SUCCESS,
+ ],
+ amounts=[first_cancel_value, second_cancel_value, second_cancel_value],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ cancel_pending_value=first_cancel_value,
+ canceled_value=second_cancel_value,
+ )
+
+
+def test_event_without_psp_reference(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ authorize_value = Decimal("110.00")
+ charge_value = Decimal("50.00")
+ first_refund_value = Decimal("30.0")
+ second_refund_value = Decimal("11.00")
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[None, None, "3", "3", None],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+ amounts=[
+ authorize_value,
+ charge_value,
+ first_refund_value, # value assigned to refund requst
+ first_refund_value,
+ second_refund_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction,
+ authorized_value=authorize_value,
+ charged_value=charge_value - first_refund_value,
+ refunded_value=first_refund_value + second_refund_value,
+ )
+
+
+def test_event_multiple_events(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+
+ authorize_value = Decimal("200.00")
+ authorize_adjustment_value = Decimal("250.00")
+
+ first_charge_value = Decimal("59.00")
+ first_charge_pending_value = Decimal("59.00")
+ second_charge_value = Decimal("11.00")
+ charge_back_value = Decimal("5.00")
+ charge_pending_value = Decimal("13.00")
+
+ first_refund_value = Decimal("7.00")
+ first_refund_pending_value = Decimal("7.00")
+
+ second_refund_pending_value = Decimal("22.00")
+
+ refund_reverse_value = Decimal("3.00")
+
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ None,
+ "authorization-adjustment",
+ "first-charge",
+ "first-charge",
+ "second-charge",
+ "charge-back",
+ "charge-pending",
+ "first-refund",
+ "first-refund",
+ "refund-pending",
+ "refund-reverse",
+ ],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_ADJUSTMENT,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_BACK,
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_REVERSE,
+ ],
+ amounts=[
+ authorize_value,
+ authorize_adjustment_value,
+ first_charge_value,
+ first_charge_pending_value,
+ second_charge_value,
+ charge_back_value,
+ charge_pending_value,
+ first_refund_value,
+ first_refund_pending_value,
+ second_refund_pending_value,
+ refund_reverse_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+
+ # second pending refund is only use as for the first one we already received
+ # success notification
+ total_refund_pending = second_refund_pending_value
+
+ # total refund includes all success refund, and removes any refund reverse
+ total_refunded = first_refund_value - refund_reverse_value
+
+ total_charge_pending = charge_pending_value
+
+ # total charged is a sum of charges minus the amounts that were moved to refund or
+ # pending refund
+ total_charged = (
+ first_charge_value + second_charge_value - total_refunded - total_refund_pending
+ )
+
+ # total authorized is the amount left and accessible for authorization. The amount
+ # that was charged, refunded or canceled is subtracted from total authorize
+ total_authorized = (
+ authorize_adjustment_value
+ - total_charged
+ - total_charge_pending
+ - total_refunded
+ - total_refund_pending
+ )
+
+ transaction.refresh_from_db()
+
+ _assert_amounts(
+ transaction,
+ authorized_value=total_authorized,
+ # charge back is reduced from charged value as we don't have this part of money
+ # anymore
+ charged_value=total_charged - charge_back_value,
+ refunded_value=total_refunded,
+ charge_pending_value=charge_pending_value,
+ refund_pending_value=total_refund_pending,
+ )
+
+
+def test_event_multiple_events_with_auth_charge_and_refund(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+
+ authorize_value = Decimal("250.00")
+
+ charged_value = Decimal("200")
+ charged_pending_value = Decimal("50")
+ refunded_value = Decimal("30")
+ ongoing_pending_refund_value = Decimal("15")
+
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "authorization",
+ "charge",
+ "charge-pending",
+ "refund",
+ "refund-pending",
+ ],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_REQUEST,
+ ],
+ amounts=[
+ authorize_value,
+ charged_value,
+ charged_pending_value,
+ refunded_value,
+ ongoing_pending_refund_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ total_refunded = refunded_value
+ total_pending_refund = ongoing_pending_refund_value
+ total_charged = charged_value - total_refunded - total_pending_refund
+ total_pending_charge = charged_pending_value
+
+ total_authorize = (
+ authorize_value
+ - total_charged
+ - total_pending_charge
+ - total_refunded
+ - total_pending_refund
+ )
+ transaction.refresh_from_db()
+
+ _assert_amounts(
+ transaction,
+ authorized_value=total_authorize,
+ charged_value=total_charged,
+ charge_pending_value=total_pending_charge,
+ refunded_value=total_refunded,
+ refund_pending_value=total_pending_refund,
+ )
+
+
+def test_event_multiple_events_with_auth_charge_and_refund_without_psp_references(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+
+ authorize_value = Decimal("250.00")
+
+ charged_value = Decimal("200")
+ charged_pending_value = Decimal("50")
+ refunded_value = Decimal("30")
+ ongoing_pending_refund_value = Decimal("15")
+
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ None,
+ None,
+ None,
+ "charge-request",
+ "refund-request",
+ ],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.REFUND_REQUEST,
+ ],
+ amounts=[
+ authorize_value,
+ charged_value,
+ refunded_value,
+ charged_pending_value,
+ ongoing_pending_refund_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ total_refunded = refunded_value
+ total_pending_refund = ongoing_pending_refund_value
+ total_charged = charged_value - total_pending_refund
+ total_pending_charge = charged_pending_value
+
+ total_authorize = authorize_value - charged_pending_value
+ transaction.refresh_from_db()
+
+ _assert_amounts(
+ transaction,
+ authorized_value=total_authorize,
+ charged_value=total_charged,
+ charge_pending_value=total_pending_charge,
+ refunded_value=total_refunded,
+ refund_pending_value=total_pending_refund,
+ )
+
+
+def test_event_multiple_events_with_auth_and_cancel(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+
+ authorize_value = Decimal("200.00")
+ authorize_adjustment_value = Decimal("250.00")
+
+ canceled_value = Decimal("11.00")
+ cancel_pending_value = Decimal("11")
+ ongoing_pending_value = Decimal("3")
+
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ None,
+ "authorization-adjustment",
+ "cancel-ref",
+ "cancel-ref",
+ "ongoing_pending_value",
+ ],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_ADJUSTMENT,
+ TransactionEventType.CANCEL_REQUEST,
+ TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.CANCEL_REQUEST,
+ ],
+ amounts=[
+ authorize_value,
+ authorize_adjustment_value,
+ cancel_pending_value,
+ canceled_value,
+ ongoing_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ total_canceled = canceled_value
+ total_pending_canceled = ongoing_pending_value
+
+ total_authorized = (
+ authorize_adjustment_value - total_canceled - total_pending_canceled
+ )
+
+ transaction.refresh_from_db()
+
+ _assert_amounts(
+ transaction,
+ authorized_value=total_authorized,
+ canceled_value=total_canceled,
+ cancel_pending_value=total_pending_canceled,
+ )
+
+
+def test_event_multiple_events_with_charge_and_refund(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+
+ charged_value = Decimal("250.00")
+
+ refunded_value = Decimal("11.00")
+ refund_pending_value = Decimal("15")
+ ongoing_refund_pending_value = Decimal("3")
+
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "charge",
+ "refund",
+ "refund",
+ "ongoing_refund_pending_value",
+ ],
+ types=[
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_REQUEST,
+ ],
+ amounts=[
+ charged_value,
+ refunded_value,
+ refund_pending_value,
+ ongoing_refund_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ total_refuned = refunded_value
+ total_pending_refund = ongoing_refund_pending_value
+
+ total_charged = charged_value - total_refuned - total_pending_refund
+
+ transaction.refresh_from_db()
+
+ _assert_amounts(
+ transaction,
+ charged_value=total_charged,
+ refunded_value=total_refuned,
+ refund_pending_value=total_pending_refund,
+ )
+
+
+def test_event_multiple_events_with_charge_and_failure_refund(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+
+ charged_value = Decimal("250.00")
+
+ refunded_value = Decimal("11.00")
+ refund_pending_value = Decimal("15")
+ ongoing_refund_pending_value = Decimal("3")
+
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "charge",
+ "refund",
+ "refund",
+ "ongoing_refund_pending_value",
+ ],
+ types=[
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.REFUND_REQUEST,
+ ],
+ amounts=[
+ charged_value,
+ refund_pending_value,
+ refunded_value,
+ ongoing_refund_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ total_refuned = Decimal(0)
+ total_pending_refund = ongoing_refund_pending_value
+
+ total_charged = charged_value - total_refuned - total_pending_refund
+
+ transaction.refresh_from_db()
+
+ _assert_amounts(
+ transaction,
+ charged_value=total_charged,
+ refunded_value=total_refuned,
+ refund_pending_value=total_pending_refund,
+ )
+
+
+def test_event_multiple_events_and_transaction_with_amounts(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ currently_authorized = Decimal("30")
+ currently_charged = Decimal("200")
+ transaction = transaction_item_generator(
+ authorized_value=currently_authorized,
+ charged_value=currently_charged,
+ )
+ charged_value = Decimal("20.00")
+
+ refunded_value = Decimal("11.00")
+ refund_pending_value = Decimal("15")
+ ongoing_refund_pending_value = Decimal("3")
+
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "charge",
+ "refund",
+ "refund",
+ "ongoing_refund_pending_value",
+ ],
+ types=[
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.REFUND_REQUEST,
+ ],
+ amounts=[
+ charged_value,
+ refund_pending_value,
+ refunded_value,
+ ongoing_refund_pending_value,
+ ],
+ )
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+
+ total_refuned = Decimal(0)
+ total_pending_refund = ongoing_refund_pending_value
+
+ total_charged = max(
+ (currently_charged + charged_value - total_refuned - total_pending_refund),
+ Decimal("0"),
+ )
+
+ transaction.refresh_from_db()
+
+ _assert_amounts(
+ transaction,
+ authorized_value=currently_authorized - charged_value,
+ charged_value=total_charged,
+ refunded_value=total_refuned,
+ refund_pending_value=total_pending_refund,
+ )
+
+
+def test_skips_event_that_should_not_be_taken_into_account(
+ transaction_item_generator, transaction_events_generator
+):
+ # given
+ transaction = transaction_item_generator()
+ first_value = Decimal("11.00")
+ second_value = Decimal("12.00")
+ transaction_events = transaction_events_generator(
+ transaction=transaction,
+ psp_references=["1", "2", "2"],
+ types=[
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ ],
+ amounts=[first_value, second_value, second_value],
+ )
+ transaction_event_to_skip = transaction_events[-1]
+ transaction_event_to_skip.include_in_calculations = False
+ transaction_event_to_skip.save()
+
+ # when
+ recalculate_transaction_amounts(transaction)
+
+ # then
+ transaction.refresh_from_db()
+ _assert_amounts(
+ transaction, authorized_value=first_value, authorize_pending_value=second_value
+ )
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 89f782b469..1a25605bac 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -1,12 +1,30 @@
+from datetime import datetime
from decimal import Decimal
from unittest.mock import patch
+import pytest
+from django.utils import timezone
+from freezegun import freeze_time
+
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ...order import OrderAuthorizeStatus, OrderChargeStatus
from ...plugins.manager import get_plugins_manager
-from ..interface import PaymentLineData, PaymentLinesData
+from .. import TransactionEventType
+from ..interface import (
+ PaymentLineData,
+ PaymentLinesData,
+ TransactionRequestEventResponse,
+ TransactionRequestResponse,
+)
+from ..models import TransactionEvent
from ..utils import (
+ create_failed_transaction_event,
+ create_manual_adjustment_events,
create_payment_lines_information,
+ create_transaction_event_from_request_and_webhook_response,
get_channel_slug_from_payment,
+ get_correct_event_types_based_on_request_type,
+ parse_transaction_action_data,
try_void_or_refund_inactive_payment,
)
@@ -215,3 +233,678 @@ def test_try_void_or_refund_inactive_payment_transaction_success(
)
assert get_channel_slug_from_payment_mock.called
assert refund_or_void_mock.called
+
+
+def test_parse_transaction_action_data_with_only_psp_reference():
+ # given
+ expected_psp_reference = "psp:122:222"
+ response_data = {"pspReference": expected_psp_reference}
+
+ # when
+ parsed_data, _ = parse_transaction_action_data(
+ response_data, TransactionEventType.AUTHORIZATION_REQUEST
+ )
+
+ # then
+ assert isinstance(parsed_data, TransactionRequestResponse)
+
+ assert parsed_data.psp_reference == expected_psp_reference
+ assert parsed_data.event is None
+
+
+def test_parse_transaction_action_data_with_event_all_fields_provided():
+ # given
+ expected_psp_reference = "psp:122:222"
+ event_amount = 12.00
+ event_type = TransactionEventType.CHARGE_SUCCESS
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ }
+
+ # when
+ parsed_data, error_msg = parse_transaction_action_data(
+ response_data, TransactionEventType.CHARGE_REQUEST
+ )
+ # then
+ assert isinstance(parsed_data, TransactionRequestResponse)
+ assert error_msg is None
+
+ assert parsed_data.psp_reference == expected_psp_reference
+ assert isinstance(parsed_data.event, TransactionRequestEventResponse)
+ assert parsed_data.event.psp_reference == expected_psp_reference
+ assert parsed_data.event.amount == event_amount
+ assert parsed_data.event.time == datetime.fromisoformat(event_time)
+ assert parsed_data.event.external_url == event_url
+ assert parsed_data.event.message == event_cause
+ assert parsed_data.event.type == event_type
+
+
+def test_parse_transaction_action_data_with_incorrect_result():
+ # given
+ expected_psp_reference = "psp:122:222"
+ event_amount = 12.00
+ event_type = TransactionEventType.CHARGE_SUCCESS
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ }
+
+ # when
+ parsed_data, error_msg = parse_transaction_action_data(
+ response_data, TransactionEventType.REFUND_REQUEST
+ )
+
+ # then
+ assert parsed_data is None
+ assert isinstance(error_msg, str)
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_parse_transaction_action_data_with_event_only_mandatory_fields():
+ # given
+ expected_psp_reference = "psp:122:222"
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ }
+
+ # when
+ parsed_data, _ = parse_transaction_action_data(
+ response_data, TransactionEventType.CHARGE_REQUEST
+ )
+
+ # then
+ assert isinstance(parsed_data, TransactionRequestResponse)
+
+ assert parsed_data.psp_reference == expected_psp_reference
+ assert isinstance(parsed_data.event, TransactionRequestEventResponse)
+ assert parsed_data.event.psp_reference == expected_psp_reference
+ assert parsed_data.event.type == TransactionEventType.CHARGE_SUCCESS
+ assert parsed_data.event.amount is None
+ assert parsed_data.event.time == timezone.now()
+ assert parsed_data.event.external_url == ""
+ assert parsed_data.event.message == ""
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_parse_transaction_action_data_with_missin_psp_reference():
+ # given
+ response_data = {}
+
+ # when
+ parsed_data, _ = parse_transaction_action_data(
+ response_data, TransactionEventType.AUTHORIZATION_REQUEST
+ )
+
+ # then
+ assert parsed_data is None
+
+
+def test_parse_transaction_action_data_with_missing_mandatory_event_fields():
+ # given
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {"pspReference": expected_psp_reference, "amount": Decimal("1")}
+
+ # when
+ parsed_data, _ = parse_transaction_action_data(
+ response_data, TransactionEventType.AUTHORIZATION_REQUEST
+ )
+
+ # then
+ assert parsed_data is None
+
+
+def test_create_failed_transaction_event(transaction_item_generator):
+ # given
+ transaction = transaction_item_generator()
+ cause = "Test failure"
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ # when
+ failed_event = create_failed_transaction_event(request_event, cause=cause)
+
+ # then
+ assert failed_event.type == TransactionEventType.CHARGE_FAILURE
+ assert failed_event.amount_value == request_event.amount_value
+ assert failed_event.currency == request_event.currency
+ assert failed_event.transaction_id == transaction.id
+
+
+def test_create_transaction_event_from_request_and_webhook_response_with_psp_reference(
+ transaction_item_generator,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+ expected_psp_reference = "psp:122:222"
+ response_data = {"pspReference": expected_psp_reference}
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ request_event.refresh_from_db()
+ assert request_event.psp_reference == expected_psp_reference
+ assert TransactionEvent.objects.count() == 1
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_and_webhook_response_part_event(
+ transaction_item_generator,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+ expected_psp_reference = "psp:122:222"
+ amount = request_event.amount_value
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ "amount": amount,
+ }
+
+ # when
+ event = create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ assert TransactionEvent.objects.count() == 2
+ request_event.refresh_from_db()
+ assert request_event.psp_reference == expected_psp_reference
+ assert event
+ assert event.psp_reference == expected_psp_reference
+ assert event.amount_value == amount
+ assert event.created_at == timezone.now()
+ assert event.external_url == ""
+ assert event.message == ""
+ assert event.type == TransactionEventType.CHARGE_SUCCESS
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_updates_order_charge(
+ transaction_item_generator, app, order_with_lines
+):
+ # given
+ order = order_with_lines
+ transaction = transaction_item_generator(order_id=order.pk)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = 12.00
+ event_type = TransactionEventType.CHARGE_SUCCESS
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ order.refresh_from_db()
+ assert order.total_charged_amount == Decimal(event_amount)
+ assert order.charge_status == OrderChargeStatus.PARTIAL
+ assert order.search_vector
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_updates_order_authorize(
+ transaction_item_generator, app, order_with_lines
+):
+ # given
+ order = order_with_lines
+ transaction = transaction_item_generator(order_id=order.pk)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.AUTHORIZATION_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = 12.00
+ event_type = TransactionEventType.AUTHORIZATION_SUCCESS
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ order.refresh_from_db()
+ assert order.total_authorized_amount == Decimal(event_amount)
+ assert order.authorize_status == OrderAuthorizeStatus.PARTIAL
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_and_webhook_response_full_event(
+ transaction_item_generator,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = 12.00
+ event_type = TransactionEventType.CHARGE_FAILURE
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ }
+
+ # when
+ event = create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ assert TransactionEvent.objects.count() == 2
+ request_event.refresh_from_db()
+ assert request_event.psp_reference == expected_psp_reference
+ assert event
+ assert event.psp_reference == expected_psp_reference
+ assert event.amount_value == event_amount
+ assert event.created_at == datetime.fromisoformat(event_time)
+ assert event.external_url == event_url
+ assert event.message == event_cause
+ assert event.type == event_type
+
+
+def test_create_transaction_event_from_request_and_webhook_response_incorrect_data(
+ transaction_item_generator,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+ response_data = {"wrong-data": "psp:122:222"}
+
+ # when
+ failed_event = create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ request_event.refresh_from_db()
+ assert TransactionEvent.objects.count() == 2
+
+ assert failed_event
+ assert failed_event.type == TransactionEventType.CHARGE_FAILURE
+ assert failed_event.amount_value == request_event.amount_value
+ assert failed_event.currency == request_event.currency
+ assert failed_event.transaction_id == transaction.id
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_and_webhook_response_twice_auth(
+ transaction_item_generator,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ transaction.events.create(
+ type=TransactionEventType.AUTHORIZATION_SUCCESS,
+ amount_value=Decimal(22.00),
+ currency="USD",
+ )
+
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.AUTHORIZATION_REQUEST,
+ amount_value=Decimal(11.00),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = 12.00
+ event_type = TransactionEventType.AUTHORIZATION_SUCCESS
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ }
+
+ # when
+ failed_event = create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ assert TransactionEvent.objects.count() == 3
+ request_event.refresh_from_db()
+ assert request_event.psp_reference == expected_psp_reference
+ assert failed_event
+ assert failed_event.psp_reference == expected_psp_reference
+ assert failed_event.type == TransactionEventType.AUTHORIZATION_FAILURE
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_and_webhook_response_same_event(
+ transaction_item_generator,
+ app,
+):
+ # given
+ expected_psp_reference = "psp:122:222"
+ event_amount = 12.00
+ event_type = TransactionEventType.AUTHORIZATION_SUCCESS
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+
+ transaction = transaction_item_generator()
+ existing_authorize_success = transaction.events.create(
+ type=event_type,
+ amount_value=event_amount,
+ currency="USD",
+ psp_reference=expected_psp_reference,
+ )
+
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.AUTHORIZATION_REQUEST,
+ amount_value=event_amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ }
+
+ # when
+ event = create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ assert TransactionEvent.objects.count() == 2
+ request_event.refresh_from_db()
+ assert request_event.psp_reference == expected_psp_reference
+ assert event
+ assert event.pk == existing_authorize_success.pk
+
+
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_and_webhook_response_differnt_amout(
+ transaction_item_generator,
+ app,
+):
+ # given
+ expected_psp_reference = "psp:122:222"
+ authorize_event_amount = Decimal(12.00)
+ event_type = TransactionEventType.AUTHORIZATION_SUCCESS
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+
+ transaction = transaction_item_generator()
+ transaction.events.create(
+ type=event_type,
+ amount_value=authorize_event_amount,
+ currency="USD",
+ psp_reference=expected_psp_reference,
+ )
+
+ second_authorize_event_amount = Decimal(33.00)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.AUTHORIZATION_REQUEST,
+ amount_value=second_authorize_event_amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": second_authorize_event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ }
+
+ # when
+ failed_event = create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ assert TransactionEvent.objects.count() == 3
+ request_event.refresh_from_db()
+ assert request_event.psp_reference == expected_psp_reference
+ assert failed_event
+ assert failed_event.psp_reference == expected_psp_reference
+ assert failed_event.type == TransactionEventType.AUTHORIZATION_FAILURE
+
+
+ "db_field_name, value, event_type",
+ [
+ ("authorized_value", Decimal("12"), TransactionEventType.AUTHORIZATION_SUCCESS),
+ ("charged_value", Decimal("13"), TransactionEventType.CHARGE_SUCCESS),
+ ("canceled_value", Decimal("14"), TransactionEventType.CANCEL_SUCCESS),
+ ("refunded_value", Decimal("15"), TransactionEventType.REFUND_SUCCESS),
+ ],
+)
+def test_create_manual_adjustment_events_creates_calculation_events(
+ db_field_name, value, event_type, transaction_item_generator, app
+):
+ # given
+ transaction = transaction_item_generator(app=app)
+ money_data = {db_field_name: value}
+
+ # when
+ create_manual_adjustment_events(
+ transaction=transaction, money_data=money_data, app=app, user=None
+ )
+
+ # then
+ event = transaction.events.filter(type=event_type).get()
+ assert event.amount_value == value
+ assert event.include_in_calculations is True
+
+
+def test_create_manual_adjustment_events_additional_authorization(
+ transaction_item_generator, app
+):
+ # given
+ authorized_value = Decimal("10")
+ transaction = transaction_item_generator(app=app, authorized_value=Decimal("2"))
+ money_data = {"authorized_value": authorized_value}
+
+ # when
+ create_manual_adjustment_events(
+ transaction=transaction, money_data=money_data, app=app, user=None
+ )
+
+ # then
+ event = transaction.events.filter(
+ type=TransactionEventType.AUTHORIZATION_ADJUSTMENT
+ ).get()
+ assert event.amount_value == authorized_value
+ assert event.include_in_calculations is True
+
+
+def test_create_manual_adjustment_events_additional_charge(
+ transaction_item_generator, app
+):
+ # given
+ charged_value = Decimal("10")
+ current_charge_value = Decimal("2")
+ transaction = transaction_item_generator(
+ app=app, charged_value=current_charge_value
+ )
+ money_data = {"charged_value": charged_value}
+
+ # when
+ create_manual_adjustment_events(
+ transaction=transaction, money_data=money_data, app=app, user=None
+ )
+
+ # then
+ event = transaction.events.filter(type=TransactionEventType.CHARGE_SUCCESS).last()
+ assert event.amount_value == charged_value - current_charge_value
+ assert event.include_in_calculations is True
+
+
+def test_create_manual_adjustment_events_additional_refund(
+ transaction_item_generator, app
+):
+ # given
+ refunded_value = Decimal("10")
+ current_refunded_value = Decimal("2")
+ transaction = transaction_item_generator(
+ app=app, refunded_value=current_refunded_value
+ )
+ money_data = {"refunded_value": refunded_value}
+
+ # when
+ create_manual_adjustment_events(
+ transaction=transaction, money_data=money_data, app=app, user=None
+ )
+
+ # then
+ event = transaction.events.filter(type=TransactionEventType.REFUND_SUCCESS).last()
+ assert event.amount_value == refunded_value - current_refunded_value
+ assert event.include_in_calculations is True
+
+
+def test_create_manual_adjustment_events_additional_cancel(
+ transaction_item_generator, app
+):
+ # given
+ canceled_value = Decimal("10")
+ current_canceled_value = Decimal("2")
+ transaction = transaction_item_generator(
+ app=app, canceled_value=current_canceled_value
+ )
+ money_data = {"canceled_value": canceled_value}
+
+ # when
+ create_manual_adjustment_events(
+ transaction=transaction, money_data=money_data, app=app, user=None
+ )
+
+ # then
+ event = transaction.events.filter(type=TransactionEventType.CANCEL_SUCCESS).last()
+ assert event.amount_value == canceled_value - current_canceled_value
+ assert event.include_in_calculations is True
+
+
+ "request_type, expected_events",
+ [
+ (
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ [
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.AUTHORIZATION_ADJUSTMENT,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ ],
+ ),
+ (
+ TransactionEventType.CHARGE_REQUEST,
+ [
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.CHARGE_SUCCESS,
+ ],
+ ),
+ (
+ TransactionEventType.REFUND_REQUEST,
+ [
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+ ),
+ (
+ TransactionEventType.CANCEL_REQUEST,
+ [
+ TransactionEventType.CANCEL_FAILURE,
+ TransactionEventType.CANCEL_SUCCESS,
+ ],
+ ),
+ ],
+)
+def test_get_correct_event_types_based_on_request_type(request_type, expected_events):
+ correct_types = get_correct_event_types_based_on_request_type(request_type)
+ assert set(correct_types) == set(expected_events)
diff --git a/saleor/payment/transaction_item_calculations.py b/saleor/payment/transaction_item_calculations.py
new file mode 100644
index 0000000000..f4658cf38f
--- /dev/null
+++ b/saleor/payment/transaction_item_calculations.py
@@ -0,0 +1,408 @@
+from collections import defaultdict
+from dataclasses import dataclass, field
+from decimal import Decimal
+from typing import Dict, Iterable, List, Optional, cast
+
+from . import TransactionEventType
+from .models import TransactionEvent, TransactionItem
+
+
+@dataclass
+class BaseEvent:
+ request: Optional[TransactionEvent] = None
+ success: Optional[TransactionEvent] = None
+ failure: Optional[TransactionEvent] = None
+
+
+@dataclass
+class AuthorizationEvents(BaseEvent):
+ adjustment: Optional[TransactionEvent] = None
+
+
+@dataclass
+class ChargeEvents(BaseEvent):
+ back: Optional[TransactionEvent] = None
+
+
+@dataclass
+class RefundEvents(BaseEvent):
+ reverse: Optional[TransactionEvent] = None
+
+
+@dataclass
+class CancelEvents(BaseEvent):
+ ...
+
+
+PSPReference = str
+
+AUTHORIZATION_EVENTS = [
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.AUTHORIZATION_ADJUSTMENT,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+]
+
+
+@dataclass
+class ActionEventMap:
+ without_psp_reference: List[TransactionEvent]
+ authorization: Dict[PSPReference, AuthorizationEvents] = field(
+ default_factory=lambda: defaultdict(AuthorizationEvents)
+ )
+ charge: Dict[PSPReference, ChargeEvents] = field(
+ default_factory=lambda: defaultdict(ChargeEvents)
+ )
+ refund: Dict[PSPReference, RefundEvents] = field(
+ default_factory=lambda: defaultdict(RefundEvents)
+ )
+ cancel: Dict[PSPReference, CancelEvents] = field(
+ default_factory=lambda: defaultdict(CancelEvents)
+ )
+
+
+def _should_increase_pending_amount(
+ request: Optional[TransactionEvent],
+ success: Optional[TransactionEvent],
+ failure: Optional[TransactionEvent],
+) -> bool:
+ if request:
+ # the pending amount should be increased only when we don't
+ # have any failure/success event with the psp reference
+ if not failure and not success:
+ return True
+ return False
+
+
+def _should_increse_amount(
+ success: Optional[TransactionEvent], failure: Optional[TransactionEvent]
+) -> bool:
+ if success and failure:
+ # in case of having success and failure events for the same psp reference
+ # we take into account the success transaction only when we don't have
+ # newer failure event
+ if success.created_at > failure.created_at:
+ return True
+ elif success:
+ return True
+ return False
+
+
+def _recalculate_base_amounts(
+ transaction: TransactionItem,
+ request: Optional[TransactionEvent],
+ success: Optional[TransactionEvent],
+ failure: Optional[TransactionEvent],
+ pending_amount_field_name: str,
+ amount_field_name: str,
+ previous_amount_field_name: Optional[str],
+):
+ if _should_increase_pending_amount(request, success, failure):
+ request = cast(TransactionEvent, request)
+ pending_value = getattr(transaction, pending_amount_field_name)
+ setattr(
+ transaction, pending_amount_field_name, pending_value + request.amount_value
+ )
+ if previous_amount_field_name:
+ current_previous_amount = getattr(transaction, previous_amount_field_name)
+ setattr(
+ transaction,
+ previous_amount_field_name,
+ current_previous_amount - request.amount_value,
+ )
+
+ if _should_increse_amount(success, failure):
+ success = cast(TransactionEvent, success)
+ current_value = getattr(transaction, amount_field_name)
+ setattr(transaction, amount_field_name, current_value + success.amount_value)
+ if previous_amount_field_name:
+ current_previous_amount = getattr(transaction, previous_amount_field_name)
+ setattr(
+ transaction,
+ previous_amount_field_name,
+ current_previous_amount - success.amount_value,
+ )
+
+
+def _recalculate_authorization_amounts(
+ transaction: TransactionItem, authorization_events: AuthorizationEvents
+):
+ success = authorization_events.success
+ failure = authorization_events.failure
+ request = authorization_events.request
+ adjustment = authorization_events.adjustment
+
+ if adjustment:
+ # adjustment event overwrites the total amount of authorized
+ # value.
+ transaction.authorized_value = adjustment.amount_value
+
+ _recalculate_base_amounts(
+ transaction,
+ request,
+ success,
+ failure,
+ pending_amount_field_name="authorize_pending_value",
+ amount_field_name="authorized_value",
+ previous_amount_field_name=None,
+ )
+
+
+def _recalculate_charge_amounts(
+ transaction: TransactionItem, charge_events: ChargeEvents
+):
+ success = charge_events.success
+ failure = charge_events.failure
+ request = charge_events.request
+ back = charge_events.back
+
+ if back:
+ transaction.charged_value -= back.amount_value
+
+ _recalculate_base_amounts(
+ transaction,
+ request,
+ success,
+ failure,
+ pending_amount_field_name="charge_pending_value",
+ amount_field_name="charged_value",
+ previous_amount_field_name="authorized_value",
+ )
+
+
+def _recalculate_refund_amounts(
+ transaction: TransactionItem, refund_events: RefundEvents
+):
+ success = refund_events.success
+ failure = refund_events.failure
+ request = refund_events.request
+ reverse = refund_events.reverse
+
+ if reverse:
+ transaction.charged_value += reverse.amount_value
+ transaction.refunded_value -= reverse.amount_value
+
+ _recalculate_base_amounts(
+ transaction,
+ request,
+ success,
+ failure,
+ pending_amount_field_name="refund_pending_value",
+ amount_field_name="refunded_value",
+ previous_amount_field_name="charged_value",
+ )
+
+
+def _recalculate_cancel_amounts(
+ transaction: TransactionItem, cancel_events: CancelEvents
+):
+ success = cancel_events.success
+ failure = cancel_events.failure
+ request = cancel_events.request
+
+ _recalculate_base_amounts(
+ transaction,
+ request,
+ success,
+ failure,
+ pending_amount_field_name="cancel_pending_value",
+ amount_field_name="canceled_value",
+ previous_amount_field_name="authorized_value",
+ )
+
+
+def _get_authorize_events(events: Iterable[TransactionEvent]) -> List[TransactionEvent]:
+ authorize_events: List[TransactionEvent] = [
+ event for event in events if event.type in AUTHORIZATION_EVENTS
+ ]
+ auth_adjustment_event: Optional[TransactionEvent] = next(
+ (
+ event
+ for event in reversed(authorize_events)
+ if event.type == TransactionEventType.AUTHORIZATION_ADJUSTMENT
+ ),
+ None,
+ )
+ # in case of having authorization_adjustment, the transaction's authorized
+ # amount is overwriten by provided amount. In that case we need to skip the older
+ # event than the newest authorization_adjustment.
+ if auth_adjustment_event:
+ adujstment_event_index = authorize_events.index(auth_adjustment_event)
+ authorize_events = authorize_events[adujstment_event_index:]
+ return authorize_events
+
+
+def _handle_events_without_psp_reference(
+ transaction: TransactionItem, events: List[TransactionEvent]
+):
+ """Calculate the amounts for event without psp reference.
+
+ The events without a psp reference are the one that are reported by
+ transactionCreate or transactionUpdate. For transactionUpdate, we require a
+ manually reducing the amount by app, so there is no need to reduce the amount
+ from previous state as it is required for transaction events with psp reference
+ created by transactionEventReport.
+ """
+
+ for event in events:
+ if event.type == TransactionEventType.AUTHORIZATION_SUCCESS:
+ transaction.authorized_value += event.amount_value
+ elif event.type == TransactionEventType.AUTHORIZATION_ADJUSTMENT:
+ transaction.authorized_value = event.amount_value
+ elif event.type == TransactionEventType.CHARGE_SUCCESS:
+ transaction.charged_value += event.amount_value
+ elif event.type == TransactionEventType.CHARGE_BACK:
+ transaction.charged_value -= event.amount_value
+
+ elif event.type == TransactionEventType.REFUND_SUCCESS:
+ transaction.refunded_value += event.amount_value
+ elif event.type == TransactionEventType.REFUND_REVERSE:
+ transaction.charged_value += event.amount_value
+ elif event.type == TransactionEventType.CANCEL_SUCCESS:
+ transaction.canceled_value += event.amount_value
+
+
+def _initilize_action_map(events: Iterable[TransactionEvent]) -> ActionEventMap:
+ event_map = ActionEventMap(without_psp_reference=[])
+ authorize_events = _get_authorize_events(events)
+ events_without_authorize: List[TransactionEvent] = [
+ event for event in events if event.type not in AUTHORIZATION_EVENTS
+ ]
+
+ for event in authorize_events:
+ psp_reference = event.psp_reference
+ if not psp_reference:
+ event_map.without_psp_reference.append(event)
+ elif event.type == TransactionEventType.AUTHORIZATION_REQUEST:
+ event_map.authorization[psp_reference].request = event
+ elif event.type == TransactionEventType.AUTHORIZATION_SUCCESS:
+ event_map.authorization[psp_reference].success = event
+ elif event.type == TransactionEventType.AUTHORIZATION_FAILURE:
+ event_map.authorization[psp_reference].failure = event
+ elif event.type == TransactionEventType.AUTHORIZATION_ADJUSTMENT:
+ event_map.authorization[psp_reference].adjustment = event
+
+ for event in events_without_authorize:
+ psp_reference = event.psp_reference
+ if not psp_reference:
+ event_map.without_psp_reference.append(event)
+ elif event.type == TransactionEventType.CHARGE_REQUEST:
+ event_map.charge[psp_reference].request = event
+ elif event.type == TransactionEventType.CHARGE_SUCCESS:
+ event_map.charge[psp_reference].success = event
+ elif event.type == TransactionEventType.CHARGE_FAILURE:
+ event_map.charge[psp_reference].failure = event
+ elif event.type == TransactionEventType.CHARGE_BACK:
+ event_map.charge[psp_reference].back = event
+
+ elif event.type == TransactionEventType.REFUND_REQUEST:
+ event_map.refund[psp_reference].request = event
+ elif event.type == TransactionEventType.REFUND_FAILURE:
+ event_map.refund[psp_reference].failure = event
+ elif event.type == TransactionEventType.REFUND_SUCCESS:
+ event_map.refund[psp_reference].success = event
+ elif event.type == TransactionEventType.REFUND_REVERSE:
+ event_map.refund[psp_reference].reverse = event
+
+ elif event.type == TransactionEventType.CANCEL_REQUEST:
+ event_map.cancel[psp_reference].request = event
+ elif event.type == TransactionEventType.CANCEL_SUCCESS:
+ event_map.cancel[psp_reference].success = event
+ elif event.type == TransactionEventType.CANCEL_FAILURE:
+ event_map.cancel[psp_reference].failure = event
+
+ return event_map
+
+
+def _set_transaction_amounts_to_zero(transaction: TransactionItem):
+ transaction.authorized_value = Decimal("0")
+ transaction.charged_value = Decimal("0")
+ transaction.refunded_value = Decimal("0")
+ transaction.canceled_value = Decimal("0")
+
+ transaction.authorize_pending_value = Decimal("0")
+ transaction.charge_pending_value = Decimal("0")
+ transaction.refund_pending_value = Decimal("0")
+ transaction.cancel_pending_value = Decimal("0")
+
+
+def calculate_transaction_amount_based_on_events(transaction: TransactionItem):
+ events: Iterable[TransactionEvent] = transaction.events.order_by(
+ "created_at"
+ ).exclude(include_in_calculations=False)
+
+ action_map = _initilize_action_map(events)
+ _set_transaction_amounts_to_zero(transaction)
+
+ _handle_events_without_psp_reference(transaction, action_map.without_psp_reference)
+
+ for authorize_events in action_map.authorization.values():
+ _recalculate_authorization_amounts(transaction, authorize_events)
+
+ for charge_events in action_map.charge.values():
+ _recalculate_charge_amounts(transaction, charge_events)
+
+ for refund_events in action_map.refund.values():
+ _recalculate_refund_amounts(transaction, refund_events)
+
+ for cancel_events in action_map.cancel.values():
+ _recalculate_cancel_amounts(transaction, cancel_events)
+
+
+def recalculate_transaction_amounts(transaction: TransactionItem):
+ """Recalculate transaction amounts.
+
+ The function calculates the transaction amounts based on the amounts that
+ are stored in transaction's events. It groups the events based on the
+ psp reference and the type of the action (like authorization, or charge).
+ The grouping is mandatory to properly match the set of events based on the
+ same type and psp reference and correctly increase the amounts.
+
+ In case of having the event of type authorize_adjustment, any authorize
+ events older than the `authorize_adjustment` will be skipped. The
+ `authorize_adjustment` overwrites the amount of authorization.
+
+ The pending amount is increased only when the `request` event exists for
+ a given psp reference. In case of having a success or failure event for
+ the same psp reference as the request event, it assumes that the requested
+ amount has been already processed. The pending amount will not be increased.
+
+ The transaction amount is increased when the success event exists. In case
+ of having a failure event for the same psp reference, the creation time will
+ be used to determine which event is newer. If the failure event is newer, the
+ success event will be ignored.
+
+ There is a possibility of having events that don't have psp reference (for
+ example the events created by Saleor to keep correct amounts). In that case
+ the event amounts will be included in the transaction amounts.
+ """
+ calculate_transaction_amount_based_on_events(transaction)
+
+ transaction.authorized_value = max(transaction.authorized_value, Decimal("0"))
+ transaction.charged_value = max(transaction.charged_value, Decimal("0"))
+ transaction.refunded_value = max(transaction.refunded_value, Decimal("0"))
+ transaction.canceled_value = max(transaction.canceled_value, Decimal("0"))
+ transaction.authorize_pending_value = max(
+ transaction.authorize_pending_value, Decimal("0")
+ )
+ transaction.charge_pending_value = max(
+ transaction.charge_pending_value, Decimal("0")
+ )
+ transaction.refund_pending_value = max(
+ transaction.refund_pending_value, Decimal("0")
+ )
+ transaction.cancel_pending_value = max(
+ transaction.cancel_pending_value, Decimal("0")
+ )
+ transaction.save(
+ update_fields=[
+ "authorized_value",
+ "charged_value",
+ "refunded_value",
+ "canceled_value",
+ "authorize_pending_value",
+ "charge_pending_value",
+ "refund_pending_value",
+ "cancel_pending_value",
+ ]
+ )
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 65411b01b3..c1e8189079 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,27 +1,35 @@
+import decimal
import json
import logging
+from datetime import datetime
from decimal import Decimal
-from typing import Dict, List, Optional, cast, overload
+from typing import Any, Dict, Optional, cast, overload
import graphene
from babel.numbers import get_currency_precision
from django.core.serializers.json import DjangoJSONEncoder
+from django.db import transaction
from django.db.models import Q
+from django.utils import timezone
from ..account.models import User
+from ..app.models import App
from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ..checkout.models import Checkout
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
from ..discount.utils import fetch_active_discounts
+from ..graphql.core.utils import str_to_enum
from ..order.models import Order
-from ..order.utils import update_order_authorize_data, update_order_charge_data
+from ..order.search import update_order_search_vector
+from ..order.utils import update_order_authorize_data, updates_amounts_for_order
from ..plugins.manager import PluginsManager, get_plugins_manager
from . import (
ChargeStatus,
GatewayError,
PaymentError,
StorePaymentMethod,
+ TransactionEventType,
TransactionKind,
)
from .error_codes import PaymentErrorCode
@@ -35,8 +43,11 @@ from .interface import (
RefundData,
StorePaymentMethodEnum,
TransactionData,
+ TransactionRequestEventResponse,
+ TransactionRequestResponse,
)
-from .models import Payment, Transaction
+from .models import Payment, Transaction, TransactionEvent, TransactionItem
+from .transaction_item_calculations import recalculate_transaction_amounts
logger = logging.getLogger(__name__)
@@ -139,7 +150,7 @@ def create_order_payment_lines_information(order: Order) -> PaymentLinesData:
)
-def generate_transactions_data(payment: Payment) -> List[TransactionData]:
+def generate_transactions_data(payment: Payment) -> list[TransactionData]:
return [
TransactionData(
token=t.token,
@@ -452,7 +463,7 @@ def validate_gateway_response(response: GatewayResponse):
@traced_atomic_transaction()
def gateway_postprocess(transaction, payment: Payment):
- changed_fields: List[str] = []
+ changed_fields: list[str] = []
if not transaction.is_success or transaction.already_processed:
if changed_fields:
@@ -528,7 +539,7 @@ def update_payment_charge_status(payment, transaction, changed_fields=None):
transaction.already_processed = True
transaction.save(update_fields=["already_processed"])
if "captured_amount" in changed_fields and payment.order_id:
- update_order_charge_data(payment.order)
+ updates_amounts_for_order(payment.order)
if transaction_kind == TransactionKind.AUTH and payment.order_id:
update_order_authorize_data(payment.order)
@@ -568,7 +579,7 @@ def update_payment(payment: "Payment", gateway_response: "GatewayResponse"):
def update_payment_method_details(
payment: "Payment",
payment_method_info: Optional["PaymentMethodInfo"],
- changed_fields: List[str],
+ changed_fields: list[str],
):
if not payment_method_info:
return
@@ -677,3 +688,462 @@ def payment_owned_by_user(payment_pk: int, user) -> bool:
).first()
is not None
)
+
+
+def get_correct_event_types_based_on_request_type(request_type: str) -> list[str]:
+ type_map = {
+ TransactionEventType.AUTHORIZATION_REQUEST: [
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.AUTHORIZATION_ADJUSTMENT,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ ],
+ TransactionEventType.CHARGE_REQUEST: [
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.CHARGE_SUCCESS,
+ ],
+ TransactionEventType.REFUND_REQUEST: [
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+ TransactionEventType.CANCEL_REQUEST: [
+ TransactionEventType.CANCEL_FAILURE,
+ TransactionEventType.CANCEL_SUCCESS,
+ ],
+ }
+ return type_map.get(request_type, [])
+
+
+def parse_transaction_event_data(
+ event_data: dict,
+ parsed_event_data: dict,
+ error_field_msg: list[str],
+ psp_reference: str,
+ request_type: str,
+):
+ if event_data.get("amount") is None and not event_data.get("result"):
+ return
+ missing_msg = (
+ "Missing value for field: %s in " "response of transaction action webhook."
+ )
+ invalid_msg = (
+ "Incorrect value for field: %s, value: %s in "
+ "response of transaction action webhook."
+ )
+
+ parsed_event_data["psp_reference"] = psp_reference
+
+ possible_event_types = {
+ str_to_enum(event_result): event_result
+ for event_result in get_correct_event_types_based_on_request_type(request_type)
+ }
+
+ result = event_data.get("result")
+ if result:
+ if result in possible_event_types:
+ parsed_event_data["type"] = possible_event_types[result]
+ else:
+ possible_types = ",".join(possible_event_types.keys())
+ msg = (
+ "Incorrect value: %s for field: `result` in the response. Request: %s "
+ "can accept only types: %s"
+ )
+ logger.warning(msg, result, request_type.upper(), possible_types)
+ error_field_msg.append(msg % (result, request_type.upper(), possible_types))
+ else:
+ logger.warning(missing_msg, "result")
+ error_field_msg.append(missing_msg % "result")
+
+ if amount_data := event_data.get("amount"):
+ try:
+ parsed_event_data["amount"] = decimal.Decimal(amount_data)
+ except decimal.DecimalException:
+ logger.warning(invalid_msg, "amount", amount_data)
+ error_field_msg.append(invalid_msg % ("amount", amount_data))
+ else:
+ parsed_event_data["amount"] = None
+
+ if event_time_data := event_data.get("time"):
+ try:
+ parsed_event_data["time"] = (
+ datetime.fromisoformat(event_time_data) if event_time_data else None
+ )
+ except ValueError:
+ logger.warning(invalid_msg, "time", event_time_data)
+ error_field_msg.append(invalid_msg % ("time", event_time_data))
+ else:
+ parsed_event_data["time"] = timezone.now()
+
+ parsed_event_data["external_url"] = event_data.get("externalUrl", "")
+ parsed_event_data["message"] = event_data.get("message", "")
+
+
+error_msg = str
+
+
+def parse_transaction_action_data(
+ response_data: Any, request_type: str
+) -> tuple[Optional["TransactionRequestResponse"], Optional[error_msg]]:
+ """Parse response from transaction action webhook.
+
+ It takes the recieved response from sync webhook and
+ returns TransactionRequestResponse with all details.
+ If unable to parse, None will be returned.
+ """
+ psp_reference: str = response_data.get("pspReference")
+ if not psp_reference:
+ msg: str = "Missing `pspReference` field in the response."
+ logger.error(msg)
+ return None, msg
+
+ parsed_event_data: dict = {}
+ error_field_msg: list[str] = []
+ parse_transaction_event_data(
+ event_data=response_data,
+ parsed_event_data=parsed_event_data,
+ error_field_msg=error_field_msg,
+ psp_reference=psp_reference,
+ request_type=request_type,
+ )
+
+ if error_field_msg:
+ # error field msg can contain details of the value returned by payment app
+ # which means that we need to confirm that we don't exceed the field limit.
+ msg = "\n".join(error_field_msg)
+ if len(msg) >= 512:
+ msg = msg[:509] + "..."
+ return None, msg
+
+ return (
+ TransactionRequestResponse(
+ psp_reference=psp_reference,
+ event=TransactionRequestEventResponse(**parsed_event_data)
+ if parsed_event_data
+ else None,
+ ),
+ None,
+ )
+
+
+def get_failed_transaction_event_type_for_request_event(
+ request_event: TransactionEvent,
+):
+ if request_event.type == TransactionEventType.AUTHORIZATION_REQUEST:
+ return TransactionEventType.AUTHORIZATION_FAILURE
+ elif request_event.type == TransactionEventType.CHARGE_REQUEST:
+ return TransactionEventType.CHARGE_FAILURE
+ elif request_event.type == TransactionEventType.REFUND_REQUEST:
+ return TransactionEventType.REFUND_FAILURE
+ elif request_event.type == TransactionEventType.CANCEL_REQUEST:
+ return TransactionEventType.CANCEL_FAILURE
+ return None
+
+
+def get_failed_type_based_on_event(event: TransactionEvent):
+ event_type = get_failed_transaction_event_type_for_request_event(event)
+ if event_type:
+ return event_type
+ if event.type in [
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_ADJUSTMENT,
+ ]:
+ return TransactionEventType.AUTHORIZATION_FAILURE
+ elif event.type in [
+ TransactionEventType.CHARGE_BACK,
+ TransactionEventType.CHARGE_SUCCESS,
+ ]:
+ return TransactionEventType.CHARGE_FAILURE
+ elif event.type in [
+ TransactionEventType.REFUND_REVERSE,
+ TransactionEventType.REFUND_SUCCESS,
+ ]:
+ return TransactionEventType.REFUND_FAILURE
+ elif event.type == TransactionEventType.CANCEL_SUCCESS:
+ return TransactionEventType.CANCEL_FAILURE
+ return event.type
+
+
+def create_failed_transaction_event(
+ event: TransactionEvent,
+ cause: str,
+):
+ return TransactionEvent.objects.create(
+ type=get_failed_type_based_on_event(event),
+ amount_value=event.amount_value,
+ currency=event.currency,
+ transaction_id=event.transaction_id,
+ message=cause,
+ include_in_calculations=False,
+ psp_reference=event.psp_reference,
+ )
+
+
+def authorization_success_already_exists(transaction_id: int) -> bool:
+ return TransactionEvent.objects.filter(
+ transaction_id=transaction_id,
+ type=TransactionEventType.AUTHORIZATION_SUCCESS,
+ ).exists()
+
+
+def get_already_existing_event(event: TransactionEvent) -> Optional[TransactionEvent]:
+ existing_event = (
+ TransactionEvent.objects.filter(
+ transaction_id=event.transaction_id,
+ psp_reference=event.psp_reference,
+ type=event.type,
+ )
+ .select_for_update(of=("self",))
+ .first()
+ )
+ if existing_event:
+ return existing_event
+ return None
+
+
+def deduplicate_event(
+ event: TransactionEvent, app: App
+) -> tuple[TransactionEvent, Optional[error_msg]]:
+ """Deduplicate the TransactionEvent.
+
+ In case of having an existing event with the same type, psp reference
+ and amount, the event will be treated as a duplicate.
+ In case of a mismatch between the amounts, the failure TransactionEvent
+ will be created.
+ In case of already having `AUTHORIZATION_SUCCESS` event and trying to
+ create a new one, the failure TransactionEvent will be created.
+ """
+ error_message = None
+
+ already_existing_event = get_already_existing_event(event)
+ if already_existing_event:
+ if already_existing_event.amount != event.amount:
+ error_message = (
+ "The transaction with provided `pspReference` and "
+ "`type` already exists with different amount."
+ )
+ event = already_existing_event
+
+ elif event.type == TransactionEventType.AUTHORIZATION_SUCCESS:
+ already_existing_authorization = authorization_success_already_exists(
+ event.transaction_id
+ )
+ if already_existing_authorization:
+ error_message = (
+ "Event with `AUTHORIZATION_SUCCESS` already "
+ "reported for the transaction. Use "
+ "`AUTHORIZATION_ADJUSTMENT` to change the "
+ "authorization amount."
+ )
+ if error_message:
+ logger.error(
+ msg=error_message,
+ extra={
+ "transaction_id": event.transaction_id,
+ "psp_reference": event.psp_reference,
+ "app_identifier": app.identifier,
+ "app_id": app.pk,
+ },
+ )
+ return event, error_message
+
+
+def create_transaction_event_from_request_and_webhook_response(
+ request_event: TransactionEvent,
+ app: App,
+ transaction_webhook_response: Optional[Dict[str, Any]] = None,
+):
+ if transaction_webhook_response is None:
+ return create_failed_transaction_event(
+ request_event, cause="Failed to delivery request."
+ )
+ request_event_type = request_event.type
+ transaction_request_response, error_msg = parse_transaction_action_data(
+ transaction_webhook_response, request_event_type
+ )
+ if not transaction_request_response:
+ return create_failed_transaction_event(request_event, cause=error_msg or "")
+
+ psp_reference = transaction_request_response.psp_reference
+ request_event.psp_reference = psp_reference
+ request_event.save()
+ event = None
+ if response_event := transaction_request_response.event:
+ app_identifier = None
+ if app and app.identifier:
+ app_identifier = app.identifier
+
+ event = TransactionEvent(
+ psp_reference=response_event.psp_reference,
+ created_at=response_event.time or timezone.now(),
+ type=response_event.type, # type:ignore
+ amount_value=response_event.amount or request_event.amount_value,
+ external_url=response_event.external_url,
+ currency=request_event.currency,
+ transaction_id=request_event.transaction_id,
+ message=response_event.message,
+ app_identifier=app_identifier,
+ app=app,
+ include_in_calculations=True,
+ )
+ with transaction.atomic():
+ event, error_msg = deduplicate_event(event, app)
+ if error_msg:
+ return create_failed_transaction_event(request_event, cause=error_msg)
+ if not event.pk:
+ event.save()
+ transaction_item = request_event.transaction
+ recalculate_transaction_amounts(transaction_item)
+ if transaction_item.order_id:
+ order = cast(Order, transaction_item.order)
+ update_order_search_vector(order, save=False)
+ updates_amounts_for_order(order, save=False)
+ order.save(
+ update_fields=[
+ "total_charged_amount",
+ "charge_status",
+ "updated_at",
+ "total_authorized_amount",
+ "authorize_status",
+ "search_vector",
+ ]
+ )
+ return event
+
+
+def _prepare_manual_event(
+ transaction: TransactionItem,
+ transaction_amount: Decimal,
+ input_amount: Decimal,
+ event_type: str,
+ user: Optional["User"],
+ app: Optional["App"],
+) -> TransactionEvent:
+ amount_to_update = input_amount - transaction_amount
+ return TransactionEvent(
+ type=event_type,
+ amount_value=amount_to_update,
+ currency=transaction.currency,
+ transaction_id=transaction.pk,
+ include_in_calculations=True,
+ app_identifier=app.identifier if app else None,
+ app=app,
+ user=user,
+ created_at=timezone.now(),
+ message="Manual adjustment of the transaction.",
+ )
+
+
+def prepare_manual_event(
+ events_to_create: list[TransactionEvent],
+ amount_field: str,
+ money_data: Dict[str, Decimal],
+ event_type: str,
+ transaction: TransactionItem,
+ user: Optional["User"],
+ app: Optional["App"],
+):
+ amount_value = money_data.get(amount_field)
+ if amount_value is None:
+ return
+ transaction_amount = getattr(transaction, amount_field)
+ if transaction_amount != amount_value:
+ events_to_create.append(
+ _prepare_manual_event(
+ transaction,
+ transaction_amount,
+ amount_value,
+ event_type,
+ user,
+ app,
+ )
+ )
+
+
+def create_manual_adjustment_events(
+ transaction: TransactionItem,
+ money_data: Dict[str, Decimal],
+ user: Optional["User"],
+ app: Optional["App"],
+) -> list[TransactionEvent]:
+ """Create TransactionEvent used to recalculate the transaction amounts.
+
+ The transaction amounts are calculated based on the amounts stored in
+ the TransactionEvents assigned to the given transaction. To properly
+ match the amounts, the manual events are created in case of calling
+ transactionCreate or transactionUpdate
+ """
+ events_to_create: list[TransactionEvent] = []
+ if "authorized_value" in money_data:
+ authorized_value = money_data["authorized_value"]
+ event_type = TransactionEventType.AUTHORIZATION_SUCCESS
+ current_authorized_value = transaction.authorized_value
+ if transaction.events.filter(type=event_type).exists():
+ event_type = TransactionEventType.AUTHORIZATION_ADJUSTMENT
+ # adjust overwrite the amount of authorization so we need to set
+ # current auth value to 0, to match calculations
+ current_authorized_value = Decimal(0)
+ if transaction.authorized_value != authorized_value:
+ events_to_create.append(
+ _prepare_manual_event(
+ transaction,
+ current_authorized_value,
+ authorized_value,
+ event_type,
+ user,
+ app,
+ )
+ )
+ prepare_manual_event(
+ events_to_create=events_to_create,
+ amount_field="charged_value",
+ money_data=money_data,
+ event_type=TransactionEventType.CHARGE_SUCCESS,
+ transaction=transaction,
+ app=app,
+ user=user,
+ )
+ prepare_manual_event(
+ events_to_create=events_to_create,
+ amount_field="refunded_value",
+ money_data=money_data,
+ event_type=TransactionEventType.REFUND_SUCCESS,
+ transaction=transaction,
+ app=app,
+ user=user,
+ )
+ prepare_manual_event(
+ events_to_create=events_to_create,
+ amount_field="canceled_value",
+ money_data=money_data,
+ event_type=TransactionEventType.CANCEL_SUCCESS,
+ transaction=transaction,
+ app=app,
+ user=user,
+ )
+ if events_to_create:
+ return TransactionEvent.objects.bulk_create(events_to_create)
+ return []
+
+
+def create_transaction_for_order(
+ order: "Order",
+ user: Optional["User"],
+ app: Optional["App"],
+ psp_reference: Optional[str],
+ charged_value: Decimal,
+) -> TransactionItem:
+ transaction = TransactionItem.objects.create(
+ order_id=order.pk,
+ user=user,
+ app_identifier=app.identifier if app else None,
+ app=app,
+ psp_reference=psp_reference,
+ currency=order.currency,
+ )
+ create_manual_adjustment_events(
+ transaction=transaction,
+ money_data={"charged_value": charged_value},
+ user=user,
+ app=app,
+ )
+ recalculate_transaction_amounts(transaction=transaction)
+ return transaction
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index dca7d45ba6..34f037b85d 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -770,6 +770,12 @@ class BasePlugin:
transaction_action_request: Callable[["TransactionActionData", None], None]
+ transaction_charge_requested: Callable[["TransactionActionData", None], None]
+
+ transaction_cancelation_requested: Callable[["TransactionActionData", None], None]
+
+ transaction_refund_requested: Callable[["TransactionActionData", None], None]
+
# Trigger when transaction item metadata is updated.
#
# Overwrite this method if you need to trigger specific logic when a transaction
diff --git a/saleor/plugins/const.py b/saleor/plugins/const.py
new file mode 100644
index 0000000000..6a9dee5a57
--- /dev/null
+++ b/saleor/plugins/const.py
@@ -0,0 +1 @@
+APP_ID_PREFIX = "app"
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 35642c714f..c8fa62271f 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -957,6 +957,39 @@ class PluginsManager(PaymentInterface):
channel_slug=channel_slug,
)
+ def transaction_charge_requested(
+ self, payment_data: "TransactionActionData", channel_slug: str
+ ):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "transaction_charge_requested",
+ default_value,
+ payment_data,
+ channel_slug=channel_slug,
+ )
+
+ def transaction_refund_requested(
+ self, payment_data: "TransactionActionData", channel_slug: str
+ ):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "transaction_refund_requested",
+ default_value,
+ payment_data,
+ channel_slug=channel_slug,
+ )
+
+ def transaction_cancelation_requested(
+ self, payment_data: "TransactionActionData", channel_slug: str
+ ):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "transaction_cancelation_requested",
+ default_value,
+ payment_data,
+ channel_slug=channel_slug,
+ )
+
def transaction_item_metadata_updated(self, transaction_item: "TransactionItem"):
default_value = None
return self.__run_method_on_plugins(
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 090e527123..99ea2c7c51 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -49,6 +49,7 @@ from .shipping import get_excluded_shipping_data, parse_list_shipping_methods_re
from .tasks import (
send_webhook_request_async,
trigger_all_webhooks_sync,
+ trigger_transaction_request,
trigger_webhook_sync,
trigger_webhooks_async,
)
@@ -1360,6 +1361,61 @@ class WebhookPlugin(BasePlugin):
requestor=self.requestor,
)
+ def _request_transaction_action(
+ self,
+ transaction_data: "TransactionActionData",
+ event_type: str,
+ previous_value: Any,
+ ) -> None:
+ if not self.active:
+ return previous_value
+
+ if not transaction_data.transaction_app_owner:
+ logger.warning(
+ f"Transaction request skipped for "
+ f"{transaction_data.transaction.psp_reference}. "
+ f"Missing relation to App."
+ )
+ return None
+
+ if not transaction_data.event:
+ logger.warning(
+ f"Transaction request skipped for "
+ f"{transaction_data.transaction.psp_reference}. "
+ f"Missing relation to TransactionEvent."
+ )
+ return None
+
+ trigger_transaction_request(transaction_data, event_type, self.requestor)
+ return None
+
+ def transaction_charge_requested(
+ self, transaction_data: "TransactionActionData", previous_value: Any
+ ):
+ return self._request_transaction_action(
+ transaction_data,
+ WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED,
+ previous_value,
+ )
+
+ def transaction_refund_requested(
+ self, transaction_data: "TransactionActionData", previous_value: Any
+ ):
+ return self._request_transaction_action(
+ transaction_data,
+ WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,
+ previous_value,
+ )
+
+ def transaction_cancelation_requested(
+ self, transaction_data: "TransactionActionData", previous_value: Any
+ ):
+ return self._request_transaction_action(
+ transaction_data,
+ WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED,
+ previous_value,
+ )
+
def __run_payment_webhook(
self,
event_type: str,
@@ -1654,5 +1710,7 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST
),
}
- webhooks = get_webhooks_for_event(event_type=map_event[event])
- return any(webhooks)
+
+ if event in map_event:
+ return any(get_webhooks_for_event(event_type=map_event[event]))
+ return False
diff --git a/saleor/plugins/webhook/shipping.py b/saleor/plugins/webhook/shipping.py
index faaa4ecfdd..39c7ab9d5e 100644
--- a/saleor/plugins/webhook/shipping.py
+++ b/saleor/plugins/webhook/shipping.py
@@ -17,9 +17,9 @@ from ...order.models import Order
from ...shipping.interface import ShippingMethodData
from ...webhook.utils import get_webhooks_for_event
from ..base_plugin import ExcludedShippingMethod
+from ..const import APP_ID_PREFIX
from .const import CACHE_EXCLUDED_SHIPPING_TIME, EXCLUDED_SHIPPING_REQUEST_TIMEOUT
from .tasks import trigger_webhook_sync
-from .utils import APP_ID_PREFIX
logger = logging.getLogger(__name__)
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index 8fe7512491..a39d76f8ed 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -3,7 +3,7 @@ import logging
from dataclasses import dataclass
from enum import Enum
from json import JSONDecodeError
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, TypeVar
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, TypeVar
from urllib.parse import unquote, urlparse, urlunparse
import boto3
@@ -23,16 +23,24 @@ from ...core import EventDeliveryStatus
from ...core.models import EventDelivery, EventPayload
from ...core.tracing import webhooks_opentracing_trace
from ...core.utils import build_absolute_uri
+from ...core.utils.events import call_event
from ...graphql.webhook.subscription_payload import (
generate_payload_from_subscription,
initialize_request,
)
from ...graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP
from ...payment import PaymentError
+from ...payment.interface import TransactionActionData
+from ...payment.models import TransactionEvent
+from ...payment.utils import (
+ create_failed_transaction_event,
+ create_transaction_event_from_request_and_webhook_response,
+)
from ...site.models import Site
from ...webhook import observability
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...webhook.observability import WebhookData
+from ...webhook.payloads import generate_transaction_action_request_payload
from ...webhook.utils import get_webhooks_for_event
from . import signature_for_payload
from .utils import (
@@ -42,6 +50,7 @@ from .utils import (
create_attempt,
create_event_delivery_list_for_webhooks,
delivery_update,
+ get_delivery_for_webhook,
)
if TYPE_CHECKING:
@@ -481,6 +490,43 @@ def send_webhook_using_scheme_method(
raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))
+def handle_webhook_retry(
+ celery_task, webhook, response_content, delivery, delivery_attempt
+) -> bool:
+ """Handle celery retry for webhook requests.
+
+ Calls retry to re-run the celery_task by raising Retry exception.
+ When MaxRetriesExceededError is raised the function will end without exception.
+ """
+ is_success = True
+ task_logger.info(
+ "[Webhook ID: %r] Failed request to %r: %r for event: %r."
+ " Delivery attempt id: %r",
+ webhook.id,
+ webhook.target_url,
+ response_content,
+ delivery.event_type,
+ delivery_attempt.id,
+ )
+ try:
+ countdown = celery_task.retry_backoff * (2**celery_task.request.retries)
+ celery_task.retry(countdown=countdown, **celery_task.retry_kwargs)
+ except Retry as retry_error:
+ next_retry = observability.task_next_retry_date(retry_error)
+ observability.report_event_delivery_attempt(delivery_attempt, next_retry)
+ raise retry_error
+ except MaxRetriesExceededError:
+ is_success = False
+ task_logger.info(
+ "[Webhook ID: %r] Failed request to %r: exceeded retry limit."
+ "Delivery id: %r",
+ webhook.id,
+ webhook.target_url,
+ delivery.id,
+ )
+ return is_success
+
+
@app.task(
queue=settings.WEBHOOK_CELERY_QUEUE_NAME,
bind=True,
@@ -488,18 +534,9 @@ def send_webhook_using_scheme_method(
retry_kwargs={"max_retries": 5},
)
def send_webhook_request_async(self, event_delivery_id):
- try:
- delivery = EventDelivery.objects.select_related("payload", "webhook__app").get(
- id=event_delivery_id
- )
- except EventDelivery.DoesNotExist:
- logger.error("Event delivery id: %r not found", event_delivery_id)
- return
-
- if not delivery.webhook.is_active:
- delivery_update(delivery=delivery, status=EventDeliveryStatus.FAILED)
- logger.info("Event delivery id: %r webhook is disabled.", event_delivery_id)
- return
+ delivery = get_delivery_for_webhook(event_delivery_id)
+ if not delivery:
+ return None
webhook = delivery.webhook
domain = Site.objects.get_current().domain
@@ -525,31 +562,8 @@ def send_webhook_request_async(self, event_delivery_id):
attempt_update(attempt, response)
if response.status == EventDeliveryStatus.FAILED:
- task_logger.info(
- "[Webhook ID: %r] Failed request to %r: %r for event: %r."
- " Delivery attempt id: %r",
- webhook.id,
- webhook.target_url,
- response.content,
- delivery.event_type,
- attempt.id,
- )
- try:
- countdown = self.retry_backoff * (2**self.request.retries)
- self.retry(countdown=countdown, **self.retry_kwargs)
- except Retry as retry_error:
- next_retry = observability.task_next_retry_date(retry_error)
- observability.report_event_delivery_attempt(attempt, next_retry)
- raise retry_error
- except MaxRetriesExceededError:
- task_logger.info(
- "[Webhook ID: %r] Failed request to %r: exceeded retry limit."
- "Delivery id: %r",
- webhook.id,
- webhook.target_url,
- delivery.id,
- )
- delivery_status = EventDeliveryStatus.FAILED
+ handle_webhook_retry(self, webhook, response.content, delivery, attempt)
+ delivery_status = EventDeliveryStatus.FAILED
elif response.status == EventDeliveryStatus.SUCCESS:
task_logger.info(
"[Webhook ID:%r] Payload sent to %r for event %r. Delivery id: %r",
@@ -567,9 +581,9 @@ def send_webhook_request_async(self, event_delivery_id):
clear_successful_delivery(delivery)
-def send_webhook_request_sync(
- app_name, delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT
-) -> Optional[Dict[Any, Any]]:
+def _send_webhook_request_sync(
+ app_name, delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT, attempt=None
+) -> Tuple[WebhookResponse, Optional[Dict[Any, Any]]]:
event_payload = delivery.payload
data = event_payload.payload
webhook = delivery.webhook
@@ -587,7 +601,8 @@ def send_webhook_request_sync(
webhook.target_url,
delivery.event_type,
)
- attempt = create_attempt(delivery=delivery, task_id=None)
+ if attempt is None:
+ attempt = create_attempt(delivery=delivery, task_id=None)
response = WebhookResponse(content="")
response_data = None
@@ -636,7 +651,13 @@ def send_webhook_request_sync(
delivery_update(delivery, response.status)
observability.report_event_delivery_attempt(attempt)
clear_successful_delivery(delivery)
+ return response, response_data
+
+def send_webhook_request_sync(
+ app_name, delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT
+) -> Optional[Dict[Any, Any]]:
+ response, response_data = _send_webhook_request_sync(app_name, delivery, timeout)
return response_data if response.status == EventDeliveryStatus.SUCCESS else None
@@ -723,3 +744,101 @@ def observability_reporter_task():
if events:
with observability.opentracing_trace("send_events", "webhooks"):
send_observability_events(webhooks, events)
+
+
+def trigger_transaction_request(
+ transaction_data: "TransactionActionData", event_type: str, requestor
+):
+ if not transaction_data.event:
+ logger.warning(
+ "The transaction request for transaction: %s doesn't have a "
+ "proper REQUEST event.",
+ transaction_data.transaction.id,
+ )
+ return None
+ if not transaction_data.transaction_app_owner:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause=(
+ "Cannot process the action as the given transaction is not "
+ "attached to any app."
+ ),
+ )
+ return None
+ webhook = get_webhooks_for_event(
+ event_type, apps_ids=[transaction_data.transaction_app_owner.pk]
+ ).first()
+ if not webhook:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause="Cannot find a webhook that can process the action.",
+ )
+ return None
+
+ if webhook.subscription_query:
+ delivery = create_delivery_for_subscription_sync_event(
+ event_type=event_type,
+ subscribable_object=transaction_data,
+ webhook=webhook,
+ )
+ if not delivery:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause="Cannot generate a payload for the action.",
+ )
+ return None
+ else:
+ payload = generate_transaction_action_request_payload(
+ transaction_data, requestor
+ )
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=event_type,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ call_event(
+ handle_transaction_request_task.delay,
+ delivery.id,
+ webhook.app.name,
+ transaction_data.event.id,
+ )
+ return None
+
+
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+)
+def handle_transaction_request_task(self, delivery_id, app_name, request_event_id):
+ delivery = get_delivery_for_webhook(delivery_id)
+ if not delivery:
+ logger.error(
+ f"Cannot find the delivery with id: {delivery_id} "
+ f"for transaction-request webhook."
+ )
+ return None
+ request_event = TransactionEvent.objects.filter(id=request_event_id).first()
+ if not request_event:
+ logger.error(
+ f"Cannot find the request event with id: {request_event_id} "
+ f"for transaction-request webhook."
+ )
+ return None
+ attempt = create_attempt(delivery, self.request.id)
+ response, response_data = _send_webhook_request_sync(
+ app_name, delivery, attempt=attempt
+ )
+ if response.response_status_code and response.response_status_code >= 500:
+ handle_webhook_retry(
+ self, delivery.webhook, response.content, delivery, attempt
+ )
+ response_data = None
+ create_transaction_event_from_request_and_webhook_response(
+ request_event,
+ delivery.webhook.app,
+ response_data,
+ )
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index 299f528303..783d4c4a2c 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -1918,18 +1918,19 @@ def test_voucher_metadata_updated(
def test_transaction_item_metadata_updated(
- transaction_item, subscription_transaction_item_metadata_updated_webhook
+ transaction_item_created_by_app,
+ subscription_transaction_item_metadata_updated_webhook,
):
# given
webhooks = [subscription_transaction_item_metadata_updated_webhook]
event_type = WebhookEventAsyncType.TRANSACTION_ITEM_METADATA_UPDATED
transaction_item_id = graphene.Node.to_global_id(
- "TransactionItem", transaction_item.id
+ "TransactionItem", transaction_item_created_by_app.id
)
# when
deliveries = create_deliveries_for_subscriptions(
- event_type, transaction_item, webhooks
+ event_type, transaction_item_created_by_app, webhooks
)
# then
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
index 320372f760..f02637b9a1 100644
--- 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
@@ -5,7 +5,7 @@ import graphene
from freezegun import freeze_time
from .....core.prices import quantize_price
-from .....payment import TransactionAction
+from .....payment import TransactionAction, TransactionEventType
from .....payment.interface import TransactionActionData
from .....payment.models import TransactionItem
from .....webhook.event_types import WebhookEventAsyncType
@@ -41,6 +41,7 @@ subscription{
}
status
type
+ pspReference
reference
order {
id
@@ -65,13 +66,19 @@ def test_transaction_refund_action_request(
webhook_app.permissions.add(permission_manage_payments)
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["refund"],
currency="USD",
order_id=order.pk,
charged_value=charged_value,
)
+ action_value = Decimal("5.00")
+ request_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ )
webhook = Webhook.objects.create(
name="Webhook",
app=webhook_app,
@@ -82,11 +89,12 @@ def test_transaction_refund_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,
+ event=request_event,
+ transaction_app_owner=None,
)
# when
deliveries = create_deliveries_for_subscriptions(
@@ -104,17 +112,20 @@ def test_transaction_refund_action_request(
"voidedAmount": {"currency": "USD", "amount": 0.0},
"chargedAmount": {
"currency": "USD",
- "amount": quantize_price(charged_value, "USD"),
+ "amount": float(quantize_price(charged_value, "USD")),
},
- "events": [],
+ "events": [
+ {"id": graphene.Node.to_global_id("TransactionEvent", request_event.id)}
+ ],
"status": "Captured",
"type": "Credit card",
"reference": "PSP ref",
+ "pspReference": "PSP ref",
"order": {"id": graphene.Node.to_global_id("Order", order.id)},
},
"action": {
"actionType": "REFUND",
- "amount": quantize_price(action_value, "USD"),
+ "amount": float(quantize_price(action_value, "USD")),
},
}
@@ -128,13 +139,18 @@ def test_transaction_charge_action_request(
webhook_app.permissions.add(permission_manage_payments)
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["charge"],
currency="USD",
order_id=order.pk,
authorized_value=authorized_value,
)
+ request_event = transaction.events.create(
+ amount_value=authorized_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
webhook = Webhook.objects.create(
name="Webhook",
app=webhook_app,
@@ -150,6 +166,8 @@ def test_transaction_charge_action_request(
transaction=transaction,
action_type=TransactionAction.CHARGE,
action_value=action_value,
+ event=request_event,
+ transaction_app_owner=None,
)
# when
deliveries = create_deliveries_for_subscriptions(
@@ -169,10 +187,13 @@ def test_transaction_charge_action_request(
"refundedAmount": {"currency": "USD", "amount": 0.0},
"voidedAmount": {"currency": "USD", "amount": 0.0},
"chargedAmount": {"currency": "USD", "amount": 0.0},
- "events": [],
+ "events": [
+ {"id": graphene.Node.to_global_id("TransactionEvent", request_event.id)}
+ ],
"status": "Authorized",
"type": "Credit card",
"reference": "PSP ref",
+ "pspReference": "PSP ref",
"order": {"id": graphene.Node.to_global_id("Order", order.id)},
},
"action": {
@@ -191,13 +212,18 @@ def test_transaction_void_action_request(
webhook_app.permissions.add(permission_manage_payments)
transaction = TransactionItem.objects.create(
status="Captured",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["void"],
currency="USD",
order_id=order.pk,
authorized_value=authorized_value,
)
+ request_event = transaction.events.create(
+ amount_value=authorized_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CANCEL_REQUEST,
+ )
webhook = Webhook.objects.create(
name="Webhook",
app=webhook_app,
@@ -212,6 +238,8 @@ def test_transaction_void_action_request(
transaction_data = TransactionActionData(
transaction=transaction,
action_type=TransactionAction.VOID,
+ event=request_event,
+ transaction_app_owner=None,
)
# when
deliveries = create_deliveries_for_subscriptions(
@@ -231,10 +259,13 @@ def test_transaction_void_action_request(
"refundedAmount": {"currency": "USD", "amount": 0.0},
"voidedAmount": {"currency": "USD", "amount": 0.0},
"chargedAmount": {"currency": "USD", "amount": 0.0},
- "events": [],
+ "events": [
+ {"id": graphene.Node.to_global_id("TransactionEvent", request_event.id)}
+ ],
"status": "Captured",
"type": "Credit card",
"reference": "PSP ref",
+ "pspReference": "PSP ref",
"order": {"id": graphene.Node.to_global_id("Order", order.id)},
},
"action": {"actionType": "VOID", "amount": None},
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py
new file mode 100644
index 0000000000..06deea9580
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py
@@ -0,0 +1,101 @@
+import json
+from decimal import Decimal
+
+import graphene
+from freezegun import freeze_time
+
+from .....core.prices import quantize_price
+from .....graphql.tests.queries import fragments
+from .....payment import TransactionAction, TransactionEventType
+from .....payment.interface import TransactionActionData
+from .....payment.models import TransactionItem
+from .....webhook.event_types import WebhookEventSyncType
+from .....webhook.models import Webhook
+from ...tasks import create_deliveries_for_subscriptions
+
+TRANSACTION_CANCELATION_REQUESTED_SUBSCRIPTION = (
+ fragments.TRANSACTION_ITEM_DETAILS
+ + """
+subscription {
+ event {
+ ... on TransactionCancelationRequested {
+ transaction {
+ ...TransactionFragment
+ }
+ action {
+ actionType
+ amount
+ }
+ }
+ }
+}
+"""
+)
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_transaction_void_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",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=authorized_value,
+ )
+
+ request_event = transaction.events.create(
+ currency=transaction.currency,
+ type=TransactionEventType.CANCEL_REQUEST,
+ )
+
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TRANSACTION_CANCELATION_REQUESTED_SUBSCRIPTION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED
+ 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,
+ event=request_event,
+ transaction_app_owner=None,
+ )
+ # 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},
+ "chargedAmount": {"currency": "USD", "amount": 0.0},
+ "events": [
+ {"id": graphene.Node.to_global_id("TransactionEvent", request_event.id)}
+ ],
+ "status": "Captured",
+ "type": "Credit card",
+ "reference": "PSP ref",
+ "pspReference": "PSP ref",
+ "order": {"id": graphene.Node.to_global_id("Order", order.id)},
+ },
+ "action": {"actionType": "VOID", "amount": None},
+ }
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_charge_requested.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_charge_requested.py
new file mode 100644
index 0000000000..37af9faffe
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_charge_requested.py
@@ -0,0 +1,106 @@
+import json
+from decimal import Decimal
+
+import graphene
+from freezegun import freeze_time
+
+from .....core.prices import quantize_price
+from .....graphql.tests.queries import fragments
+from .....payment import TransactionAction, TransactionEventType
+from .....payment.interface import TransactionActionData
+from .....payment.models import TransactionItem
+from .....webhook.event_types import WebhookEventSyncType
+from .....webhook.models import Webhook
+from ...tasks import create_deliveries_for_subscriptions
+
+TRANSACTION_CHARGE_REQUESTED_SUBSCRIPTION = (
+ fragments.TRANSACTION_ITEM_DETAILS
+ + """
+subscription {
+ event {
+ ... on TransactionChargeRequested {
+ transaction {
+ ...TransactionFragment
+ }
+ action {
+ actionType
+ amount
+ }
+ }
+ }
+}
+"""
+)
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_transaction_charge_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",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["charge"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=authorized_value,
+ )
+
+ action_value = Decimal("5.00")
+ request_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TRANSACTION_CHARGE_REQUESTED_SUBSCRIPTION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED
+ 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.CHARGE,
+ action_value=action_value,
+ event=request_event,
+ transaction_app_owner=None,
+ )
+ # 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": ["CHARGE"],
+ "authorizedAmount": {
+ "currency": "USD",
+ "amount": quantize_price(authorized_value, "USD"),
+ },
+ "refundedAmount": {"currency": "USD", "amount": 0.0},
+ "voidedAmount": {"currency": "USD", "amount": 0.0},
+ "chargedAmount": {"currency": "USD", "amount": 0.0},
+ "events": [
+ {"id": graphene.Node.to_global_id("TransactionEvent", request_event.id)}
+ ],
+ "status": "Authorized",
+ "type": "Credit card",
+ "reference": "PSP ref",
+ "pspReference": "PSP ref",
+ "order": {"id": graphene.Node.to_global_id("Order", order.id)},
+ },
+ "action": {
+ "actionType": "CHARGE",
+ "amount": quantize_price(action_value, "USD"),
+ },
+ }
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py
new file mode 100644
index 0000000000..cf14eba037
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py
@@ -0,0 +1,106 @@
+import json
+from decimal import Decimal
+
+import graphene
+from freezegun import freeze_time
+
+from .....core.prices import quantize_price
+from .....graphql.tests.queries import fragments
+from .....payment import TransactionAction, TransactionEventType
+from .....payment.interface import TransactionActionData
+from .....payment.models import TransactionItem
+from .....webhook.event_types import WebhookEventSyncType
+from .....webhook.models import Webhook
+from ...tasks import create_deliveries_for_subscriptions
+
+TRANSACTION_REFUND_REQUESTED_SUBSCRIPTION = (
+ fragments.TRANSACTION_ITEM_DETAILS
+ + """
+subscription {
+ event {
+ ... on TransactionRefundRequested {
+ transaction {
+ ...TransactionFragment
+ }
+ action {
+ actionType
+ amount
+ }
+ }
+ }
+}
+"""
+)
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_transaction_refund_request(order, webhook_app, permission_manage_payments):
+ # given
+ charged_value = Decimal("10")
+ webhook_app.permissions.add(permission_manage_payments)
+ transaction = TransactionItem.objects.create(
+ status="Captured",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ order_id=order.pk,
+ charged_value=charged_value,
+ )
+
+ action_value = Decimal("5.00")
+ request_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.REFUND_REQUEST,
+ )
+
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TRANSACTION_REFUND_REQUESTED_SUBSCRIPTION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ 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.REFUND,
+ action_value=action_value,
+ event=request_event,
+ transaction_app_owner=None,
+ )
+ # 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},
+ "chargedAmount": {
+ "currency": "USD",
+ "amount": quantize_price(charged_value, "USD"),
+ },
+ "events": [
+ {"id": graphene.Node.to_global_id("TransactionEvent", request_event.id)}
+ ],
+ "status": "Captured",
+ "type": "Credit card",
+ "reference": "PSP ref",
+ "pspReference": "PSP ref",
+ "order": {"id": graphene.Node.to_global_id("Order", order.id)},
+ },
+ "action": {
+ "actionType": "REFUND",
+ "amount": quantize_price(action_value, "USD"),
+ },
+ }
diff --git a/saleor/plugins/webhook/tests/test_tasks.py b/saleor/plugins/webhook/tests/test_tasks.py
new file mode 100644
index 0000000000..9705ea5eef
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_tasks.py
@@ -0,0 +1,686 @@
+import json
+from decimal import Decimal
+from unittest import mock
+
+import pytest
+from django.utils import timezone
+from freezegun import freeze_time
+from graphene import Node
+
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery, EventPayload
+from ....payment import TransactionEventType
+from ....payment.interface import TransactionActionData
+from ....payment.models import TransactionEvent
+from ....payment.transaction_item_calculations import recalculate_transaction_amounts
+from ....tests.utils import flush_post_commit_hooks
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.payloads import generate_transaction_action_request_payload
+from ..tasks import handle_transaction_request_task, trigger_transaction_request
+
+
+def mocked_webhook_response():
+ mocked_post_response = mock.Mock()
+ mocked_post_response.text = json.dumps({"pspReference": "123"})
+ mocked_post_response.headers = []
+ mocked_post_response.status_code = 200
+ mocked_post_response.ok = True
+ mocked_post_response.content = json.dumps({"pspReference": "123"})
+ mocked_post_response.elapsed.total_seconds = lambda: 1 # noqa: E731
+ return mocked_post_response
+
+
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")
+def test_trigger_transaction_request(
+ mocked_task,
+ transaction_item_created_by_app,
+ staff_user,
+ permission_manage_payments,
+ app,
+):
+ # given
+ event = transaction_item_created_by_app.events.create(
+ type=TransactionEventType.REFUND_REQUEST
+ )
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook", is_active=True, target_url="http://localhost:3000/"
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction_item_created_by_app,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ # when
+ trigger_transaction_request(
+ transaction_data, WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED, staff_user
+ )
+
+ # then
+ flush_post_commit_hooks()
+ generated_payload = EventPayload.objects.first()
+ generated_delivery = EventDelivery.objects.first()
+
+ assert generated_payload.payload == generate_transaction_action_request_payload(
+ transaction_data, staff_user
+ )
+ assert generated_delivery.status == EventDeliveryStatus.PENDING
+ assert (
+ generated_delivery.event_type
+ == WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ assert generated_delivery.webhook == webhook
+ assert generated_delivery.payload == generated_payload
+
+ mocked_task.assert_called_once_with(generated_delivery.id, app.name, event.id)
+
+
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")
+def test_trigger_transaction_request_with_webhook_subscription(
+ mocked_task,
+ transaction_item_created_by_app,
+ staff_user,
+ permission_manage_payments,
+ app,
+):
+ # given
+ subscription = """
+ subscription{
+ event{
+ ...on TransactionRefundRequested{
+ transaction{
+ id
+ }
+ action{
+ amount
+ actionType
+ }
+ }
+ }
+ }
+ """
+ event = transaction_item_created_by_app.events.create(
+ type=TransactionEventType.REFUND_REQUEST
+ )
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url="http://localhost:3000/",
+ subscription_query=subscription,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction_item_created_by_app,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ # when
+ trigger_transaction_request(
+ transaction_data, WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED, staff_user
+ )
+
+ # then
+ flush_post_commit_hooks()
+ generated_payload = EventPayload.objects.first()
+ generated_delivery = EventDelivery.objects.first()
+
+ assert generated_payload
+ assert generated_delivery
+ assert json.loads(generated_payload.payload) == {
+ "transaction": {
+ "id": Node.to_global_id("TransactionItem", transaction_data.transaction.id),
+ },
+ "action": {"amount": 10.0, "actionType": "REFUND"},
+ }
+ assert generated_delivery.status == EventDeliveryStatus.PENDING
+ assert (
+ generated_delivery.event_type
+ == WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
+ )
+ assert generated_delivery.webhook == webhook
+
+ assert generated_delivery.payload == generated_payload
+
+ mocked_task.assert_called_once_with(generated_delivery.id, app.name, event.id)
+
+
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
+def test_handle_transaction_request_task_with_only_psp_reference(
+ mocked_post_request,
+ transaction_item_generator,
+ permission_manage_payments,
+ staff_user,
+ mocked_webhook_response,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ expected_psp_reference = "psp:ref:123"
+ mocked_webhook_response.text = json.dumps({"pspReference": expected_psp_reference})
+ mocked_webhook_response.content = json.dumps(
+ {"pspReference": expected_psp_reference}
+ )
+ mocked_post_request.return_value = mocked_webhook_response
+
+ target_url = "http://localhost:3000/"
+
+ event = transaction.events.create(type=TransactionEventType.REFUND_REQUEST)
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url=target_url,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ payload = generate_transaction_action_request_payload(transaction_data, staff_user)
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ # when
+ handle_transaction_request_task(delivery.id, app.name, transaction_data.event.id)
+
+ # then
+ assert TransactionEvent.objects.count() == 1
+ event.refresh_from_db()
+ assert event.psp_reference == expected_psp_reference
+ mocked_post_request.assert_called_once_with(
+ target_url, data=payload.encode("utf-8"), headers=mock.ANY, timeout=mock.ANY
+ )
+
+
[email protected]("status_code", [500, 501, 510])
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.handle_webhook_retry")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
+def test_handle_transaction_request_task_with_server_error(
+ mocked_post_request,
+ mocked_webhook_retry,
+ status_code,
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ staff_user,
+ mocked_webhook_response,
+ app,
+):
+ # given
+ mocked_webhook_response.status_code = status_code
+ mocked_webhook_response.text = ""
+ mocked_webhook_response.content = ""
+ mocked_post_request.return_value = mocked_webhook_response
+
+ target_url = "http://localhost:3000/"
+
+ event = transaction_item_created_by_app.events.create(
+ type=TransactionEventType.CHARGE_REQUEST
+ )
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url=target_url,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction_item_created_by_app,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ payload = generate_transaction_action_request_payload(transaction_data, staff_user)
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ # when
+ handle_transaction_request_task(delivery.id, app.name, transaction_data.event.id)
+
+ # then
+ assert mocked_webhook_retry.called
+
+
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
+def test_handle_transaction_request_task_with_missing_psp_reference(
+ mocked_post_request,
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ staff_user,
+ mocked_webhook_response,
+ app,
+):
+ # given
+ mocked_webhook_response.text = "{}"
+ mocked_webhook_response.content = "{}"
+ mocked_post_request.return_value = mocked_webhook_response
+
+ target_url = "http://localhost:3000/"
+
+ event = transaction_item_created_by_app.events.create(
+ type=TransactionEventType.REFUND_REQUEST
+ )
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url=target_url,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction_item_created_by_app,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ payload = generate_transaction_action_request_payload(transaction_data, staff_user)
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ # when
+ handle_transaction_request_task(delivery.id, app.name, transaction_data.event.id)
+
+ # then
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_FAILURE
+ ).count()
+ == 1
+ )
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST
+ ).count()
+ == 1
+ )
+ failure_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_FAILURE
+ ).first()
+ event.refresh_from_db()
+ assert event.psp_reference is None
+ assert failure_event.amount_value == event.amount_value
+ assert failure_event.transaction_id == event.transaction_id
+ mocked_post_request.assert_called_once_with(
+ target_url, data=payload.encode("utf-8"), headers=mock.ANY, timeout=mock.ANY
+ )
+
+
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
+def test_handle_transaction_request_task_with_missing_required_event_field(
+ mocked_post_request,
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ staff_user,
+ mocked_webhook_response,
+ app,
+):
+ # given
+ expected_psp_reference = "psp:123:111"
+ mocked_webhook_response.text = json.dumps(
+ {"pspReference": expected_psp_reference, "amount": 12.00}
+ )
+ mocked_webhook_response.content = json.dumps(
+ {"pspReference": expected_psp_reference, "amount": 12.00}
+ )
+ mocked_post_request.return_value = mocked_webhook_response
+
+ target_url = "http://localhost:3000/"
+
+ event = transaction_item_created_by_app.events.create(
+ type=TransactionEventType.REFUND_REQUEST
+ )
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url=target_url,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction_item_created_by_app,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ payload = generate_transaction_action_request_payload(transaction_data, staff_user)
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ # when
+ handle_transaction_request_task(delivery.id, app.name, transaction_data.event.id)
+
+ # then
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_FAILURE
+ ).count()
+ == 1
+ )
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST
+ ).count()
+ == 1
+ )
+ failure_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_FAILURE
+ ).first()
+ event.refresh_from_db()
+ assert event.psp_reference is None
+ assert failure_event.amount_value == event.amount_value
+ assert failure_event.transaction_id == event.transaction_id
+ mocked_post_request.assert_called_once_with(
+ target_url, data=payload.encode("utf-8"), headers=mock.ANY, timeout=mock.ANY
+ )
+
+
+@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
+def test_handle_transaction_request_task_with_result_event(
+ mocked_post_request,
+ transaction_item_generator,
+ permission_manage_payments,
+ staff_user,
+ mocked_webhook_response,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ request_psp_reference = "psp:123:111"
+ event_amount = 12.00
+ event_type = TransactionEventType.CHARGE_SUCCESS
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ response_payload = {
+ "pspReference": request_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ }
+ mocked_webhook_response.text = json.dumps(response_payload)
+ mocked_webhook_response.content = json.dumps(response_payload)
+ mocked_post_request.return_value = mocked_webhook_response
+
+ target_url = "http://localhost:3000/"
+
+ request_event = transaction.events.create(type=TransactionEventType.CHARGE_REQUEST)
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url=target_url,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=request_event,
+ transaction_app_owner=app,
+ )
+
+ payload = generate_transaction_action_request_payload(transaction_data, staff_user)
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ # when
+ handle_transaction_request_task(delivery.id, app.name, transaction_data.event.id)
+
+ # then
+ assert TransactionEvent.objects.all().count() == 2
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST
+ ).count()
+ == 1
+ )
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).count()
+ == 1
+ )
+ success_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).first()
+ assert success_event
+ request_event.refresh_from_db()
+ assert request_event.psp_reference == request_psp_reference
+ assert success_event.psp_reference == request_psp_reference
+ assert success_event.amount_value == event_amount
+ assert success_event.created_at.isoformat() == event_time
+ assert success_event.external_url == event_url
+ assert success_event.message == event_cause
+
+ mocked_post_request.assert_called_once_with(
+ target_url, data=payload.encode("utf-8"), headers=mock.ANY, timeout=mock.ANY
+ )
+
+
+@freeze_time("2022-06-11T17:50:00+00:00")
[email protected]("saleor.plugins.webhook.tasks.requests.post")
+def test_handle_transaction_request_task_with_only_required_fields_for_result_event(
+ mocked_post_request,
+ transaction_item_generator,
+ permission_manage_payments,
+ staff_user,
+ mocked_webhook_response,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ request_psp_reference = "psp:123:111"
+
+ request_event = transaction.events.create(type=TransactionEventType.REFUND_REQUEST)
+
+ response_payload = {
+ "pspReference": request_psp_reference,
+ "result": TransactionEventType.REFUND_SUCCESS.upper(),
+ "amount": str(request_event.amount_value),
+ }
+ mocked_webhook_response.text = json.dumps(response_payload)
+ mocked_webhook_response.content = json.dumps(response_payload)
+ mocked_post_request.return_value = mocked_webhook_response
+
+ target_url = "http://localhost:3000/"
+
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url=target_url,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction,
+ action_type="refund",
+ action_value=Decimal("10.00"),
+ event=request_event,
+ transaction_app_owner=app,
+ )
+
+ payload = generate_transaction_action_request_payload(transaction_data, staff_user)
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ # when
+ handle_transaction_request_task(delivery.id, app.name, transaction_data.event.id)
+
+ # then
+ assert TransactionEvent.objects.all().count() == 2
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_REQUEST
+ ).count()
+ == 1
+ )
+ assert (
+ TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_SUCCESS
+ ).count()
+ == 1
+ )
+ success_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.REFUND_SUCCESS
+ ).first()
+ request_event.refresh_from_db()
+ assert success_event
+ assert request_event.psp_reference == request_psp_reference
+ assert success_event.type == TransactionEventType.REFUND_SUCCESS
+ assert success_event.psp_reference == request_psp_reference
+ assert success_event.amount_value == request_event.amount_value
+ assert success_event.created_at == timezone.now()
+ assert success_event.external_url == ""
+ assert success_event.message == ""
+
+ mocked_post_request.assert_called_once_with(
+ target_url, data=payload.encode("utf-8"), headers=mock.ANY, timeout=mock.ANY
+ )
+
+
+@freeze_time("2022-06-11 12:50")
+ "saleor.payment.utils.recalculate_transaction_amounts",
+ wraps=recalculate_transaction_amounts,
+)
[email protected]("saleor.plugins.webhook.tasks.requests.post")
+def test_handle_transaction_request_task_calls_recalculation_of_amounts(
+ mocked_post_request,
+ mocked_recalculation,
+ transaction_item_generator,
+ permission_manage_payments,
+ staff_user,
+ mocked_webhook_response,
+ app,
+):
+ # given
+ transaction = transaction_item_generator()
+ request_psp_reference = "psp:123:111"
+ event_amount = 12.00
+ event_type = TransactionEventType.CHARGE_SUCCESS
+ event_time = "2022-11-18T13:25:58.169685+00:00"
+ event_url = "http://localhost:3000/event/ref123"
+ event_cause = "No cause"
+
+ response_payload = {
+ "pspReference": request_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ "time": event_time,
+ "externalUrl": event_url,
+ "message": event_cause,
+ }
+ mocked_webhook_response.text = json.dumps(response_payload)
+ mocked_webhook_response.content = json.dumps(response_payload)
+ mocked_post_request.return_value = mocked_webhook_response
+
+ target_url = "http://localhost:3000/"
+
+ request_event = transaction.events.create(type=TransactionEventType.CHARGE_REQUEST)
+ app.permissions.set([permission_manage_payments])
+
+ webhook = app.webhooks.create(
+ name="webhook",
+ is_active=True,
+ target_url=target_url,
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED)
+
+ transaction_data = TransactionActionData(
+ transaction=transaction,
+ action_type="charge",
+ action_value=Decimal("12.00"),
+ event=request_event,
+ transaction_app_owner=app,
+ )
+
+ payload = generate_transaction_action_request_payload(transaction_data, staff_user)
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ # when
+ handle_transaction_request_task(delivery.id, app.name, transaction_data.event.id)
+
+ # then
+ mocked_recalculation.assert_called_once_with(transaction)
+ transaction.refresh_from_db()
+ assert transaction.charged_value == event_amount
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 381fa4d82e..912bc54638 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -31,10 +31,10 @@ from ....core.notify_events import NotifyEventType
from ....core.utils.url import prepare_url
from ....discount.utils import fetch_catalogue_info
from ....graphql.discount.mutations.utils import convert_catalogue_info_to_global_ids
-from ....payment import TransactionAction
+from ....payment import TransactionAction, TransactionEventType
from ....payment.interface import TransactionActionData
from ....payment.models import TransactionItem
-from ....webhook.event_types import WebhookEventAsyncType
+from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....webhook.payloads import (
generate_checkout_payload,
generate_collection_payload,
@@ -1148,19 +1148,19 @@ def test_transaction_item_metadata_updated(
mocked_get_webhooks_for_event,
any_webhook,
settings,
- transaction_item,
+ transaction_item_created_by_app,
):
mocked_get_webhooks_for_event.return_value = [any_webhook]
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
manager = get_plugins_manager()
- manager.transaction_item_metadata_updated(transaction_item)
- expected_data = generate_metadata_updated_payload(transaction_item)
+ manager.transaction_item_metadata_updated(transaction_item_created_by_app)
+ expected_data = generate_metadata_updated_payload(transaction_item_created_by_app)
mocked_webhook_trigger.assert_called_once_with(
expected_data,
WebhookEventAsyncType.TRANSACTION_ITEM_METADATA_UPDATED,
[any_webhook],
- transaction_item,
+ transaction_item_created_by_app,
None,
)
@@ -1244,6 +1244,8 @@ def test_create_event_payload_reference_with_error(
send_webhook_request_async(delivery.id)
attempt = EventDeliveryAttempt.objects.first()
+ assert delivery
+ assert attempt
assert delivery.webhook == webhook
assert delivery.event_type == WebhookEventAsyncType.ORDER_CREATED
assert attempt.response == "Unknown webhook scheme: ''"
@@ -1388,6 +1390,9 @@ def test_send_webhook_request_async(
mocked_clear_delivery.assert_called_once_with(event_delivery)
attempt = EventDeliveryAttempt.objects.filter(delivery=event_delivery).first()
delivery = EventDelivery.objects.get(id=event_delivery.pk)
+
+ assert attempt
+ assert delivery
assert attempt.status == EventDeliveryStatus.SUCCESS
assert attempt.response == webhook_response.content
assert attempt.response_headers == json.dumps(webhook_response.response_headers)
@@ -1454,18 +1459,28 @@ def test_transaction_action_request(
manager = get_plugins_manager()
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["capture", "void"],
currency="USD",
order_id=order.pk,
authorized_value=Decimal("10"),
)
+
action_value = Decimal("5.00")
+
+ request_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
transaction_action_data = TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CHARGE,
action_value=action_value,
+ event=request_event,
+ transaction_app_owner=None,
)
# when
@@ -1486,6 +1501,169 @@ def test_transaction_action_request(
)
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_transaction_request")
+def test_transaction_charge_requested(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ order,
+ channel_USD,
+ app,
+):
+ # given
+ any_webhook.app = app
+ any_webhook.save()
+
+ 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",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=app.identifier,
+ app=app,
+ )
+ event = transaction.events.create(type=TransactionEventType.CHARGE_REQUEST)
+ action_value = Decimal("5.00")
+ transaction_action_data = TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CHARGE,
+ action_value=action_value,
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ # when
+ manager.transaction_charge_requested(
+ transaction_action_data, channel_slug=channel_USD.slug
+ )
+
+ # then
+ mocked_webhook_trigger.assert_called_once_with(
+ transaction_action_data,
+ WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED,
+ None,
+ )
+
+
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_transaction_request")
+def test_transaction_refund_requested(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ order,
+ channel_USD,
+ app,
+):
+ # given
+ any_webhook.app = app
+ any_webhook.save()
+
+ 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",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=[
+ "refund",
+ ],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=app.identifier,
+ app=app,
+ )
+ event = transaction.events.create(type=TransactionEventType.REFUND_REQUEST)
+ action_value = Decimal("5.00")
+ transaction_action_data = TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.REFUND,
+ action_value=action_value,
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ # when
+ manager.transaction_refund_requested(
+ transaction_action_data, channel_slug=channel_USD.slug
+ )
+
+ # then
+ mocked_webhook_trigger.assert_called_once_with(
+ transaction_action_data,
+ WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED,
+ None,
+ )
+
+
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_transaction_request")
+def test_transaction_cancelation_requested(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ order,
+ channel_USD,
+ app,
+):
+ # given
+ any_webhook.app = app
+ any_webhook.save()
+
+ 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",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=[
+ "refund",
+ ],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ app_identifier=app.identifier,
+ app=app,
+ )
+ event = transaction.events.create(type=TransactionEventType.CANCEL_REQUEST)
+ action_value = Decimal("5.00")
+ transaction_action_data = TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CANCEL,
+ action_value=action_value,
+ event=event,
+ transaction_app_owner=app,
+ )
+
+ # when
+ manager.transaction_cancelation_requested(
+ transaction_action_data, channel_slug=channel_USD.slug
+ )
+
+ # then
+ mocked_webhook_trigger.assert_called_once_with(
+ transaction_action_data,
+ WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED,
+ None,
+ )
+
+
@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
def test_send_webhook_request_async_when_delivery_attempt_failed(
diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.py
index 5d4eb2b2e7..ff0b5e00f5 100644
--- a/saleor/plugins/webhook/utils.py
+++ b/saleor/plugins/webhook/utils.py
@@ -16,15 +16,13 @@ from ...core.models import (
from ...core.taxes import TaxData, TaxLineData
from ...payment.interface import GatewayResponse, PaymentGateway, PaymentMethodInfo
from ...webhook.event_types import WebhookEventSyncType
+from ..const import APP_ID_PREFIX
if TYPE_CHECKING:
from ...payment.interface import PaymentData
from ...webhook.models import Webhook
from .tasks import WebhookResponse
-APP_GATEWAY_ID_PREFIX = "app"
-
-APP_ID_PREFIX = "app"
logger = logging.getLogger(__name__)
@@ -179,6 +177,22 @@ def parse_tax_data(
return None
+def get_delivery_for_webhook(event_delivery_id) -> Optional["EventDelivery"]:
+ try:
+ delivery = EventDelivery.objects.select_related("payload", "webhook__app").get(
+ id=event_delivery_id
+ )
+ except EventDelivery.DoesNotExist:
+ logger.error("Event delivery id: %r not found", event_delivery_id)
+ return None
+
+ if not delivery.webhook.is_active:
+ delivery_update(delivery=delivery, status=EventDeliveryStatus.FAILED)
+ logger.info("Event delivery id: %r webhook is disabled.", event_delivery_id)
+ return None
+ return delivery
+
+
@contextmanager
def catch_duration_time():
start = time()
diff --git a/saleor/settings.py b/saleor/settings.py
index 677518049f..da97f3a867 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -795,6 +795,7 @@ CHECKOUT_PRICES_TTL = timedelta(
INDEX_MAXIMUM_EXPR_COUNT = 4000
# Maximum related objects that can be indexed in an order
+SEARCH_ORDERS_MAX_INDEXED_TRANSACTIONS = 20
SEARCH_ORDERS_MAX_INDEXED_PAYMENTS = 20
SEARCH_ORDERS_MAX_INDEXED_DISCOUNTS = 20
SEARCH_ORDERS_MAX_INDEXED_LINES = 100
diff --git a/saleor/shipping/interface.py b/saleor/shipping/interface.py
index 9be3a89f21..c2f3bf1e5a 100644
--- a/saleor/shipping/interface.py
+++ b/saleor/shipping/interface.py
@@ -7,7 +7,7 @@ from measurement.measures import Weight
from prices import Money
from ..graphql.core.utils import from_global_id_or_error
-from ..plugins.webhook.utils import APP_ID_PREFIX
+from ..plugins.const import APP_ID_PREFIX
if TYPE_CHECKING:
from ..tax.models import TaxClass
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 449b365600..cf6bc08a8f 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -87,6 +87,8 @@ from ..page.models import Page, PageTranslation, PageType
from ..payment import ChargeStatus, TransactionKind
from ..payment.interface import AddressData, GatewayConfig, GatewayResponse, PaymentData
from ..payment.models import Payment, TransactionItem
+from ..payment.transaction_item_calculations import recalculate_transaction_amounts
+from ..payment.utils import create_manual_adjustment_events
from ..permission.models import Permission
from ..plugins.manager import get_plugins_manager
from ..plugins.webhook.tasks import WebhookResponse
@@ -5507,15 +5509,73 @@ def payment_dummy_credit_card(db, order_with_lines):
@pytest.fixture
-def transaction_item(order):
- return TransactionItem.objects.create(
- status="Captured",
- type="Credit card",
- reference="PSP ref",
- available_actions=["refund"],
- currency="USD",
+def transaction_item_generator():
+ def create_transaction(
+ order_id=None,
+ checkout_id=None,
+ app=None,
+ user=None,
+ psp_reference="PSP ref1",
+ name="Credit card",
+ message="Transasction details",
+ available_actions=None,
+ authorized_value=Decimal(0),
+ charged_value=Decimal(0),
+ refunded_value=Decimal(0),
+ canceled_value=Decimal(0),
+ ):
+ if available_actions is None:
+ available_actions = []
+ transaction = TransactionItem.objects.create(
+ name=name,
+ message=message,
+ psp_reference=psp_reference,
+ available_actions=available_actions,
+ currency="USD",
+ order_id=order_id,
+ checkout_id=checkout_id,
+ app_identifier=app.identifier if app else None,
+ app=app,
+ user=user,
+ )
+ create_manual_adjustment_events(
+ transaction=transaction,
+ money_data={
+ "authorized_value": authorized_value,
+ "charged_value": charged_value,
+ "refunded_value": refunded_value,
+ "canceled_value": canceled_value,
+ },
+ user=user,
+ app=app,
+ )
+ recalculate_transaction_amounts(transaction)
+ return transaction
+
+ return create_transaction
+
+
+def transaction_item_created_by_app(order, app, transaction_item_generator):
+ charged_amount = Decimal("10.0")
+ return transaction_item_generator(
order_id=order.pk,
- charged_value=Decimal("10"),
+ checkout_id=None,
+ app=app,
+ user=None,
+ charged_value=charged_amount,
+ )
+
+
+def transaction_item_created_by_user(order, staff_user, transaction_item_generator):
+ charged_amount = Decimal("10.0")
+ return transaction_item_generator(
+ order_id=order.pk,
+ checkout_id=None,
+ user=staff_user,
+ app=None,
+ charged_value=charged_amount,
)
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index d3386db98a..467960516b 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -531,6 +531,10 @@ class WebhookEventSyncType:
CHECKOUT_CALCULATE_TAXES = "checkout_calculate_taxes"
ORDER_CALCULATE_TAXES = "order_calculate_taxes"
+ TRANSACTION_CHARGE_REQUESTED = "transaction_charge_requested"
+ TRANSACTION_REFUND_REQUESTED = "transaction_refund_requested"
+ TRANSACTION_CANCELATION_REQUESTED = "transaction_cancelation_requested"
+
SHIPPING_LIST_METHODS_FOR_CHECKOUT = "shipping_list_methods_for_checkout"
CHECKOUT_FILTER_SHIPPING_METHODS = "checkout_filter_shipping_methods"
ORDER_FILTER_SHIPPING_METHODS = "order_filter_shipping_methods"
@@ -543,6 +547,9 @@ class WebhookEventSyncType:
PAYMENT_PROCESS: "Process payment",
PAYMENT_REFUND: "Refund payment",
PAYMENT_VOID: "Void payment",
+ TRANSACTION_CHARGE_REQUESTED: "Transaction charge requested",
+ TRANSACTION_CANCELATION_REQUESTED: "Transaction cancelation requested",
+ TRANSACTION_REFUND_REQUESTED: "Transaction refund requested",
CHECKOUT_CALCULATE_TAXES: "Checkout calculate taxes",
ORDER_CALCULATE_TAXES: "Order calculate taxes",
SHIPPING_LIST_METHODS_FOR_CHECKOUT: "Shipping list methods for checkout",
@@ -558,6 +565,12 @@ class WebhookEventSyncType:
(PAYMENT_PROCESS, DISPLAY_LABELS[PAYMENT_PROCESS]),
(PAYMENT_REFUND, DISPLAY_LABELS[PAYMENT_REFUND]),
(PAYMENT_VOID, DISPLAY_LABELS[PAYMENT_VOID]),
+ (TRANSACTION_CHARGE_REQUESTED, DISPLAY_LABELS[TRANSACTION_CHARGE_REQUESTED]),
+ (TRANSACTION_REFUND_REQUESTED, DISPLAY_LABELS[TRANSACTION_REFUND_REQUESTED]),
+ (
+ TRANSACTION_CANCELATION_REQUESTED,
+ DISPLAY_LABELS[TRANSACTION_CANCELATION_REQUESTED],
+ ),
(CHECKOUT_CALCULATE_TAXES, DISPLAY_LABELS[CHECKOUT_CALCULATE_TAXES]),
(ORDER_CALCULATE_TAXES, DISPLAY_LABELS[ORDER_CALCULATE_TAXES]),
(
@@ -591,6 +604,9 @@ class WebhookEventSyncType:
PAYMENT_PROCESS: PaymentPermissions.HANDLE_PAYMENTS,
PAYMENT_REFUND: PaymentPermissions.HANDLE_PAYMENTS,
PAYMENT_VOID: PaymentPermissions.HANDLE_PAYMENTS,
+ TRANSACTION_REFUND_REQUESTED: PaymentPermissions.HANDLE_PAYMENTS,
+ TRANSACTION_CANCELATION_REQUESTED: PaymentPermissions.HANDLE_PAYMENTS,
+ TRANSACTION_CHARGE_REQUESTED: PaymentPermissions.HANDLE_PAYMENTS,
CHECKOUT_CALCULATE_TAXES: CheckoutPermissions.HANDLE_TAXES,
ORDER_CALCULATE_TAXES: CheckoutPermissions.HANDLE_TAXES,
SHIPPING_LIST_METHODS_FOR_CHECKOUT: ShippingPermissions.MANAGE_SHIPPING,
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 865b5f09eb..20cba22e3f 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -1462,8 +1462,11 @@ def generate_transaction_action_request_payload(
},
"transaction": {
"status": transaction.status,
- "type": transaction.type,
- "reference": transaction.reference,
+ "type": transaction.name,
+ "name": transaction.name,
+ "message": transaction.message,
+ "reference": transaction.psp_reference,
+ "psp_reference": transaction.psp_reference,
"available_actions": transaction.available_actions,
"currency": transaction.currency,
"charged_value": quantize_price(
@@ -1476,7 +1479,10 @@ def generate_transaction_action_request_payload(
transaction.refunded_value, transaction.currency
),
"voided_value": quantize_price(
- transaction.voided_value, transaction.currency
+ transaction.canceled_value, transaction.currency
+ ),
+ "canceled_value": quantize_price(
+ transaction.canceled_value, transaction.currency
),
"order_id": graphql_order_id,
"checkout_id": graphql_checkout_id,
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 53075ab170..620549a292 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -27,7 +27,7 @@ from ...order import FulfillmentLineData, OrderOrigin
from ...order.actions import fulfill_order_lines
from ...order.fetch import OrderLineInfo
from ...order.models import Order
-from ...payment import TransactionAction
+from ...payment import TransactionAction, TransactionEventType
from ...payment.interface import RefundData, TransactionActionData, TransactionData
from ...payment.models import TransactionItem
from ...plugins.manager import get_plugins_manager
@@ -1223,16 +1223,20 @@ def test_generate_payment_with_transactions_payload(dummy_webhook_app_payment_da
@freeze_time()
def test_generate_transaction_item_metadata_updated_payload(
- transaction_item, customer_user
+ transaction_item_created_by_user, customer_user
):
# when
payload = json.loads(
- generate_metadata_updated_payload(transaction_item, customer_user)
+ generate_metadata_updated_payload(
+ transaction_item_created_by_user, customer_user
+ )
)[0]
# then
assert payload == {
- "id": graphene.Node.to_global_id("TransactionItem", transaction_item.id),
+ "id": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_user.id
+ ),
"meta": generate_meta(requestor_data=generate_requestor(customer_user)),
}
@@ -2141,13 +2145,17 @@ def test_generate_transaction_action_request_payload_for_order(
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["capture", "void"],
currency="USD",
order_id=order.pk,
authorized_value=Decimal("10"),
)
+ requested_event = transaction.events.create(
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
# when
payload = json.loads(
@@ -2156,6 +2164,8 @@ def test_generate_transaction_action_request_payload_for_order(
transaction=transaction,
action_type=action_type,
action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
),
requestor=requestor,
)
@@ -2172,8 +2182,11 @@ def test_generate_transaction_action_request_payload_for_order(
},
"transaction": {
"status": transaction.status,
- "type": transaction.type,
- "reference": transaction.reference,
+ "type": transaction.name,
+ "name": transaction.name,
+ "message": transaction.message,
+ "reference": transaction.psp_reference,
+ "psp_reference": transaction.psp_reference,
"available_actions": transaction.available_actions,
"currency": currency,
"charged_value": str(quantize_price(transaction.charged_value, currency)),
@@ -2181,7 +2194,8 @@ def test_generate_transaction_action_request_payload_for_order(
quantize_price(transaction.authorized_value, currency)
),
"refunded_value": str(quantize_price(transaction.refunded_value, currency)),
- "voided_value": str(quantize_price(transaction.voided_value, currency)),
+ "voided_value": str(quantize_price(transaction.canceled_value, currency)),
+ "canceled_value": str(quantize_price(transaction.canceled_value, currency)),
"order_id": graphene.Node.to_global_id("Order", order.pk),
"checkout_id": None,
"created_at": parse_django_datetime(transaction.created_at),
@@ -2198,16 +2212,24 @@ def test_generate_transaction_action_request_payload_for_order(
@pytest.mark.parametrize(
- "action_type, action_value",
+ "action_type, request_type, action_value",
[
- (TransactionAction.CHARGE, Decimal("5.000")),
- (TransactionAction.REFUND, Decimal("9.000")),
- (TransactionAction.VOID, None),
+ (
+ TransactionAction.CHARGE,
+ TransactionEventType.CHARGE_REQUEST,
+ Decimal("5.000"),
+ ),
+ (
+ TransactionAction.REFUND,
+ TransactionEventType.REFUND_REQUEST,
+ Decimal("9.000"),
+ ),
+ (TransactionAction.VOID, TransactionEventType.CANCEL_REQUEST, None),
],
)
@freeze_time("1914-06-28 10:50")
def test_generate_transaction_action_request_payload_for_checkout(
- action_type, action_value, checkout, app, rf
+ action_type, request_type, action_value, checkout, app, rf
):
# given
request = rf.request()
@@ -2217,13 +2239,17 @@ def test_generate_transaction_action_request_payload_for_checkout(
transaction = TransactionItem.objects.create(
status="Authorized",
- type="Credit card",
- reference="PSP ref",
+ name="Credit card",
+ psp_reference="PSP ref",
available_actions=["capture", "void"],
currency="USD",
checkout_id=checkout.pk,
authorized_value=Decimal("10"),
)
+ requested_event = transaction.events.create(
+ currency=transaction.currency,
+ type=request_type,
+ )
# when
payload = json.loads(
@@ -2232,6 +2258,8 @@ def test_generate_transaction_action_request_payload_for_checkout(
transaction=transaction,
action_type=action_type,
action_value=action_value,
+ event=requested_event,
+ transaction_app_owner=None,
),
requestor=requestor,
)
@@ -2248,8 +2276,11 @@ def test_generate_transaction_action_request_payload_for_checkout(
},
"transaction": {
"status": transaction.status,
- "type": transaction.type,
- "reference": transaction.reference,
+ "type": transaction.name,
+ "name": transaction.name,
+ "message": transaction.message,
+ "reference": transaction.psp_reference,
+ "psp_reference": transaction.psp_reference,
"available_actions": transaction.available_actions,
"currency": currency,
"charged_value": str(quantize_price(transaction.charged_value, currency)),
@@ -2257,7 +2288,8 @@ def test_generate_transaction_action_request_payload_for_checkout(
quantize_price(transaction.authorized_value, currency)
),
"refunded_value": str(quantize_price(transaction.refunded_value, currency)),
- "voided_value": str(quantize_price(transaction.voided_value, currency)),
+ "voided_value": str(quantize_price(transaction.canceled_value, currency)),
+ "canceled_value": str(quantize_price(transaction.canceled_value, currency)),
"order_id": None,
"checkout_id": graphene.Node.to_global_id("Checkout", checkout.pk),
"created_at": parse_django_datetime(transaction.created_at),
diff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.py
index 3151ff02c6..8c30a0cd1d 100644
--- a/saleor/webhook/utils.py
+++ b/saleor/webhook/utils.py
@@ -12,7 +12,9 @@ if TYPE_CHECKING:
def get_webhooks_for_event(
- event_type: str, webhooks: Optional["QuerySet[Webhook]"] = None
+ event_type: str,
+ webhooks: Optional["QuerySet[Webhook]"] = None,
+ apps_ids: Optional["list[int]"] = None,
) -> "QuerySet[Webhook]":
"""Get active webhooks from the database for an event."""
permissions = {}
@@ -26,7 +28,10 @@ def get_webhooks_for_event(
if webhooks is None:
webhooks = Webhook.objects.all()
- apps = App.objects.filter(is_active=True, **permissions)
+ app_kwargs: dict = {"is_active": True, **permissions}
+ if apps_ids:
+ app_kwargs["id__in"] = apps_ids
+ apps = App.objects.filter(**app_kwargs)
event_types = [event_type]
if event_type in WebhookEventAsyncType.ALL:
event_types.append(WebhookEventAsyncType.ANY)