Skip to content

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

Support for payment apps (#12179)

Maciej Korycinskif35e09021454
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3ef94e5a7f..54caded390 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -97,6 +97,15 @@ All notable, unreleased changes to this project will be documented in this file.
- `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).
+- Support for payment apps - #12179 by @korycins
+ - Add new mutations:
+ - `paymentGatewayInitialize` - Initialize the payment gateway to process a payment.
+ - `transactionInitialize` - Initiate payment processing.
+ - `transactionProcess` - Process the initialized payment.
+ - Add new synchronous webhooks:
+ - `PAYMENT_GATEWAY_INITIALIZE_SESSION` - Triggered when a customer requests the initialization of a payment gateway.
+ - `TRANSACTION_INITIALIZE_SESSION` - Triggered when a customer requests the initialization of a payment processing.
+ - `TRANSACTION_PROCESS_SESSION` - Triggered when a customer requests the processing of the initialized payment.
### Breaking changes
- **Feature preview breaking change**:
diff --git a/saleor/channel/__init__.py b/saleor/channel/__init__.py
index 67ebe25c9f..b362c98b53 100644
--- a/saleor/channel/__init__.py
+++ b/saleor/channel/__init__.py
@@ -34,3 +34,16 @@ class MarkAsPaidStrategy:
(TRANSACTION_FLOW, "Use transaction"),
(PAYMENT_FLOW, "Use payment"),
]
+
+
+class TransactionFlowStrategy:
+ """Determine the transaction flow strategy.
+
+ AUTHORIZATION - the processed transaction should be only authorized
+ CHARGE - the processed transaction should be charged.
+ """
+
+ AUTHORIZATION = "authorization"
+ CHARGE = "charge"
+
+ CHOICES = [(AUTHORIZATION, "Authorize"), (CHARGE, "Charge")]
diff --git a/saleor/channel/migrations/0010_channel_default_transaction_flow_strategy.py b/saleor/channel/migrations/0010_channel_default_transaction_flow_strategy.py
new file mode 100644
index 0000000000..06249fb921
--- /dev/null
+++ b/saleor/channel/migrations/0010_channel_default_transaction_flow_strategy.py
@@ -0,0 +1,29 @@
+# Generated by Django 3.2.18 on 2023-03-01 15:07
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("channel", "0009_channel_order_mark_as_paid_strategy"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="channel",
+ name="default_transaction_flow_strategy",
+ field=models.CharField(
+ choices=[("authorization", "Authorize"), ("charge", "Charge")],
+ default="charge",
+ max_length=255,
+ ),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE channel_channel
+ ALTER COLUMN default_transaction_flow_strategy
+ SET DEFAULT 'charge';
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/channel/models.py b/saleor/channel/models.py
index d05a9f2ebd..8d9d720297 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, MarkAsPaidStrategy
+from . import AllocationStrategy, MarkAsPaidStrategy, TransactionFlowStrategy
class Channel(models.Model):
@@ -23,16 +23,17 @@ class Channel(models.Model):
default=MarkAsPaidStrategy.PAYMENT_FLOW,
)
+ default_transaction_flow_strategy = models.CharField(
+ max_length=255,
+ choices=TransactionFlowStrategy.CHOICES,
+ default=TransactionFlowStrategy.CHARGE,
+ )
+
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/__init__.py b/saleor/checkout/__init__.py
index a2fd060bcd..a769bf24b6 100644
--- a/saleor/checkout/__init__.py
+++ b/saleor/checkout/__init__.py
@@ -11,3 +11,59 @@ class AddressType:
(BILLING, "Billing"),
(SHIPPING, "Shipping"),
]
+
+
+class CheckoutChargeStatus:
+ """Determine the current charge status for the checkout.
+
+ The checkout is considered overcharged when the sum of the transactionItem's charge
+ amounts exceeds the value of `checkout.total`.
+ If the sum of the transactionItem's charge amounts equals
+ `checkout.total`, we consider the checkout to be fully charged.
+ If the sum of the transactionItem's charge amounts covers a part of the
+ `checkout.total`, we treat the checkout as partially charged.
+
+
+ NONE - the funds are not charged.
+ PARTIAL - the funds that are charged don't cover the checkout's total
+ FULL - the funds that are charged fully cover the checkout's total
+ OVERCHARGED - the charged funds are bigger than checkout's total
+ """
+
+ NONE = "none"
+ PARTIAL = "partial"
+ FULL = "full"
+ OVERCHARGED = "overcharged"
+
+ CHOICES = [
+ (NONE, "The checkout is not charged"),
+ (PARTIAL, "The checkout is partially charged"),
+ (FULL, "The checkout is fully charged"),
+ (OVERCHARGED, "The checkout is overcharged"),
+ ]
+
+
+class CheckoutAuthorizeStatus:
+ """Determine a current authorize status for checkout.
+
+ We treat the checkout as fully authorized when the sum of authorized and charged
+ funds cover the checkout.total.
+ We treat the checkout as partially authorized when the sum of authorized and charged
+ funds covers only part of the checkout.total
+ We treat the checkout as not authorized when the sum of authorized and charged funds
+ is 0.
+
+ NONE - the funds are not authorized
+ PARTIAL - the cover funds don't cover fully the checkout's total
+ FULL - the cover funds covers the checkout's total
+ """
+
+ NONE = "none"
+ PARTIAL = "partial"
+ FULL = "full"
+
+ CHOICES = [
+ (NONE, "The checkout is not authorized"),
+ (PARTIAL, "The checkout is partially authorized"),
+ (FULL, "The checkout is fully authorized"),
+ ]
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
new file mode 100644
index 0000000000..b40de508c7
--- /dev/null
+++ b/saleor/checkout/actions.py
@@ -0,0 +1,37 @@
+from typing import Iterable, Optional, cast
+
+from ..core.utils.events import call_event
+from ..discount import DiscountInfo
+from ..payment.models import TransactionItem
+from ..plugins.manager import PluginsManager
+from . import CheckoutChargeStatus
+from .calculations import fetch_checkout_data
+from .fetch import fetch_checkout_info, fetch_checkout_lines
+from .models import Checkout
+
+
+def transaction_amounts_for_checkout_updated(
+ transaction: TransactionItem,
+ discounts: Optional[Iterable["DiscountInfo"]],
+ manager: "PluginsManager",
+):
+ if not transaction.checkout_id:
+ return
+ checkout = cast(Checkout, transaction.checkout)
+ lines, _ = fetch_checkout_lines(checkout)
+ discounts = discounts or []
+ checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)
+ previous_charge_status = checkout_info.checkout.charge_status
+ fetch_checkout_data(
+ checkout_info, manager, lines, discounts=discounts, force_status_update=True
+ )
+ previous_charge_status_is_fully_paid = previous_charge_status in [
+ CheckoutChargeStatus.FULL,
+ CheckoutChargeStatus.OVERCHARGED,
+ ]
+ current_status_is_fully_paid = checkout_info.checkout.charge_status in [
+ CheckoutChargeStatus.FULL,
+ CheckoutChargeStatus.OVERCHARGED,
+ ]
+ if not previous_charge_status_is_fully_paid and current_status_is_fully_paid:
+ call_event(manager.checkout_fully_paid, checkout_info.checkout)
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 88a5b0206c..7fbbaa9ca1 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -9,6 +9,7 @@ from ..checkout import base_calculations
from ..core.prices import quantize_price
from ..core.taxes import TaxData, zero_money, zero_taxed_money
from ..discount import DiscountInfo
+from ..payment.models import TransactionItem
from ..tax import TaxCalculationStrategy
from ..tax.calculations.checkout import update_checkout_prices_with_flat_rates
from ..tax.utils import (
@@ -17,6 +18,7 @@ from ..tax.utils import (
normalize_tax_rate_for_db,
)
from .models import Checkout
+from .payment_utils import update_checkout_payment_statuses
if TYPE_CHECKING:
from ..account.models import Address
@@ -37,7 +39,7 @@ def checkout_shipping_price(
It takes in account all plugins.
"""
currency = checkout_info.checkout.currency
- checkout_info, _ = fetch_checkout_prices_if_expired(
+ checkout_info, _ = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
@@ -59,7 +61,7 @@ def checkout_shipping_tax_rate(
It takes in account all plugins.
"""
- checkout_info, _ = fetch_checkout_prices_if_expired(
+ checkout_info, _ = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
@@ -82,7 +84,7 @@ def checkout_subtotal(
It takes in account all plugins.
"""
currency = checkout_info.checkout.currency
- checkout_info, _ = fetch_checkout_prices_if_expired(
+ checkout_info, _ = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
@@ -129,7 +131,7 @@ def checkout_total(
It takes in account all plugins.
"""
currency = checkout_info.checkout.currency
- checkout_info, _ = fetch_checkout_prices_if_expired(
+ checkout_info, _ = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
@@ -168,7 +170,7 @@ def checkout_line_total(
"""
currency = checkout_info.checkout.currency
address = checkout_info.shipping_address or checkout_info.billing_address
- _, lines = fetch_checkout_prices_if_expired(
+ _, lines = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
@@ -193,7 +195,7 @@ def checkout_line_unit_price(
"""
currency = checkout_info.checkout.currency
address = checkout_info.shipping_address or checkout_info.billing_address
- _, lines = fetch_checkout_prices_if_expired(
+ _, lines = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
@@ -218,7 +220,7 @@ def checkout_line_tax_rate(
It takes in account all plugins.
"""
address = checkout_info.shipping_address or checkout_info.billing_address
- _, lines = fetch_checkout_prices_if_expired(
+ _, lines = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
@@ -229,7 +231,7 @@ def checkout_line_tax_rate(
return checkout_line_info.line.tax_rate
-def fetch_checkout_prices_if_expired(
+def _fetch_checkout_prices_if_expired(
checkout_info: "CheckoutInfo",
manager: "PluginsManager",
lines: Iterable["CheckoutLineInfo"],
@@ -296,7 +298,6 @@ def fetch_checkout_prices_if_expired(
else:
# Calculate net prices without taxes.
_get_checkout_base_prices(checkout, checkout_info, lines, discounts)
-
checkout.price_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL
checkout.save(
update_fields=[
@@ -313,6 +314,7 @@ def fetch_checkout_prices_if_expired(
"discount_amount",
"discount_name",
"currency",
+ "last_change",
],
using=settings.DATABASE_CONNECTION_DEFAULT_NAME,
)
@@ -513,3 +515,38 @@ def _get_checkout_base_prices(
# Calculate checkout total
total = subtotal + shipping_price
checkout.total = quantize_price(TaxedMoney(net=total, gross=total), currency)
+
+
+def fetch_checkout_data(
+ checkout_info: "CheckoutInfo",
+ manager: "PluginsManager",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"] = None,
+ discounts: Optional[Iterable["DiscountInfo"]] = None,
+ force_update: bool = False,
+ checkout_transactions: Optional[Iterable["TransactionItem"]] = None,
+ force_status_update: bool = False,
+):
+ """Fetch checkout data.
+
+ This function refreshes prices if they have expired. If the checkout total has
+ changed as a result, it will update the payment statuses accordingly.
+ """
+ previous_total_gross = checkout_info.checkout.total.gross
+ checkout_info, lines = _fetch_checkout_prices_if_expired(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ force_update=force_update,
+ )
+ current_total_gross = checkout_info.checkout.total.gross
+ if current_total_gross != previous_total_gross or force_status_update:
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=current_total_gross,
+ checkout_transactions=checkout_transactions,
+ )
+
+ return checkout_info, lines
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index a264743663..fb762b84eb 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from decimal import Decimal
from typing import (
TYPE_CHECKING,
Any,
@@ -24,7 +25,7 @@ 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 import CheckoutAuthorizeStatus, calculations
from ..checkout.error_codes import CheckoutErrorCode
from ..core.exceptions import GiftCardNotApplicable, InsufficientStock
from ..core.postgres import FlatConcatSearchVector
@@ -44,11 +45,7 @@ from ..graphql.checkout.utils import (
prepare_insufficient_stock_checkout_validation_error,
)
from ..order import OrderOrigin, OrderStatus
-from ..order.actions import (
- mark_order_as_paid_with_payment,
- mark_order_as_paid_with_transaction,
- order_created,
-)
+from ..order.actions import mark_order_as_paid_with_payment, order_created
from ..order.fetch import OrderInfo, OrderLineInfo
from ..order.models import Order, OrderLine
from ..order.notifications import send_order_confirmation
@@ -77,9 +74,10 @@ from .base_calculations import (
calculate_undiscounted_base_line_total_price,
calculate_undiscounted_base_line_unit_price,
)
-from .calculations import fetch_checkout_prices_if_expired
+from .calculations import fetch_checkout_data
from .checkout_cleaner import (
_validate_gift_cards,
+ clean_billing_address,
clean_checkout_payment,
clean_checkout_shipping,
)
@@ -647,19 +645,9 @@ def _prepare_checkout(
discounts,
tracking_code,
redirect_url,
- payment,
):
- """Prepare checkout object to complete the checkout process."""
checkout = checkout_info.checkout
clean_checkout_shipping(checkout_info, lines, CheckoutErrorCode)
- clean_checkout_payment(
- manager,
- checkout_info,
- lines,
- discounts,
- CheckoutErrorCode,
- last_payment=payment,
- )
if not checkout_info.channel.is_active:
raise ValidationError(
{
@@ -691,6 +679,64 @@ def _prepare_checkout(
checkout.save(update_fields=to_update)
+def _prepare_checkout_with_transactions(
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ discounts: Iterable["DiscountInfo"],
+ tracking_code: Optional[str],
+ redirect_url: Optional[str],
+):
+ """Prepare checkout object with transactions to complete the checkout process."""
+ clean_billing_address(checkout_info, CheckoutErrorCode)
+ if checkout_info.checkout.authorize_status != CheckoutAuthorizeStatus.FULL:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "The authorized amount doesn't cover the checkout's total amount.",
+ code=CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.value,
+ )
+ }
+ )
+
+ _prepare_checkout(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ discounts=discounts,
+ tracking_code=tracking_code,
+ redirect_url=redirect_url,
+ )
+
+
+def _prepare_checkout_with_payment(
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ discounts: Iterable["DiscountInfo"],
+ tracking_code: Optional[str],
+ redirect_url: Optional[str],
+ payment: Optional[Payment],
+):
+ """Prepare checkout object with payment to complete the checkout process."""
+ clean_checkout_payment(
+ manager,
+ checkout_info,
+ lines,
+ discounts,
+ CheckoutErrorCode,
+ last_payment=payment,
+ )
+ _prepare_checkout(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ discounts=discounts,
+ tracking_code=tracking_code,
+ redirect_url=redirect_url,
+ )
+
+
def _get_order_data(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
@@ -784,13 +830,13 @@ def complete_checkout_pre_payment_part(
if site_settings is None:
site_settings = Site.objects.get_current().settings
- fetch_checkout_prices_if_expired(checkout_info, manager, lines, discounts=discounts)
+ fetch_checkout_data(checkout_info, manager, lines, discounts=discounts)
checkout = checkout_info.checkout
channel_slug = checkout_info.channel.slug
payment = checkout.get_last_active_payment()
try:
- _prepare_checkout(
+ _prepare_checkout_with_payment(
manager=manager,
checkout_info=checkout_info,
lines=lines,
@@ -886,8 +932,6 @@ def complete_checkout_post_payment_part(
== 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
@@ -920,7 +964,7 @@ def _increase_voucher_usage(checkout_info: "CheckoutInfo"):
def _create_order_lines_from_checkout_lines(
checkout_info: CheckoutInfo,
lines: List[CheckoutLineInfo],
- discounts: List["DiscountInfo"],
+ discounts: Iterable["DiscountInfo"],
manager: "PluginsManager",
order_pk: Union[str, UUID],
prices_entered_with_tax: bool,
@@ -992,7 +1036,7 @@ def _post_create_order_actions(
checkout_info: "CheckoutInfo",
order_lines_info: List["OrderLineInfo"],
manager: "PluginsManager",
- user: User,
+ user: Optional[User],
app: Optional["App"],
site_settings: "SiteSettings",
):
@@ -1025,9 +1069,9 @@ def _post_create_order_actions(
def _create_order_from_checkout(
checkout_info: CheckoutInfo,
checkout_lines_info: List[CheckoutLineInfo],
- discounts: List["DiscountInfo"],
+ discounts: Iterable["DiscountInfo"],
manager: "PluginsManager",
- user: User,
+ user: Optional[User],
app: Optional["App"],
tracking_code: Optional[str] = None,
metadata_list: Optional[List] = None,
@@ -1051,7 +1095,6 @@ def _create_order_from_checkout(
address=address,
discounts=discounts,
)
- undiscounted_total = taxed_total + checkout_info.checkout.discount
# voucher
voucher = checkout_info.voucher
@@ -1099,7 +1142,6 @@ def _create_order_from_checkout(
language_code=checkout_info.checkout.language_code,
tracking_client_id=tracking_code or "",
total=taxed_total, # money field not supported by mypy_django_plugin
- undiscounted_total=undiscounted_total, # money field not supported by mypy_django_plugin # noqa: E501
shipping_tax_rate=shipping_tax_rate,
voucher=voucher,
checkout_token=str(checkout_info.checkout.token),
@@ -1133,6 +1175,22 @@ def _create_order_from_checkout(
prices_entered_with_tax=prices_entered_with_tax,
)
+ # update undiscounted order total
+ undiscounted_total = (
+ sum(
+ [line.line.undiscounted_total_price for line in order_lines_info],
+ start=zero_taxed_money(taxed_total.currency),
+ )
+ + shipping_total
+ )
+ order.undiscounted_total = undiscounted_total
+ order.save(
+ update_fields=[
+ "undiscounted_total_net_amount",
+ "undiscounted_total_gross_amount",
+ ]
+ )
+
# allocations
_handle_allocations_of_order_lines(
checkout_info=checkout_info,
@@ -1182,11 +1240,11 @@ def _create_order_from_checkout(
def create_order_from_checkout(
checkout_info: CheckoutInfo,
checkout_lines: Iterable["CheckoutLineInfo"],
- discounts: List["DiscountInfo"],
+ discounts: Iterable["DiscountInfo"],
manager: "PluginsManager",
- user: User,
+ user: Optional["User"],
app: Optional["App"],
- tracking_code: str,
+ tracking_code: Optional[str],
delete_checkout: bool = True,
metadata_list: Optional[List] = None,
private_metadata_list: Optional[List] = None,
@@ -1242,6 +1300,100 @@ def create_order_from_checkout(
def complete_checkout(
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ payment_data: Dict[Any, Any],
+ store_source: bool,
+ discounts: Iterable["DiscountInfo"],
+ user: Optional["User"],
+ app: Optional["App"],
+ site_settings: Optional["SiteSettings"] = None,
+ tracking_code: Optional[str] = None,
+ redirect_url: Optional[str] = None,
+ metadata_list: Optional[List] = None,
+ private_metadata_list: Optional[List] = None,
+) -> Tuple[Optional[Order], bool, dict]:
+ transactions = checkout_info.checkout.payment_transactions.all()
+ fetch_checkout_data(checkout_info, manager, lines, discounts=discounts)
+
+ # When checkout is zero, we don't need any transaction to cover the checkout total.
+ # We check if checkout is zero, and we also check what flow for marking an order as
+ # paid is used. In case when we have TRANSACTION_FLOW we use transaction flow to
+ # finalize the checkout.
+ checkout_is_zero = checkout_info.checkout.total.gross.amount == Decimal(0)
+ if transactions or (
+ checkout_is_zero
+ and checkout_info.channel.order_mark_as_paid_strategy
+ == MarkAsPaidStrategy.TRANSACTION_FLOW
+ ):
+ order = complete_checkout_with_transaction(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ discounts=discounts,
+ user=user,
+ app=app,
+ tracking_code=tracking_code,
+ redirect_url=redirect_url,
+ metadata_list=metadata_list,
+ private_metadata_list=private_metadata_list,
+ )
+ return order, False, {}
+
+ return complete_checkout_with_payment(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ payment_data=payment_data,
+ store_source=store_source,
+ discounts=discounts,
+ user=user,
+ app=app,
+ site_settings=site_settings,
+ tracking_code=tracking_code,
+ redirect_url=redirect_url,
+ metadata_list=metadata_list,
+ private_metadata_list=private_metadata_list,
+ )
+
+
+def complete_checkout_with_transaction(
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ discounts: Iterable["DiscountInfo"],
+ user: Optional["User"],
+ app: Optional["App"],
+ tracking_code: Optional[str] = None,
+ redirect_url: Optional[str] = None,
+ metadata_list: Optional[List] = None,
+ private_metadata_list: Optional[List] = None,
+) -> Optional[Order]:
+ _prepare_checkout_with_transactions(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ discounts=discounts,
+ tracking_code=tracking_code,
+ redirect_url=redirect_url,
+ )
+
+ return create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ discounts=discounts,
+ manager=manager,
+ user=user,
+ app=app,
+ tracking_code=tracking_code,
+ delete_checkout=True,
+ metadata_list=metadata_list,
+ private_metadata_list=private_metadata_list,
+ )
+
+
+def complete_checkout_with_payment(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
diff --git a/saleor/checkout/migrations/0058_auto_20230313_1602.py b/saleor/checkout/migrations/0058_auto_20230313_1602.py
new file mode 100644
index 0000000000..adee54bc9d
--- /dev/null
+++ b/saleor/checkout/migrations/0058_auto_20230313_1602.py
@@ -0,0 +1,57 @@
+# Generated by Django 3.2.18 on 2023-03-13 16:02
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0057_remove_metadata_from_checkout_model_state"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="authorize_status",
+ field=models.CharField(
+ choices=[
+ ("none", "The checkout is not authorized"),
+ ("partial", "The checkout is partially authorized"),
+ ("full", "The checkout is fully authorized"),
+ ],
+ db_index=True,
+ default="none",
+ max_length=32,
+ ),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE checkout_checkout
+ ALTER COLUMN authorize_status
+ SET DEFAULT 'none';
+ """,
+ migrations.RunSQL.noop,
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="charge_status",
+ field=models.CharField(
+ choices=[
+ ("none", "The checkout is not charged"),
+ ("partial", "The checkout is partially charged"),
+ ("full", "The checkout is fully charged"),
+ ("overcharged", "The checkout is overcharged"),
+ ],
+ db_index=True,
+ default="none",
+ max_length=32,
+ ),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE checkout_checkout
+ ALTER COLUMN charge_status
+ SET DEFAULT 'none';
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 024615bd27..2959044679 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -21,6 +21,7 @@ from ..core.weight import zero_weight
from ..giftcard.models import GiftCard
from ..permission.enums import CheckoutPermissions
from ..shipping.models import ShippingMethod
+from . import CheckoutAuthorizeStatus, CheckoutChargeStatus
if TYPE_CHECKING:
from django_measurement import Weight
@@ -137,6 +138,20 @@ class Checkout(models.Model):
max_digits=5, decimal_places=4, default=Decimal("0.0")
)
+ authorize_status = models.CharField(
+ max_length=32,
+ default=CheckoutAuthorizeStatus.NONE,
+ choices=CheckoutAuthorizeStatus.CHOICES,
+ db_index=True,
+ )
+
+ charge_status = models.CharField(
+ max_length=32,
+ default=CheckoutChargeStatus.NONE,
+ choices=CheckoutChargeStatus.CHOICES,
+ db_index=True,
+ )
+
price_expiration = models.DateTimeField(default=timezone.now)
discount_amount = models.DecimalField(
diff --git a/saleor/checkout/payment_utils.py b/saleor/checkout/payment_utils.py
new file mode 100644
index 0000000000..6ee5b86612
--- /dev/null
+++ b/saleor/checkout/payment_utils.py
@@ -0,0 +1,82 @@
+"""Checkout-related utility functions."""
+from typing import TYPE_CHECKING, Iterable, Optional, Tuple
+
+from prices import Money
+
+from ..core.taxes import zero_money
+from . import CheckoutAuthorizeStatus, CheckoutChargeStatus
+from .models import Checkout
+
+if TYPE_CHECKING:
+ from ..payment.models import TransactionItem
+
+
+def _update_charge_status(
+ checkout: Checkout, checkout_total_gross: Money, total_charged: Money
+):
+ zero_money_amount = zero_money(checkout.currency)
+ total_charged = max(zero_money_amount, total_charged)
+
+ if total_charged <= zero_money_amount and checkout_total_gross != zero_money_amount:
+ checkout.charge_status = CheckoutChargeStatus.NONE
+ elif total_charged < checkout_total_gross:
+ checkout.charge_status = CheckoutChargeStatus.PARTIAL
+ elif total_charged == checkout_total_gross:
+ checkout.charge_status = CheckoutChargeStatus.FULL
+ elif total_charged > checkout_total_gross:
+ checkout.charge_status = CheckoutChargeStatus.OVERCHARGED
+ else:
+ checkout.charge_status = CheckoutChargeStatus.NONE
+
+
+def _update_authorize_status(
+ checkout: Checkout,
+ checkout_total_gross: Money,
+ total_authorized: Money,
+ total_charged: Money,
+):
+ total_covered = total_authorized + total_charged
+ zero_money_amount = zero_money(checkout.currency)
+ if total_covered == zero_money_amount and checkout_total_gross != zero_money_amount:
+ checkout.authorize_status = CheckoutAuthorizeStatus.NONE
+ elif total_covered >= checkout_total_gross:
+ checkout.authorize_status = CheckoutAuthorizeStatus.FULL
+ elif total_covered < checkout_total_gross and total_covered > zero_money_amount:
+ checkout.authorize_status = CheckoutAuthorizeStatus.PARTIAL
+ else:
+ checkout.authorize_status = CheckoutAuthorizeStatus.NONE
+
+
+def _get_payment_amount_for_checkout(
+ checkout_transactions: Iterable["TransactionItem"], currency: str
+) -> Tuple[Money, Money]:
+ total_charged_amount = zero_money(currency)
+ total_authorized_amount = zero_money(currency)
+ for transaction in checkout_transactions:
+ total_authorized_amount += transaction.amount_authorized
+ total_authorized_amount += transaction.amount_authorize_pending
+
+ total_charged_amount += transaction.amount_charged
+ total_charged_amount += transaction.amount_charge_pending
+ return total_authorized_amount, total_charged_amount
+
+
+def update_checkout_payment_statuses(
+ checkout: Checkout,
+ checkout_total_gross: Money,
+ checkout_transactions: Optional[Iterable["TransactionItem"]] = None,
+ save: bool = True,
+):
+ if checkout_transactions is None:
+ checkout_transactions = checkout.payment_transactions.all()
+ total_authorized_amount, total_charged_amount = _get_payment_amount_for_checkout(
+ checkout_transactions, checkout.currency
+ )
+ _update_authorize_status(
+ checkout, checkout_total_gross, total_authorized_amount, total_charged_amount
+ )
+ _update_charge_status(checkout, checkout_total_gross, total_charged_amount)
+ if save:
+ checkout.save(
+ update_fields=["authorize_status", "charge_status", "last_change"]
+ )
diff --git a/saleor/checkout/tests/test_actions.py b/saleor/checkout/tests/test_actions.py
new file mode 100644
index 0000000000..0a64b7552d
--- /dev/null
+++ b/saleor/checkout/tests/test_actions.py
@@ -0,0 +1,70 @@
+from unittest.mock import patch
+
+from ...tests.utils import flush_post_commit_hooks
+from .. import CheckoutAuthorizeStatus, CheckoutChargeStatus
+from ..actions import transaction_amounts_for_checkout_updated
+from ..calculations import fetch_checkout_data
+from ..fetch import fetch_checkout_info, fetch_checkout_lines
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_amounts_for_checkout_updated_fully_paid(
+ mocked_fully_paid, checkout_with_items, transaction_item_generator, plugins_manager
+):
+ # given
+ checkout = checkout_with_items
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
+ )
+
+ # when
+ transaction_amounts_for_checkout_updated(
+ transaction, discounts=[], manager=plugins_manager
+ )
+
+ # then
+ flush_post_commit_hooks()
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_fully_paid.assert_called_with(checkout)
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_amounts_for_checkout_updated_with_already_fully_paid(
+ mocked_fully_paid, checkout_with_items, transaction_item_generator, plugins_manager
+):
+ # given
+ checkout = checkout_with_items
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
+ )
+
+ fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[], force_status_update=True
+ )
+
+ second_transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
+ )
+ # when
+ transaction_amounts_for_checkout_updated(
+ second_transaction, discounts=[], manager=plugins_manager
+ )
+
+ # then
+ flush_post_commit_hooks()
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.OVERCHARGED
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ assert not mocked_fully_paid.called
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index 141ca86506..f132c75671 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -20,7 +20,7 @@ from ..base_calculations import (
from ..calculations import (
_apply_tax_data,
_get_checkout_base_prices,
- fetch_checkout_prices_if_expired,
+ fetch_checkout_data,
)
from ..fetch import CheckoutLineInfo, fetch_checkout_info, fetch_checkout_lines
@@ -129,7 +129,7 @@ def get_taxed_money(
@freeze_time("2020-12-12 12:00:00")
@patch("saleor.checkout.calculations._apply_tax_data")
-def test_fetch_checkout_prices_if_expired_plugins(
+def test_fetch_checkout_data_plugins(
_mocked_from_app,
plugins_manager,
fetch_kwargs,
@@ -173,7 +173,7 @@ def test_fetch_checkout_prices_if_expired_plugins(
)
# when
- fetch_checkout_prices_if_expired(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs)
# then
checkout_with_items.refresh_from_db()
@@ -193,7 +193,7 @@ def test_fetch_checkout_prices_if_expired_plugins(
wraps=update_checkout_prices_with_flat_rates,
)
@pytest.mark.parametrize("prices_entered_with_tax", [True, False])
-def test_fetch_checkout_prices_if_expired_flat_rates(
+def test_fetch_checkout_data_flat_rates(
mocked_update_checkout_prices_with_flat_rates,
checkout_with_items_and_shipping,
fetch_kwargs,
@@ -218,7 +218,7 @@ def test_fetch_checkout_prices_if_expired_flat_rates(
)
# when
- fetch_checkout_prices_if_expired(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs)
checkout.refresh_from_db()
line = checkout.lines.first()
@@ -232,7 +232,7 @@ def test_fetch_checkout_prices_if_expired_flat_rates(
"saleor.checkout.calculations.update_checkout_prices_with_flat_rates",
wraps=update_checkout_prices_with_flat_rates,
)
-def test_fetch_checkout_prices_if_expired_flat_rates_and_no_tax_calc_strategy(
+def test_fetch_checkout_data_flat_rates_and_no_tax_calc_strategy(
mocked_update_checkout_prices_with_flat_rates,
checkout_with_items_and_shipping,
fetch_kwargs,
@@ -256,7 +256,7 @@ def test_fetch_checkout_prices_if_expired_flat_rates_and_no_tax_calc_strategy(
)
# when
- fetch_checkout_prices_if_expired(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs)
checkout.refresh_from_db()
line = checkout.lines.first()
@@ -339,7 +339,7 @@ def test_get_checkout_base_prices_no_charge_taxes_with_voucher(
@freeze_time("2020-12-12 12:00:00")
-def test_fetch_checkout_prices_if_expired_webhooks_success(
+def test_fetch_checkout_data_webhooks_success(
plugins_manager,
fetch_kwargs,
checkout_with_items,
@@ -352,7 +352,7 @@ def test_fetch_checkout_prices_if_expired_webhooks_success(
plugins_manager.get_taxes_for_checkout = Mock(return_value=tax_data)
# when
- fetch_checkout_prices_if_expired(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs)
# then
checkout_with_items.refresh_from_db()
@@ -407,7 +407,7 @@ def test_fetch_checkout_prices_when_tax_exemption_and_include_taxes_in_prices(
}
# when
- fetch_checkout_prices_if_expired(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs)
checkout.refresh_from_db()
# then
@@ -467,7 +467,7 @@ def test_fetch_checkout_prices_when_tax_exemption_and_not_include_taxes_in_price
}
# when
- fetch_checkout_prices_if_expired(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs)
checkout.refresh_from_db()
# then
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 6c84a85210..1f1e89e8a1 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -32,6 +32,7 @@ from ..complete_checkout import (
complete_checkout,
)
from ..fetch import fetch_checkout_info, fetch_checkout_lines
+from ..payment_utils import update_checkout_payment_statuses
from ..utils import add_variant_to_checkout
@@ -1205,6 +1206,8 @@ def test_complete_checkout_0_total_with_transaction_for_mark_as_paid(
checkout.billing_address = customer_user.default_billing_address
checkout.save()
+ update_checkout_payment_statuses(checkout, zero_money(checkout.currency))
+
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
@@ -1225,21 +1228,13 @@ def test_complete_checkout_0_total_with_transaction_for_mark_as_paid(
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,
@@ -1250,7 +1245,7 @@ def test_complete_checkout_0_total_captured_payment_creates_expected_events(
checkout_user = customer_user
channel = checkout.channel
- channel.order_mark_as_paid_strategy = mark_as_paid_strategy
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.PAYMENT_FLOW
channel.save(update_fields=["order_mark_as_paid_strategy"])
# Ensure not events are existing prior
@@ -1671,7 +1666,7 @@ def test_complete_checkout_invalid_shipping_method(
app,
payment_txn_to_confirm,
):
- """Ensure that when an error in _prepare_checkout method is raised
+ """Ensure that when an error in _prepare_checkout_with_payment method is raised
the method for refund or void is called."""
# given
checkout = checkout_ready_to_complete
@@ -1724,3 +1719,159 @@ def test_complete_checkout_invalid_shipping_method(
mocked_payment_refund_or_void.called_once_with(
payment, manager, channel_slug=checkout.channel.slug
)
+
+
[email protected]("saleor.checkout.complete_checkout.complete_checkout_with_transaction")
+def test_checkout_complete_pick_transaction_flow(
+ mocked_flow,
+ order,
+ checkout_ready_to_complete,
+ customer_user,
+ transaction_item_generator,
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.user = customer_user
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.shipping_address = customer_user.default_billing_address
+ checkout.tracking_code = ""
+ checkout.redirect_url = "https://www.example.com"
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ transaction_item_generator(checkout_id=checkout.pk)
+ mocked_flow.return_value = order, False, {}
+
+ # when
+ order, action_required, _ = complete_checkout(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines,
+ payment_data={},
+ store_source=False,
+ discounts=None,
+ user=customer_user,
+ app=None,
+ )
+
+ # then
+ mocked_flow.assert_called_once_with(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ discounts=None,
+ user=customer_user,
+ app=None,
+ tracking_code=None,
+ redirect_url=None,
+ metadata_list=None,
+ private_metadata_list=None,
+ )
+
+
[email protected]("saleor.checkout.complete_checkout.complete_checkout_with_transaction")
+def test_checkout_complete_pick_transaction_flow_when_checkout_total_zero(
+ mocked_flow, order, checkout_with_item_total_0, customer_user, channel_USD
+):
+ # given
+ checkout = checkout_with_item_total_0
+ checkout.user = customer_user
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.shipping_address = customer_user.default_billing_address
+ checkout.tracking_code = ""
+ checkout.redirect_url = "https://www.example.com"
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ checkout.total = zero_taxed_money(checkout.currency)
+ update_checkout_payment_statuses(
+ checkout=checkout,
+ checkout_total_gross=checkout.total,
+ )
+
+ mocked_flow.return_value = order, False, {}
+ channel_USD.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel_USD.save()
+
+ # when
+ order, action_required, _ = complete_checkout(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines,
+ payment_data={},
+ store_source=False,
+ discounts=None,
+ user=customer_user,
+ app=None,
+ )
+
+ # then
+ mocked_flow.assert_called_once_with(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ discounts=None,
+ user=customer_user,
+ app=None,
+ tracking_code=None,
+ redirect_url=None,
+ metadata_list=None,
+ private_metadata_list=None,
+ )
+
+
[email protected]("saleor.checkout.complete_checkout.complete_checkout_with_payment")
+def test_checkout_complete_pick_payment_flow(
+ mocked_flow, order, checkout_ready_to_complete, customer_user
+):
+ # given
+ checkout = checkout_ready_to_complete
+ checkout.user = customer_user
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.shipping_address = customer_user.default_billing_address
+ checkout.tracking_code = ""
+ checkout.redirect_url = "https://www.example.com"
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ mocked_flow.return_value = order, False, {}
+
+ payment = Payment.objects.create(
+ gateway="mirumee.payments.dummy", is_active=True, checkout=checkout
+ )
+ payment.to_confirm = True
+ payment.save()
+
+ # when
+ order, action_required, _ = complete_checkout(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines,
+ payment_data={},
+ store_source=False,
+ discounts=None,
+ user=customer_user,
+ app=None,
+ )
+
+ # then
+ mocked_flow.assert_called_once_with(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ payment_data={},
+ store_source=False,
+ discounts=None,
+ user=customer_user,
+ app=None,
+ site_settings=None,
+ tracking_code=None,
+ redirect_url=None,
+ metadata_list=None,
+ private_metadata_list=None,
+ )
diff --git a/saleor/graphql/channel/enums.py b/saleor/graphql/channel/enums.py
index a28b07303d..fde07ac401 100644
--- a/saleor/graphql/channel/enums.py
+++ b/saleor/graphql/channel/enums.py
@@ -1,5 +1,9 @@
-from ...channel import AllocationStrategy, MarkAsPaidStrategy
-from ..core.doc_category import DOC_CATEGORY_CHANNELS, DOC_CATEGORY_PRODUCTS
+from ...channel import AllocationStrategy, MarkAsPaidStrategy, TransactionFlowStrategy
+from ..core.doc_category import (
+ DOC_CATEGORY_CHANNELS,
+ DOC_CATEGORY_PAYMENTS,
+ DOC_CATEGORY_PRODUCTS,
+)
from ..core.enums import to_enum
AllocationStrategyEnum = to_enum(
@@ -15,3 +19,10 @@ MarkAsPaidStrategyEnum = to_enum(
description=MarkAsPaidStrategy.__doc__,
)
MarkAsPaidStrategyEnum.doc_category = DOC_CATEGORY_CHANNELS
+
+TransactionFlowStrategyEnum = to_enum(
+ TransactionFlowStrategy,
+ type_name="TransactionFlowStrategyEnum",
+ description=TransactionFlowStrategy.__doc__,
+)
+TransactionFlowStrategyEnum.doc_category = DOC_CATEGORY_PAYMENTS
diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.py
index ce06e25cc7..4b198c5537 100644
--- a/saleor/graphql/channel/mutations/channel_create.py
+++ b/saleor/graphql/channel/mutations/channel_create.py
@@ -23,7 +23,11 @@ from ...core.doc_category import (
from ...core.mutations import ModelMutation
from ...core.types import BaseInputObjectType, ChannelError, NonNullList
from ...plugins.dataloaders import get_plugin_manager_promise
-from ..enums import AllocationStrategyEnum, MarkAsPaidStrategyEnum
+from ..enums import (
+ AllocationStrategyEnum,
+ MarkAsPaidStrategyEnum,
+ TransactionFlowStrategyEnum,
+)
from ..types import Channel
@@ -64,6 +68,14 @@ class OrderSettingsInput(BaseInputObjectType):
+ PREVIEW_FEATURE
),
)
+ default_transaction_flow_strategy = TransactionFlowStrategyEnum(
+ required=False,
+ description=(
+ "Determine the transaction flow strategy to be used. "
+ "Include the selected option in the payload sent to the payment app, as a "
+ "requested action for the transaction." + ADDED_IN_313 + PREVIEW_FEATURE
+ ),
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
@@ -163,6 +175,13 @@ class ChannelCreate(ModelMutation):
if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):
cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategy
+ if default_transaction_strategy := order_settings.get(
+ "default_transaction_flow_strategy"
+ ):
+ cleaned_input[
+ "default_transaction_flow_strategy"
+ ] = default_transaction_strategy
+
return cleaned_input
@classmethod
diff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.py
index 1e66fd29bc..5d97f5da36 100644
--- a/saleor/graphql/channel/mutations/channel_update.py
+++ b/saleor/graphql/channel/mutations/channel_update.py
@@ -112,6 +112,13 @@ class ChannelUpdate(ModelMutation):
if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):
cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategy
+
+ if default_transaction_strategy := order_settings.get(
+ "default_transaction_flow_strategy"
+ ):
+ cleaned_input[
+ "default_transaction_flow_strategy"
+ ] = default_transaction_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 57cfc65aee..14192516b7 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py
@@ -13,7 +13,11 @@ 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, MarkAsPaidStrategyEnum
+from ...enums import (
+ AllocationStrategyEnum,
+ MarkAsPaidStrategyEnum,
+ TransactionFlowStrategyEnum,
+)
CHANNEL_CREATE_MUTATION = """
mutation CreateChannel($input: ChannelCreateInput!){
@@ -37,6 +41,7 @@ CHANNEL_CREATE_MUTATION = """
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
markAsPaidStrategy
+ defaultTransactionFlowStrategy
}
}
errors{
@@ -504,3 +509,49 @@ def test_channel_create_set_order_mark_as_paid(
channel.order_mark_as_paid_strategy
== MarkAsPaidStrategyEnum.TRANSACTION_FLOW.value
)
+
+
+def test_channel_create_set_default_transaction_flow_strategy(
+ 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": {
+ "defaultTransactionFlowStrategy": (
+ TransactionFlowStrategyEnum.AUTHORIZATION.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"]["defaultTransactionFlowStrategy"]
+ == TransactionFlowStrategyEnum.AUTHORIZATION.name
+ )
+ assert (
+ channel.default_transaction_flow_strategy
+ == TransactionFlowStrategyEnum.AUTHORIZATION.value
+ )
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index 537e328e5a..676f27aa29 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -12,7 +12,11 @@ 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, MarkAsPaidStrategyEnum
+from ...enums import (
+ AllocationStrategyEnum,
+ MarkAsPaidStrategyEnum,
+ TransactionFlowStrategyEnum,
+)
CHANNEL_UPDATE_MUTATION = """
mutation UpdateChannel($id: ID!,$input: ChannelUpdateInput!){
@@ -36,6 +40,7 @@ CHANNEL_UPDATE_MUTATION = """
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
markAsPaidStrategy
+ defaultTransactionFlowStrategy
}
}
errors{
@@ -919,3 +924,44 @@ def test_channel_update_order_mark_as_paid_strategy(
channel_USD.order_mark_as_paid_strategy
== MarkAsPaidStrategyEnum.TRANSACTION_FLOW.value
)
+
+
+def test_channel_update_default_transaction_flow_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": {
+ "defaultTransactionFlowStrategy": (
+ TransactionFlowStrategyEnum.AUTHORIZATION.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"]["defaultTransactionFlowStrategy"]
+ == TransactionFlowStrategyEnum.AUTHORIZATION.name
+ )
+ channel_USD.refresh_from_db()
+ assert (
+ channel_USD.default_transaction_flow_strategy
+ == TransactionFlowStrategyEnum.AUTHORIZATION.value
+ )
diff --git a/saleor/graphql/channel/tests/queries/test_channel.py b/saleor/graphql/channel/tests/queries/test_channel.py
index ec69ad73c6..1381e7f63e 100644
--- a/saleor/graphql/channel/tests/queries/test_channel.py
+++ b/saleor/graphql/channel/tests/queries/test_channel.py
@@ -288,6 +288,8 @@ QUERY_CHANNEL_ORDER_SETTINGS = """
orderSettings {
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
+ markAsPaidStrategy
+ defaultTransactionFlowStrategy
}
}
}
@@ -328,6 +330,10 @@ def test_query_channel_order_settings_as_staff_user(
channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
== channel_USD.automatically_fulfill_non_shippable_gift_card
)
+ assert (
+ channel_data["orderSettings"]["defaultTransactionFlowStrategy"]
+ == channel_USD.default_transaction_flow_strategy.upper()
+ )
def test_query_channel_order_settings_as_app(
@@ -366,6 +372,10 @@ def test_query_channel_order_settings_as_app(
channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
== channel_USD.automatically_fulfill_non_shippable_gift_card
)
+ assert (
+ channel_data["orderSettings"]["defaultTransactionFlowStrategy"]
+ == channel_USD.default_transaction_flow_strategy.upper()
+ )
def test_query_channel_order_settings_as_staff_user_no_permission(
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index 8cccef73d9..3c92382c5b 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -32,12 +32,15 @@ from ..warehouse.dataloaders import WarehousesByChannelIdLoader
from ..warehouse.types import Warehouse
from . import ChannelContext
from .dataloaders import ChannelWithHasOrdersByIdLoader
-from .enums import AllocationStrategyEnum, MarkAsPaidStrategyEnum
+from .enums import (
+ AllocationStrategyEnum,
+ MarkAsPaidStrategyEnum,
+ TransactionFlowStrategyEnum,
+)
if TYPE_CHECKING:
from ...shipping.models import ShippingZone
-
T = TypeVar("T", bound=Model)
@@ -192,6 +195,14 @@ class OrderSettings(ObjectType):
+ PREVIEW_FEATURE
),
)
+ default_transaction_flow_strategy = TransactionFlowStrategyEnum(
+ required=True,
+ description=(
+ "Determine the transaction flow strategy to be used. "
+ "Include the selected option in the payload sent to the payment app, as a "
+ "requested action for the transaction." + ADDED_IN_313 + PREVIEW_FEATURE
+ ),
+ )
class Meta:
description = "Represents the channel-specific order settings."
@@ -441,4 +452,5 @@ class Channel(ModelObjectType):
root.automatically_fulfill_non_shippable_gift_card
),
mark_as_paid_strategy=root.order_mark_as_paid_strategy,
+ default_transaction_flow_strategy=root.default_transaction_flow_strategy,
)
diff --git a/saleor/graphql/checkout/enums.py b/saleor/graphql/checkout/enums.py
index f2bcb3ef8a..dca8d8418f 100644
--- a/saleor/graphql/checkout/enums.py
+++ b/saleor/graphql/checkout/enums.py
@@ -1,9 +1,20 @@
import graphene
-from ...checkout import error_codes
-from ..core.doc_category import DOC_CATEGORY_ORDERS
+from ...checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus, error_codes
+from ..core.doc_category import DOC_CATEGORY_CHECKOUT, DOC_CATEGORY_ORDERS
+from ..core.enums import to_enum
OrderCreateFromCheckoutErrorCode = graphene.Enum.from_enum(
error_codes.OrderCreateFromCheckoutErrorCode
)
OrderCreateFromCheckoutErrorCode.doc_category = DOC_CATEGORY_ORDERS
+
+CheckoutChargeStatusEnum = to_enum(
+ CheckoutChargeStatus, description=CheckoutChargeStatus.__doc__
+)
+CheckoutChargeStatusEnum.doc_category = DOC_CATEGORY_CHECKOUT
+
+CheckoutAuthorizeStatusEnum = to_enum(
+ CheckoutAuthorizeStatus, description=CheckoutAuthorizeStatus.__doc__
+)
+CheckoutAuthorizeStatusEnum.doc_category = DOC_CATEGORY_CHECKOUT
diff --git a/saleor/graphql/checkout/filters.py b/saleor/graphql/checkout/filters.py
index a006266276..07e2de6587 100644
--- a/saleor/graphql/checkout/filters.py
+++ b/saleor/graphql/checkout/filters.py
@@ -19,6 +19,7 @@ from ..core.types import DateRangeInput, FilterInputObjectType
from ..core.utils import from_global_id_or_error
from ..utils import resolve_global_ids_to_primary_keys
from ..utils.filters import filter_range_field
+from .enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
def get_checkout_token_from_query(value):
@@ -55,6 +56,22 @@ def filter_created_range(qs, _, value):
return filter_range_field(qs, "created_at__date", value)
+def filter_authorize_status(qs, _, value):
+ if value:
+ qs = qs.filter(authorize_status__in=value)
+ return qs
+
+
+def filter_charge_status(qs, _, value):
+ if value:
+ qs = qs.filter(charge_status__in=value)
+ return qs
+
+
+def filter_updated_at_range(qs, _, value):
+ return filter_range_field(qs, "last_change__date", value)
+
+
def filter_customer(qs, _, value):
users = User.objects.filter(
Q(email__ilike=value) | Q(first_name__ilike=value) | Q(last_name__ilike=value)
@@ -112,6 +129,15 @@ class CheckoutFilter(MetadataFilterBase):
metadata = ListObjectTypeFilter(
input_class=MetadataFilter, method=filter_checkout_metadata
)
+ updated_at = ObjectTypeFilter(
+ input_class=DateRangeInput, method=filter_updated_at_range
+ )
+ authorize_status = ListObjectTypeFilter(
+ input_class=CheckoutAuthorizeStatusEnum, method=filter_authorize_status
+ )
+ charge_status = ListObjectTypeFilter(
+ input_class=CheckoutChargeStatusEnum, method=filter_charge_status
+ )
class Meta:
model = Checkout
diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
index b73995f5f2..992e1d6611 100644
--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py
+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
@@ -1,9 +1,6 @@
-from typing import cast
-
import graphene
from django.core.exceptions import ValidationError
-from ....account.models import User
from ....checkout.checkout_cleaner import validate_checkout
from ....checkout.complete_checkout import create_order_from_checkout
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -112,7 +109,6 @@ class OrderCreateFromCheckout(BaseMutation):
remove_checkout
):
user = info.context.user
- user = cast(User, user)
checkout = cls.get_node_or_error(
info,
id,
@@ -153,7 +149,7 @@ class OrderCreateFromCheckout(BaseMutation):
manager=manager,
user=user,
app=app,
- tracking_code=str(tracking_code),
+ tracking_code=tracking_code,
delete_checkout=remove_checkout,
metadata_list=metadata,
private_metadata_list=private_metadata,
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index bde2424239..e78894cab6 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -390,7 +390,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(65):
+ with django_assert_num_queries(67):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -408,7 +408,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(65):
+ with django_assert_num_queries(67):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -658,7 +658,7 @@ def test_update_checkout_lines_with_reservations(
reservation_length=5,
)
- with django_assert_num_queries(70):
+ with django_assert_num_queries(72):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -672,7 +672,7 @@ def test_update_checkout_lines_with_reservations(
assert not data["errors"]
# Updating multiple lines in checkout has same query count as updating one
- with django_assert_num_queries(70):
+ with django_assert_num_queries(72):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -867,7 +867,7 @@ def test_add_checkout_lines_with_external_shipping(
assert not response["data"]["checkoutLinesAdd"]["errors"]
# Three api calls:
# - post-mutate() logic used to validate currently selected method
- # - fetch_checkout_prices_if_expired - calculating all prices for checkout
+ # - fetch_checkout_data - calculating all prices for checkout
# - in check_stock_quantity_bulk to check if the shipping method is set
assert mock_send_request.call_count == 3
@@ -916,7 +916,7 @@ def test_add_checkout_lines_with_reservations(
new_lines.append({"quantity": 2, "variantId": variant_id})
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(69):
+ with django_assert_num_queries(71):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -929,7 +929,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(69):
+ with django_assert_num_queries(71):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
new file mode 100644
index 0000000000..66093d28ca
--- /dev/null
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -0,0 +1,651 @@
+from decimal import Decimal
+
+from .....channel import MarkAsPaidStrategy
+from .....checkout import calculations
+from .....checkout.error_codes import CheckoutErrorCode
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....checkout.models import Checkout
+from .....checkout.payment_utils import update_checkout_payment_statuses
+from .....core.taxes import zero_money
+from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderOrigin, OrderStatus
+from .....order.models import Order
+from .....payment import TransactionEventType
+from .....payment.transaction_item_calculations import recalculate_transaction_amounts
+from .....plugins.manager import get_plugins_manager
+from .....warehouse.models import Reservation
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+
+MUTATION_CHECKOUT_COMPLETE = """
+ mutation checkoutComplete(
+ $id: ID,
+ $redirectUrl: String,
+ $metadata: [MetadataInput!],
+ ) {
+ checkoutComplete(
+ id: $id,
+ redirectUrl: $redirectUrl,
+ metadata: $metadata,
+ ) {
+ order {
+ id
+ token
+ original
+ origin
+ authorizeStatus
+ chargeStatus
+ deliveryMethod {
+ ... on Warehouse {
+ id
+ }
+ ... on ShippingMethod {
+ id
+ }
+ }
+ total {
+ currency
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ undiscountedTotal {
+ currency
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ }
+ errors {
+ field,
+ message,
+ variants,
+ code
+ }
+ confirmationNeeded
+ confirmationData
+ }
+ }
+ """
+
+
+def test_checkout_without_any_transaction(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ transaction_item_generator,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_gift_card
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.tax_exemption = True
+ checkout.save()
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert data["errors"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.name
+
+
+def test_checkout_with_total_0(
+ checkout_with_item_total_0,
+ user_api_client,
+ gift_card,
+ transaction_item_generator,
+ address,
+ shipping_method,
+ channel_USD,
+):
+ # given
+ shipping_method.channel_listings.update(price_amount=Decimal(0))
+
+ checkout = checkout_with_item_total_0
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save()
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ order = Order.objects.get()
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ assert to_global_id_or_none(order) == data["order"]["id"]
+
+ assert order.total_charged == zero_money(order.currency)
+ assert order.total_authorized == zero_money(order.currency)
+ assert order.charge_status == OrderChargeStatus.FULL
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
+
+
+def test_checkout_with_authorized(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ transaction_item_generator,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_gift_card
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.tax_exemption = True
+ checkout.save()
+ checkout.metadata_storage.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, authorized_value=total.gross.amount
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ order = Order.objects.get()
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ assert to_global_id_or_none(order) == data["order"]["id"]
+
+ assert order.total_charged == zero_money(order.currency)
+ assert order.total_authorized_amount == transaction.authorized_value
+ assert order.charge_status == OrderChargeStatus.NONE
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
+
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.origin == OrderOrigin.CHECKOUT
+
+ assert order.redirect_url == redirect_url
+ assert order.total.gross == total.gross
+ assert order.metadata == checkout.metadata_storage.metadata
+ assert order.private_metadata == checkout.metadata_storage.private_metadata
+
+ order_line = order.lines.first()
+ line_tax_class = order_line.tax_class
+ shipping_tax_class = shipping_method.tax_class
+
+ assert checkout_line_quantity == order_line.quantity
+ assert checkout_line_variant == order_line.variant
+
+ assert order_line.tax_class == line_tax_class
+ assert order_line.tax_class_name == line_tax_class.name
+ assert order_line.tax_class_metadata == line_tax_class.metadata
+ assert order_line.tax_class_private_metadata == line_tax_class.private_metadata
+
+ assert order.shipping_address == address
+ assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_tax_rate is not None
+ assert order.shipping_tax_class_name == shipping_tax_class.name
+ assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
+ assert (
+ order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata
+ )
+
+ assert not Checkout.objects.filter()
+ assert not len(Reservation.objects.all())
+
+
+def test_checkout_with_charged(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ transaction_item_generator,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_gift_card
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.tax_exemption = True
+ checkout.save()
+ checkout.metadata_storage.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=total.gross.amount
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ order = Order.objects.get()
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ assert to_global_id_or_none(order) == data["order"]["id"]
+
+ assert order.total_charged_amount == transaction.charged_value
+ assert order.total_authorized == zero_money(order.currency)
+ assert order.charge_status == OrderChargeStatus.FULL
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
+
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.origin == OrderOrigin.CHECKOUT
+
+ assert order.redirect_url == redirect_url
+ assert order.total.gross == total.gross
+ assert order.metadata == checkout.metadata_storage.metadata
+ assert order.private_metadata == checkout.metadata_storage.private_metadata
+
+ order_line = order.lines.first()
+ line_tax_class = order_line.tax_class
+ shipping_tax_class = shipping_method.tax_class
+
+ assert checkout_line_quantity == order_line.quantity
+ assert checkout_line_variant == order_line.variant
+
+ assert order_line.tax_class == line_tax_class
+ assert order_line.tax_class_name == line_tax_class.name
+ assert order_line.tax_class_metadata == line_tax_class.metadata
+ assert order_line.tax_class_private_metadata == line_tax_class.private_metadata
+
+ assert order.shipping_address == address
+ assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_tax_rate is not None
+ assert order.shipping_tax_class_name == shipping_tax_class.name
+ assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
+ assert (
+ order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata
+ )
+
+ assert not Checkout.objects.filter()
+ assert not len(Reservation.objects.all())
+
+
+def test_checkout_paid_with_multiple_transactions(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ transaction_item_generator,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_gift_card
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=total.gross.amount - Decimal("10")
+ )
+ second_transaction = transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=Decimal("10")
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ order = Order.objects.get()
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ assert to_global_id_or_none(order) == data["order"]["id"]
+
+ assert (
+ order.total_charged_amount
+ == transaction.charged_value + second_transaction.charged_value
+ )
+ assert order.total_authorized == zero_money(order.currency)
+ assert order.charge_status == OrderChargeStatus.FULL
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
+
+
+def test_checkout_partially_paid(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ transaction_item_generator,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_gift_card
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.tax_exemption = True
+ checkout.save()
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ transaction_item_generator(
+ checkout_id=checkout.pk, charged_value=total.gross.amount - Decimal("10")
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "id"
+ assert error["code"] == CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.name
+
+
+def test_checkout_with_pending_charged(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ transaction_item_generator,
+ address,
+ shipping_method,
+ transaction_events_generator,
+):
+ # given
+ checkout = checkout_with_gift_card
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ transaction = transaction_item_generator(checkout_id=checkout.pk)
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.CHARGE_REQUEST,
+ ],
+ amounts=[
+ total.gross.amount,
+ ],
+ )
+ recalculate_transaction_amounts(transaction)
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ order = Order.objects.get()
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ assert to_global_id_or_none(order) == data["order"]["id"]
+
+ assert order.total_charged == zero_money(order.currency)
+ assert order.total_authorized == zero_money(order.currency)
+ assert order.charge_status == OrderChargeStatus.NONE
+ assert order.authorize_status == OrderAuthorizeStatus.NONE
+
+
+def test_checkout_with_pending_authorized(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ transaction_item_generator,
+ address,
+ shipping_method,
+ transaction_events_generator,
+):
+ # given
+ checkout = checkout_with_gift_card
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.tax_exemption = True
+ checkout.save()
+ checkout.metadata_storage.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.save()
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ transaction = transaction_item_generator(checkout_id=checkout.pk)
+ transaction_events_generator(
+ transaction=transaction,
+ psp_references=[
+ "1",
+ ],
+ types=[
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ ],
+ amounts=[
+ total.gross.amount,
+ ],
+ )
+ recalculate_transaction_amounts(transaction)
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ order = Order.objects.get()
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ assert to_global_id_or_none(order) == data["order"]["id"]
+
+ assert order.total_charged == zero_money(order.currency)
+ assert order.total_authorized == zero_money(order.currency)
+ assert order.charge_status == OrderChargeStatus.NONE
+ assert order.authorize_status == OrderAuthorizeStatus.NONE
+
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.origin == OrderOrigin.CHECKOUT
+
+ assert order.redirect_url == redirect_url
+ assert order.total.gross == total.gross
+ assert order.metadata == checkout.metadata_storage.metadata
+ assert order.private_metadata == checkout.metadata_storage.private_metadata
+
+ order_line = order.lines.first()
+ line_tax_class = order_line.tax_class
+ shipping_tax_class = shipping_method.tax_class
+
+ assert checkout_line_quantity == order_line.quantity
+ assert checkout_line_variant == order_line.variant
+
+ assert order_line.tax_class == line_tax_class
+ assert order_line.tax_class_name == line_tax_class.name
+ assert order_line.tax_class_metadata == line_tax_class.metadata
+ assert order_line.tax_class_private_metadata == line_tax_class.private_metadata
+
+ assert order.shipping_address == address
+ assert order.shipping_method == checkout.shipping_method
+ assert order.shipping_tax_rate is not None
+ assert order.shipping_tax_class_name == shipping_tax_class.name
+ assert order.shipping_tax_class_metadata == shipping_tax_class.metadata
+ assert (
+ order.shipping_tax_class_private_metadata == shipping_tax_class.private_metadata
+ )
+
+ assert not Checkout.objects.filter()
+ assert not len(Reservation.objects.all())
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
index 3c347f427b..4b92793a76 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
@@ -73,7 +73,6 @@ def test_checkout_remove_voucher_code_with_inactive_channel(
channel = checkout_with_voucher.channel
channel.is_active = False
channel.save()
- previous_checkout_last_change = checkout_with_voucher.last_change
variables = {
"id": to_global_id_or_none(checkout_with_voucher),
@@ -86,7 +85,6 @@ def test_checkout_remove_voucher_code_with_inactive_channel(
assert not data["errors"]
assert data["checkout"]["token"] == str(checkout_with_voucher.token)
assert data["checkout"]["voucherCode"] == checkout_with_voucher.voucher_code
- assert checkout_with_voucher.last_change == previous_checkout_last_change
def test_checkout_remove_gift_card_code(api_client, checkout_with_gift_card):
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index 37960bae93..6dcdb57c6b 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -627,6 +627,11 @@ def test_order_from_checkout_with_voucher_apply_once_per_order(
voucher_percentage.save(update_fields=["usage_limit", "apply_once_per_order"])
checkout = checkout_with_voucher_percentage
+
+ checkout_line = checkout.lines.first()
+ checkout_line_quantity = checkout_line.quantity
+ checkout_line_variant = checkout_line.variant
+
checkout.shipping_address = address
checkout.shipping_method = shipping_method
checkout.billing_address = address
@@ -634,6 +639,13 @@ def test_order_from_checkout_with_voucher_apply_once_per_order(
checkout.metadata_storage.store_value_in_private_metadata(
items={"accepted": "false"}
)
+ discount_amount = checkout_line_variant.channel_listings.get(
+ channel=checkout.channel
+ ).price * (
+ voucher_percentage.channel_listings.get(channel=checkout.channel).discount_value
+ / 100
+ )
+ checkout.discount = discount_amount
checkout.save()
checkout.metadata_storage.save()
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 969fc66b6f..6625b153e2 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -31,6 +31,7 @@ from ....warehouse import WarehouseClickAndCollectOption
from ....warehouse.models import PreorderReservation, Reservation, Stock, Warehouse
from ...core.utils import to_global_id_or_none
from ...tests.utils import assert_no_permission, get_graphql_content
+from ..enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
from ..mutations.utils import (
clean_delivery_method,
update_checkout_shipping_method_if_invalid,
@@ -2164,7 +2165,7 @@ def test_checkout_transactions_with_manage_checkouts(
assert len(content["data"]["checkout"]["transactions"]) == 1
transaction_id = content["data"]["checkout"]["transactions"][0]["id"]
assert transaction_id == graphene.Node.to_global_id(
- "TransactionItem", transaction.id
+ "TransactionItem", transaction.token
)
@@ -2193,5 +2194,92 @@ def test_checkout_transactions_with_handle_payments(
assert len(content["data"]["checkout"]["transactions"]) == 1
transaction_id = content["data"]["checkout"]["transactions"][0]["id"]
assert transaction_id == graphene.Node.to_global_id(
- "TransactionItem", transaction.id
+ "TransactionItem", transaction.token
+ )
+
+
+QUERY_CHECKOUT_STATUSES_AND_BALANCE = """
+query getCheckout($id: ID) {
+ checkout(id: $id) {
+ updatedAt
+ chargeStatus
+ authorizeStatus
+ totalBalance {
+ currency
+ amount
+ }
+ }
+}
+"""
+
+
+def test_checkout_payment_statuses(
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ checkout_with_prices.payment_transactions.create(
+ status="Authorized",
+ name="Credit card",
+ psp_reference="123",
+ currency="USD",
+ authorized_value=Decimal("15"),
+ charged_value=Decimal("5"),
+ charge_pending_value=Decimal("6"),
+ available_actions=[TransactionAction.CHARGE, TransactionAction.VOID],
+ )
+ query = QUERY_CHECKOUT_STATUSES_AND_BALANCE
+ variables = {"id": to_global_id_or_none(checkout_with_prices)}
+
+ # when
+ response = user_api_client.post_graphql(
+ query,
+ variables,
+ )
+
+ # then
+ checkout_with_prices.refresh_from_db()
+ content = get_graphql_content(response)
+ assert (
+ content["data"]["checkout"]["chargeStatus"]
+ == CheckoutChargeStatusEnum.PARTIAL.name
+ )
+ assert (
+ content["data"]["checkout"]["authorizeStatus"]
+ == CheckoutAuthorizeStatusEnum.PARTIAL.name
+ )
+
+
+def test_checkout_balance(
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ transaction = checkout_with_prices.payment_transactions.create(
+ status="Authorized",
+ name="Credit card",
+ psp_reference="123",
+ currency="USD",
+ authorized_value=Decimal("15"),
+ charged_value=Decimal("5"),
+ charge_pending_value=Decimal("6"),
+ available_actions=[TransactionAction.CHARGE, TransactionAction.VOID],
+ )
+ query = QUERY_CHECKOUT_STATUSES_AND_BALANCE
+ variables = {"id": to_global_id_or_none(checkout_with_prices)}
+
+ # when
+ response = user_api_client.post_graphql(
+ query,
+ variables,
+ )
+
+ # then
+ checkout_with_prices.refresh_from_db()
+ content = get_graphql_content(response)
+ assert (
+ content["data"]["checkout"]["totalBalance"]["amount"]
+ == transaction.charged_value
+ + transaction.charge_pending_value
+ - checkout_with_prices.total.gross.amount
)
diff --git a/saleor/graphql/checkout/tests/test_checkout_filters.py b/saleor/graphql/checkout/tests/test_checkout_filters.py
index 4dd4998014..821365d0fd 100644
--- a/saleor/graphql/checkout/tests/test_checkout_filters.py
+++ b/saleor/graphql/checkout/tests/test_checkout_filters.py
@@ -1,5 +1,6 @@
import uuid
from datetime import date, timedelta
+from decimal import Decimal
import graphene
import pytest
@@ -7,8 +8,10 @@ from freezegun import freeze_time
from ....account.models import User
from ....checkout.models import Checkout
+from ....checkout.payment_utils import update_checkout_payment_statuses
from ....payment.models import ChargeStatus, Payment
from ...tests.utils import get_graphql_content
+from ..enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
@pytest.fixture
@@ -390,3 +393,214 @@ def test_checkouts_query_with_filter_search_by_token(
response = staff_api_client.post_graphql(checkout_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["checkouts"]["totalCount"] == 1
+
+
+ "transaction_data, statuses, expected_count",
+ [
+ (
+ {"authorized_value": Decimal("10")},
+ [CheckoutAuthorizeStatusEnum.PARTIAL.name],
+ 1,
+ ),
+ (
+ {"charged_value": Decimal("10")},
+ [CheckoutAuthorizeStatusEnum.PARTIAL.name],
+ 1,
+ ),
+ (
+ {"authorize_pending_value": Decimal("10")},
+ [CheckoutAuthorizeStatusEnum.PARTIAL.name],
+ 1,
+ ),
+ (
+ {"charge_pending_value": Decimal("10")},
+ [CheckoutAuthorizeStatusEnum.PARTIAL.name],
+ 1,
+ ),
+ (
+ {"authorized_value": Decimal("0")},
+ [CheckoutAuthorizeStatusEnum.NONE.name],
+ 1,
+ ),
+ (
+ {"authorized_value": Decimal("200")},
+ [CheckoutAuthorizeStatusEnum.FULL.name],
+ 2,
+ ),
+ (
+ {"charged_value": Decimal("200")},
+ [CheckoutAuthorizeStatusEnum.FULL.name],
+ 2,
+ ),
+ (
+ {"authorize_pending_value": Decimal("200")},
+ [CheckoutAuthorizeStatusEnum.FULL.name],
+ 2,
+ ),
+ (
+ {"charge_pending_value": Decimal("200")},
+ [CheckoutAuthorizeStatusEnum.FULL.name],
+ 2,
+ ),
+ (
+ {"authorized_value": Decimal("10")},
+ [
+ CheckoutAuthorizeStatusEnum.FULL.name,
+ CheckoutAuthorizeStatusEnum.PARTIAL.name,
+ ],
+ 2,
+ ),
+ (
+ {"authorized_value": Decimal("0")},
+ [
+ CheckoutAuthorizeStatusEnum.FULL.name,
+ CheckoutAuthorizeStatusEnum.NONE.name,
+ ],
+ 2,
+ ),
+ (
+ {"authorized_value": Decimal("10"), "charged_value": Decimal("90")},
+ [CheckoutAuthorizeStatusEnum.PARTIAL.name],
+ 1,
+ ),
+ ],
+)
+def test_checkouts_query_with_filter_authorize_status(
+ transaction_data,
+ statuses,
+ expected_count,
+ checkout_query_with_filter,
+ staff_api_client,
+ permission_manage_checkouts,
+ customer_user,
+ channel_USD,
+ checkout_with_prices,
+ checkout,
+):
+ # given
+ first_checkout = Checkout.objects.create(
+ currency=channel_USD.currency_code, channel=channel_USD
+ )
+ first_checkout.payment_transactions.create(
+ currency=checkout_with_prices.currency, authorized_value=Decimal("10")
+ )
+
+ update_checkout_payment_statuses(first_checkout, first_checkout.total.gross)
+
+ checkout_with_prices.payment_transactions.create(
+ currency=checkout_with_prices.currency, **transaction_data
+ )
+ update_checkout_payment_statuses(
+ checkout_with_prices, checkout_with_prices.total.gross
+ )
+
+ variables = {"filter": {"authorizeStatus": statuses}}
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+
+ # when
+ response = staff_api_client.post_graphql(checkout_query_with_filter, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["checkouts"]["totalCount"] == expected_count
+
+
+ "transaction_data, statuses, expected_count",
+ [
+ (
+ {"charged_value": Decimal("10")},
+ [CheckoutChargeStatusEnum.PARTIAL.name],
+ 1,
+ ),
+ (
+ {"charge_pending_value": Decimal("10")},
+ [CheckoutChargeStatusEnum.PARTIAL.name],
+ 1,
+ ),
+ (
+ {"charged_value": Decimal("00")},
+ [CheckoutChargeStatusEnum.PARTIAL.name],
+ 0,
+ ),
+ (
+ {"charged_value": Decimal("178.00")},
+ [CheckoutChargeStatusEnum.FULL.name],
+ 1,
+ ),
+ (
+ {"charge_pending_value": Decimal("178.00")},
+ [CheckoutChargeStatusEnum.FULL.name],
+ 1,
+ ),
+ (
+ {
+ "charge_pending_value": Decimal("100.00"),
+ "charged_value": Decimal("78.00"),
+ },
+ [CheckoutChargeStatusEnum.FULL.name],
+ 1,
+ ),
+ (
+ {"charged_value": Decimal("0.00")},
+ [CheckoutChargeStatusEnum.OVERCHARGED.name],
+ 1,
+ ),
+ (
+ {"charged_value": Decimal("10")},
+ [CheckoutChargeStatusEnum.FULL.name, CheckoutChargeStatusEnum.PARTIAL.name],
+ 1,
+ ),
+ (
+ {"charged_value": Decimal("0")},
+ [CheckoutChargeStatusEnum.FULL.name, CheckoutChargeStatusEnum.NONE.name],
+ 1,
+ ),
+ (
+ {"charged_value": Decimal("178.00")},
+ [
+ CheckoutChargeStatusEnum.FULL.name,
+ CheckoutChargeStatusEnum.OVERCHARGED.name,
+ ],
+ 2,
+ ),
+ ],
+)
+def test_checkouts_query_with_filter_charge_status(
+ transaction_data,
+ statuses,
+ expected_count,
+ checkout_query_with_filter,
+ checkout_with_prices,
+ staff_api_client,
+ permission_manage_checkouts,
+ customer_user,
+ channel_USD,
+):
+ # given
+ first_checkout = Checkout.objects.create(
+ currency=channel_USD.currency_code, channel=channel_USD
+ )
+ first_checkout.payment_transactions.create(
+ currency=checkout_with_prices.currency, charged_value=Decimal("10")
+ )
+
+ update_checkout_payment_statuses(first_checkout, first_checkout.total.gross)
+
+ checkout_with_prices.payment_transactions.create(
+ currency=checkout_with_prices.currency, **transaction_data
+ )
+ update_checkout_payment_statuses(
+ checkout_with_prices, checkout_with_prices.total.gross
+ )
+
+ variables = {"filter": {"chargeStatus": statuses}}
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+
+ # when
+ response = staff_api_client.post_graphql(checkout_query_with_filter, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["checkouts"]["totalCount"] == expected_count
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 025367036f..ce8ad63f7d 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -1,3 +1,5 @@
+from typing import TYPE_CHECKING, Optional
+
import graphene
from promise import Promise
@@ -6,8 +8,9 @@ from ...checkout.base_calculations import (
calculate_undiscounted_base_line_total_price,
calculate_undiscounted_base_line_unit_price,
)
+from ...checkout.calculations import fetch_checkout_data
from ...checkout.utils import get_valid_collection_points_for_checkout
-from ...core.taxes import zero_taxed_money
+from ...core.taxes import zero_money, zero_taxed_money
from ...permission.enums import (
AccountPermissions,
CheckoutPermissions,
@@ -30,6 +33,7 @@ from ..core.descriptions import (
ADDED_IN_35,
ADDED_IN_38,
ADDED_IN_39,
+ ADDED_IN_313,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
)
@@ -71,8 +75,33 @@ from .dataloaders import (
CheckoutMetadataByCheckoutIdLoader,
TransactionItemsByCheckoutIDLoader,
)
+from .enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
from .utils import prevent_sync_event_circular_query
+if TYPE_CHECKING:
+ from ...account.models import Address
+ from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo
+ from ...discount import DiscountInfo
+ from ...plugins.manager import PluginsManager
+
+
+def get_dataloaders_for_fetching_checkout_data(
+ root: models.Checkout, info: ResolveInfo
+) -> tuple[
+ Optional[Promise["Address"]],
+ Promise[list["CheckoutLineInfo"]],
+ Promise["CheckoutInfo"],
+ Promise[list["DiscountInfo"]],
+ Promise["PluginsManager"],
+]:
+ address_id = root.shipping_address_id or root.billing_address_id
+ address = AddressByIdLoader(info.context).load(address_id) if address_id else None
+ lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token)
+ checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(root.token)
+ discounts = DiscountsByDateTimeLoader(info.context).load(info.context.request_time)
+ manager = get_plugin_manager_promise(info.context)
+ return address, lines, checkout_info, discounts, manager
+
class GatewayConfigLine(BaseObjectType):
field = graphene.String(required=True, description="Gateway config key.")
@@ -348,7 +377,14 @@ class DeliveryMethod(graphene.Union):
class Checkout(ModelObjectType[models.Checkout]):
id = graphene.ID(required=True)
created = graphene.DateTime(required=True)
- last_change = graphene.DateTime(required=True)
+ updated_at = graphene.DateTime(
+ required=True,
+ description=("Time of last modification of the given checkout." + ADDED_IN_313),
+ )
+ last_change = graphene.DateTime(
+ required=True,
+ deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Use `updatedAt` instead."),
+ )
user = graphene.Field("saleor.graphql.account.types.User")
channel = graphene.Field(Channel, required=True)
billing_address = graphene.Field("saleor.graphql.account.types.Address")
@@ -447,6 +483,17 @@ class Checkout(ModelObjectType[models.Checkout]):
),
required=True,
)
+
+ total_balance = graphene.Field(
+ Money,
+ description=(
+ "The difference between the paid and the checkout total amount."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ required=True,
+ )
+
language_code = graphene.Field(
LanguageCodeEnum, description="Checkout language code.", required=True
)
@@ -466,6 +513,18 @@ class Checkout(ModelObjectType[models.Checkout]):
),
required=True,
)
+ authorize_status = CheckoutAuthorizeStatusEnum(
+ description=(
+ "The authorize status of the checkout." + ADDED_IN_313 + PREVIEW_FEATURE
+ ),
+ required=True,
+ )
+ charge_status = CheckoutChargeStatusEnum(
+ description=(
+ "The charge status of the checkout." + ADDED_IN_313 + PREVIEW_FEATURE
+ ),
+ required=True,
+ )
class Meta:
description = "Checkout object."
@@ -568,19 +627,8 @@ class Checkout(ModelObjectType[models.Checkout]):
)
return max(taxed_total, zero_taxed_money(root.currency))
- address_id = root.shipping_address_id or root.billing_address_id
- address = (
- AddressByIdLoader(info.context).load(address_id) if address_id else None
- )
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token)
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(root.token)
- discounts = DiscountsByDateTimeLoader(info.context).load(
- info.context.request_time
- )
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([address, lines, checkout_info, discounts, manager]).then(
- calculate_total_price
- )
+ dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
+ return Promise.all(dataloaders).then(calculate_total_price)
@staticmethod
@traced_resolver
@@ -596,20 +644,8 @@ class Checkout(ModelObjectType[models.Checkout]):
discounts=discounts,
)
- address_id = root.shipping_address_id or root.billing_address_id
- address = (
- AddressByIdLoader(info.context).load(address_id) if address_id else None
- )
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token)
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(root.token)
- discounts = DiscountsByDateTimeLoader(info.context).load(
- info.context.request_time
- )
- manager = get_plugin_manager_promise(info.context)
-
- return Promise.all([address, lines, checkout_info, discounts, manager]).then(
- calculate_subtotal_price
- )
+ dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
+ return Promise.all(dataloaders).then(calculate_subtotal_price)
@staticmethod
@traced_resolver
@@ -625,21 +661,8 @@ class Checkout(ModelObjectType[models.Checkout]):
discounts=discounts,
)
- address = (
- AddressByIdLoader(info.context).load(root.shipping_address_id)
- if root.shipping_address_id
- else None
- )
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token)
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(root.token)
- discounts = DiscountsByDateTimeLoader(info.context).load(
- info.context.request_time
- )
- manager = get_plugin_manager_promise(info.context)
-
- return Promise.all([address, lines, checkout_info, discounts, manager]).then(
- calculate_shipping_price
- )
+ dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
+ return Promise.all(dataloaders).then(calculate_shipping_price)
@staticmethod
def resolve_lines(root: models.Checkout, info: ResolveInfo):
@@ -857,6 +880,74 @@ class Checkout(ModelObjectType[models.Checkout]):
)
return item_type
+ @classmethod
+ def resolve_updated_at(cls, root: models.Checkout, _info):
+ return root.last_change
+
+ @classmethod
+ def resolve_authorize_status(cls, root: models.Checkout, info):
+ def _resolve_authorize_status(data):
+ address, lines, checkout_info, discounts, manager, transactions = data
+ fetch_checkout_data(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ checkout_transactions=transactions,
+ )
+ return checkout_info.checkout.authorize_status
+
+ dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
+ dataloaders.append(
+ TransactionItemsByCheckoutIDLoader(info.context).load(root.pk)
+ )
+ return Promise.all(dataloaders).then(_resolve_authorize_status)
+
+ @classmethod
+ def resolve_charge_status(cls, root: models.Checkout, info):
+ def _resolve_charge_status(data):
+ address, lines, checkout_info, discounts, manager, transactions = data
+ fetch_checkout_data(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ checkout_transactions=transactions,
+ )
+ return checkout_info.checkout.charge_status
+
+ dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
+ dataloaders.append(
+ TransactionItemsByCheckoutIDLoader(info.context).load(root.pk)
+ )
+ return Promise.all(dataloaders).then(_resolve_charge_status)
+
+ @classmethod
+ def resolve_total_balance(cls, root: models.Checkout, info):
+ def _calculate_total_balance_for_transactions(data):
+ address, lines, checkout_info, discounts, manager, transactions = data
+ taxed_total = calculations.calculate_checkout_total_with_gift_cards(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ )
+ checkout_total = max(taxed_total, zero_taxed_money(root.currency))
+ total_charged = zero_money(root.currency)
+ for transaction in transactions:
+ total_charged += transaction.amount_charged
+ total_charged += transaction.amount_charge_pending
+ return total_charged - checkout_total.gross
+
+ dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
+ dataloaders.append(
+ TransactionItemsByCheckoutIDLoader(info.context).load(root.pk)
+ )
+ return Promise.all(dataloaders).then(_calculate_total_balance_for_transactions)
+
class CheckoutCountableConnection(CountableConnection):
class Meta:
diff --git a/saleor/graphql/checkout/utils.py b/saleor/graphql/checkout/utils.py
index 1fb8b8ef7b..fe434d9557 100644
--- a/saleor/graphql/checkout/utils.py
+++ b/saleor/graphql/checkout/utils.py
@@ -2,6 +2,7 @@ import graphene
from django.core.exceptions import ValidationError
from ...core.exceptions import CircularSubscriptionSyncEvent
+from ...webhook.event_types import WebhookEventSyncType
def prepare_insufficient_stock_checkout_validation_error(exc):
@@ -30,7 +31,13 @@ def prevent_sync_event_circular_query(func):
def wrapper(*args, **kwargs):
info = next(arg for arg in args if isinstance(arg, graphene.ResolveInfo))
- if getattr(info.context, "sync_event", False):
+ sync_event = getattr(info.context, "sync_event", False)
+ event_type = getattr(info.context, "event_type", None)
+ event_allowed = (
+ event_type and event_type in WebhookEventSyncType.ALLOWED_IN_CIRCULAR_QUERY
+ )
+
+ if sync_event and not event_allowed:
raise CircularSubscriptionSyncEvent(
"Resolving this field is not allowed in synchronous events."
)
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index ff07a4d229..f0e20019a2 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -225,6 +225,27 @@ TransactionEventReportErrorCode = graphene.Enum.from_enum(
)
TransactionEventReportErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+TransactionInitializeErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.TransactionInitializeErrorCode
+)
+TransactionInitializeErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+
+TransactionProcessErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.TransactionProcessErrorCode
+)
+TransactionProcessErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+
+PaymentGatewayConfigErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.PaymentGatewayConfigErrorCode
+)
+PaymentGatewayConfigErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+
+PaymentGatewayInitializeErrorCode = graphene.Enum.from_enum(
+ payment_error_codes.PaymentGatewayInitializeErrorCode
+)
+PaymentGatewayInitializeErrorCode.doc_category = DOC_CATEGORY_PAYMENTS
+
+
PermissionGroupErrorCode = graphene.Enum.from_enum(
account_error_codes.PermissionGroupErrorCode
)
diff --git a/saleor/graphql/core/scalars.py b/saleor/graphql/core/scalars.py
index 1369ad650a..c33621ee6b 100644
--- a/saleor/graphql/core/scalars.py
+++ b/saleor/graphql/core/scalars.py
@@ -1,6 +1,7 @@
import decimal
import graphene
+from graphene.types.generic import GenericScalar
from graphql.error import GraphQLError
from graphql.language import ast
from measurement.measures import Weight
@@ -53,6 +54,14 @@ class PositiveDecimal(Decimal):
return value
+class JSON(GenericScalar):
+ @staticmethod
+ def parse_literal(node):
+ if not isinstance(node, ast.ObjectValue):
+ raise GraphQLError("JSON scalar needs to recieve a correct JSON structure.")
+ return node
+
+
class WeightScalar(graphene.Scalar):
@staticmethod
def parse_value(value):
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 07d2f03342..e4278390e6 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -50,6 +50,8 @@ from ..enums import (
OrderSettingsErrorCode,
PageErrorCode,
PaymentErrorCode,
+ PaymentGatewayConfigErrorCode,
+ PaymentGatewayInitializeErrorCode,
PermissionEnum,
PermissionGroupErrorCode,
PluginErrorCode,
@@ -64,6 +66,8 @@ from ..enums import (
TimePeriodTypeEnum,
TransactionCreateErrorCode,
TransactionEventReportErrorCode,
+ TransactionInitializeErrorCode,
+ TransactionProcessErrorCode,
TransactionRequestActionErrorCode,
TransactionUpdateErrorCode,
TranslationErrorCode,
@@ -553,6 +557,24 @@ class TransactionEventReportError(Error):
code = TransactionEventReportErrorCode(description="The error code.", required=True)
+class TransactionInitializeError(Error):
+ code = TransactionInitializeErrorCode(description="The error code.", required=True)
+
+
+class TransactionProcessError(Error):
+ code = TransactionProcessErrorCode(description="The error code.", required=True)
+
+
+class PaymentGatewayConfigError(Error):
+ code = PaymentGatewayConfigErrorCode(description="The error code.", required=True)
+
+
+class PaymentGatewayInitializeError(Error):
+ code = PaymentGatewayInitializeErrorCode(
+ 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/order_or_checkout.py b/saleor/graphql/core/types/order_or_checkout.py
new file mode 100644
index 0000000000..a1dfce4483
--- /dev/null
+++ b/saleor/graphql/core/types/order_or_checkout.py
@@ -0,0 +1,32 @@
+import graphene
+
+from ....checkout.models import Checkout
+from ....order.models import Order
+from ...checkout import types as checkout_types
+from ...order import types as order_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 OrderOrCheckoutBase(graphene.Union):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def get_types(cls):
+ return (checkout_types.Checkout, order_types.Order)
+
+ @classmethod
+ def resolve_type(cls, instance, info: graphene.ResolveInfo):
+ if isinstance(instance, Checkout):
+ return checkout_types.Checkout
+ if isinstance(instance, Order):
+ return order_types.Order
+ return super(OrderOrCheckoutBase, cls).resolve_type(instance, info)
+
+
+class OrderOrCheckout(OrderOrCheckoutBase):
+ class Meta:
+ types = OrderOrCheckoutBase.get_types()
diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.py
index a4528194a0..09003f202d 100644
--- a/saleor/graphql/core/types/taxes.py
+++ b/saleor/graphql/core/types/taxes.py
@@ -40,19 +40,12 @@ from ...tax.dataloaders import (
from .. import ResolveInfo
from .common import NonNullList
from .money import Money
+from .order_or_checkout import OrderOrCheckoutBase
-class TaxSourceObject(graphene.Union):
+class TaxSourceObject(OrderOrCheckoutBase):
class Meta:
- types = (checkout_types.Checkout, order_types.Order)
-
- @classmethod
- def resolve_type(cls, instance, info: ResolveInfo):
- if isinstance(instance, Checkout):
- return checkout_types.Checkout
- if isinstance(instance, Order):
- return order_types.Order
- return super(TaxSourceObject, cls).resolve_type(instance, info)
+ types = OrderOrCheckoutBase.get_types()
class TaxSourceLine(graphene.Union):
diff --git a/saleor/graphql/meta/tests/test_meta_mutations.py b/saleor/graphql/meta/tests/test_meta_mutations.py
index 76b24745c1..c49a487656 100644
--- a/saleor/graphql/meta/tests/test_meta_mutations.py
+++ b/saleor/graphql/meta/tests/test_meta_mutations.py
@@ -4797,7 +4797,9 @@ def test_add_public_metadata_for_transaction_item(
):
# given
transaction_item = TransactionItem.objects.create()
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction_item.pk)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
# when
response = execute_update_public_metadata_for_item(
@@ -4817,7 +4819,9 @@ def test_delete_public_metadata_for_transaction_item(
transaction_item = TransactionItem.objects.create(
metadata={PUBLIC_KEY: PUBLIC_VALUE}
)
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction_item.pk)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
# when
response = execute_clear_public_metadata_for_item(
@@ -4837,7 +4841,9 @@ def test_add_private_metadata_for_transaction_item(
transaction_item = TransactionItem.objects.create(
private_metadata={PRIVATE_KEY: PRIVATE_VALUE}
)
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction_item.pk)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
# when
response = execute_update_private_metadata_for_item(
@@ -4859,7 +4865,9 @@ def test_delete_private_metadata_for_transaction_item(
transaction_item = TransactionItem.objects.create(
private_metadata={PRIVATE_KEY: PRIVATE_VALUE}
)
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction_item.pk)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
# when
response = execute_clear_private_metadata_for_item(
diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.py
index 2baf7d2ffb..6002af94c9 100644
--- a/saleor/graphql/order/tests/queries/test_order.py
+++ b/saleor/graphql/order/tests/queries/test_order.py
@@ -21,7 +21,6 @@ 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 TransactionEventStatusEnum
from ....payment.types import PaymentChargeStatusEnum
@@ -727,7 +726,7 @@ def test_order_query_with_transactions_details(
TransactionEvent(
message=event_name,
status=event_status,
- psp_reference=f"{event_reference}{to_global_id_or_none(transaction)}",
+ psp_reference=f"{event_reference}{transaction.token}",
transaction=transaction,
currency=transaction.currency,
)
@@ -766,7 +765,8 @@ def test_order_query_with_transactions_details(
event = transaction["events"][0]
assert event["name"] == event_name
assert event["status"] == TransactionEventStatusEnum.FAILURE.name
- assert event["pspReference"] == f"{event_reference}{transaction.get('id')}"
+ _, expected_uuid = graphene.Node.from_global_id(transaction.get("id"))
+ assert event["pspReference"] == f"{event_reference}{expected_uuid}"
def test_order_query_shipping_method_channel_listing_does_not_exist(
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 5c1f6d9e91..6da1e098c9 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,16 +1,24 @@
+import uuid
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, List, Optional, Union, cast
+from typing import TYPE_CHECKING, Dict, Iterable, 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 Model
+from django.db.models import Model, QuerySet
from django.utils import timezone
+from graphql import GraphQLError
+from ...app.models import App
+from ...channel import TransactionFlowStrategy
from ...channel.models import Channel
from ...checkout import models as checkout_models
-from ...checkout.calculations import calculate_checkout_total_with_gift_cards
+from ...checkout.actions import transaction_amounts_for_checkout_updated
+from ...checkout.calculations import (
+ calculate_checkout_total_with_gift_cards,
+ fetch_checkout_data,
+)
from ...checkout.checkout_cleaner import clean_billing_address, clean_checkout_shipping
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...checkout.utils import cancel_active_payments
@@ -21,6 +29,7 @@ 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 ...order.search import update_order_search_vector
from ...order.utils import updates_amounts_for_order
from ...payment import (
@@ -34,7 +43,7 @@ from ...payment import models as payment_models
from ...payment.error_codes import (
PaymentErrorCode,
TransactionCreateErrorCode,
- TransactionEventReportErrorCode,
+ TransactionProcessErrorCode,
TransactionRequestActionErrorCode,
TransactionUpdateErrorCode,
)
@@ -43,6 +52,7 @@ from ...payment.gateway import (
request_charge_action,
request_refund_action,
)
+from ...payment.interface import PaymentGatewayData
from ...payment.transaction_item_calculations import (
calculate_transaction_amount_based_on_events,
recalculate_transaction_amounts,
@@ -53,12 +63,16 @@ from ...payment.utils import (
create_manual_adjustment_events,
create_payment,
get_already_existing_event,
+ get_final_session_statuses,
+ handle_transaction_initialize_session,
+ handle_transaction_process_session,
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
+from ..channel.enums import TransactionFlowStrategyEnum
from ..channel.utils import validate_channel
from ..checkout.mutations.utils import get_checkout
from ..checkout.types import Checkout
@@ -72,11 +86,17 @@ from ..core.descriptions import (
PREVIEW_FEATURE_DEPRECATED_IN_313_INPUT,
)
from ..core.doc_category import DOC_CATEGORY_CHECKOUT, DOC_CATEGORY_PAYMENTS
+from ..core.enums import (
+ PaymentGatewayInitializeErrorCode,
+ TransactionEventReportErrorCode,
+ TransactionInitializeErrorCode,
+)
from ..core.fields import JSONString
from ..core.mutations import BaseMutation, ModelMutation
-from ..core.scalars import UUID, PositiveDecimal
+from ..core.scalars import JSON, UUID, PositiveDecimal
from ..core.types import BaseInputObjectType
from ..core.types import common as common_types
+from ..core.utils import from_global_id_or_error
from ..discount.dataloaders import load_discounts
from ..meta.mutations import MetadataInput
from ..plugins.dataloaders import get_plugin_manager_promise
@@ -92,8 +112,8 @@ 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
+ from ...discount import DiscountInfo
+ from ...plugins.manager import PluginsManager
class PaymentInput(BaseInputObjectType):
@@ -928,6 +948,8 @@ class TransactionCreate(BaseMutation):
if app and app.identifier:
app_identifier = app.identifier
return payment_models.TransactionItem.objects.create(
+ token=uuid.uuid4(),
+ use_old_id=True,
**transaction_input,
user=user if user and user.is_authenticated else None,
app_identifier=app_identifier,
@@ -1028,12 +1050,45 @@ class TransactionCreate(BaseMutation):
"search_vector",
]
)
+ if transaction_data.get("checkout_id") and money_data:
+ discounts = load_discounts(info.context)
+ manager = get_plugin_manager_promise(info.context).get()
+ transaction_amounts_for_checkout_updated(
+ new_transaction, discounts, manager
+ )
if transaction_event:
cls.create_transaction_event(transaction_event, new_transaction, user, app)
return TransactionCreate(transaction=new_transaction)
+def get_transaction_item(id: str) -> payment_models.TransactionItem:
+ """Get transaction based on global ID.
+
+ The transactions created before 3.13 were using the `id` field as a graphql ID.
+ From 3.13, the `token` is used as a graphql ID. All transactionItems created
+ before 3.13 will use an `int` id as an identification.
+ """
+ _, db_id = from_global_id_or_error(
+ global_id=id, only_type=TransactionItem, raise_error=True
+ )
+ if db_id.isdigit():
+ query_params = {"id": db_id, "use_old_id": True}
+ else:
+ query_params = {"token": db_id}
+ instance = payment_models.TransactionItem.objects.filter(**query_params).first()
+ if not instance:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ f"Couldn't resolve to a node: {id}",
+ code=TransactionUpdateErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+ return instance
+
+
class TransactionUpdate(TransactionCreate):
transaction = graphene.Field(TransactionItem)
@@ -1113,6 +1168,7 @@ class TransactionUpdate(TransactionCreate):
transaction_data: dict,
user: Optional["User"],
app: Optional["App"],
+ info: ResolveInfo,
):
money_data = cls.get_money_data_from_input(transaction_data)
psp_reference = transaction_data.get(
@@ -1145,6 +1201,10 @@ class TransactionUpdate(TransactionCreate):
if instance.order_id:
order = cast(order_models.Order, instance.order)
cls.update_order(order, money_data, psp_reference)
+ if instance.checkout_id and money_data:
+ discounts = load_discounts(info.context)
+ manager = get_plugin_manager_promise(info.context).get()
+ transaction_amounts_for_checkout_updated(instance, discounts, manager)
@classmethod
def update_order(
@@ -1183,7 +1243,7 @@ class TransactionUpdate(TransactionCreate):
):
app = get_app_promise(info.context).get()
user = info.context.user
- instance = cls.get_node_or_error(info, id, only_type=TransactionItem)
+ instance = get_transaction_item(id)
cls.check_can_update(
transaction=instance,
@@ -1194,7 +1254,7 @@ class TransactionUpdate(TransactionCreate):
if transaction:
cls.validate_transaction_input(instance, transaction)
cls.cleanup_metadata_data(transaction)
- cls.update_transaction(instance, transaction, user, app)
+ cls.update_transaction(instance, transaction, user, app, info)
if transaction_event:
cls.create_transaction_event(transaction_event, instance, user, app)
@@ -1315,12 +1375,13 @@ class TransactionRequestAction(BaseMutation):
id = data["id"]
action_type = data["action_type"]
action_value = data.get("amount")
- transaction = cls.get_node_or_error(info, id, only_type=TransactionItem)
- channel_slug = (
- transaction.order.channel.slug
- if transaction.order_id
- else transaction.checkout.channel.slug
- )
+ transaction = get_transaction_item(id)
+ if transaction.order_id:
+ order = cast(Order, transaction.order)
+ channel_slug = order.channel.slug
+ else:
+ checkout = cast(Checkout, transaction.checkout)
+ channel_slug = checkout.channel.slug
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
action_kwargs = {
@@ -1427,8 +1488,7 @@ class TransactionEventReport(ModelMutation):
):
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)
+ transaction = get_transaction_item(id)
if not check_if_requestor_has_access(
transaction=transaction, user=user, app=app
@@ -1521,6 +1581,12 @@ class TransactionEventReport(ModelMutation):
"search_vector",
]
)
+ if transaction.checkout_id:
+ discounts = load_discounts(info.context)
+ manager = get_plugin_manager_promise(info.context).get()
+ transaction_amounts_for_checkout_updated(
+ transaction, discounts, manager
+ )
return cls(
already_processed=already_processed,
@@ -1528,3 +1594,493 @@ class TransactionEventReport(ModelMutation):
transaction_event=transaction_event,
errors=[],
)
+
+
+class PaymentGatewayConfig(graphene.ObjectType):
+ id = graphene.String(required=True, description="The app identifier.")
+ data = graphene.Field(
+ JSON, description="The JSON data required to initialize the payment gateway."
+ )
+ errors = common_types.NonNullList(common_types.PaymentGatewayConfigError)
+
+
+class PaymentGatewayToInitialize(BaseInputObjectType):
+ id = graphene.String(
+ required=True,
+ description="The identifier of the payment gateway app to initialize.",
+ )
+ data = graphene.Field(
+ JSON, description="The data that will be passed to the payment gateway."
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+
+
+class TransactionSessionBase(BaseMutation):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def clean_source_object(
+ cls,
+ info,
+ id,
+ incorrect_type_error_code: str,
+ not_found_error: str,
+ manager: "PluginsManager",
+ discounts: Optional[Iterable["DiscountInfo"]],
+ ) -> Union[checkout_models.Checkout, order_models.Order]:
+ source_object_type, source_object_id = from_global_id_or_error(
+ id, raise_error=False
+ )
+ if not source_object_type or not source_object_id:
+ raise GraphQLError(f"Couldn't resolve id: {id}.")
+
+ if source_object_type not in ["Checkout", "Order"]:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Must receive a `Checkout` or `Order` id.",
+ code=incorrect_type_error_code,
+ )
+ }
+ )
+ source_object: Optional[Union[checkout_models.Checkout, order_models.Order]]
+ if source_object_type == "Checkout":
+ source_object = (
+ checkout_models.Checkout.objects.select_related("channel")
+ .prefetch_related("payment_transactions")
+ .filter(pk=source_object_id)
+ .first()
+ )
+ if source_object:
+ lines, _ = fetch_checkout_lines(source_object)
+ discounts = discounts or []
+ checkout_info = fetch_checkout_info(
+ source_object, lines, discounts, manager
+ )
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, manager, lines, discounts=discounts
+ )
+ source_object = checkout_info.checkout
+ else:
+ source_object = (
+ order_models.Order.objects.select_related("channel")
+ .prefetch_related("payment_transactions")
+ .filter(pk=source_object_id)
+ .first()
+ )
+
+ if not source_object:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "`Order` or `Checkout` not found.",
+ code=not_found_error,
+ )
+ }
+ )
+ return source_object
+
+ @classmethod
+ def get_amount(
+ cls,
+ source_object: Union[checkout_models.Checkout, order_models.Order],
+ input_amount: Optional[Decimal],
+ ) -> Decimal:
+ if input_amount is not None:
+ return input_amount
+ amount: Decimal = source_object.total_gross_amount
+ transactions = source_object.payment_transactions.all()
+ for transaction_item in transactions:
+ amount_to_reduce = transaction_item.authorized_value
+ if amount_to_reduce < transaction_item.charged_value:
+ amount_to_reduce = transaction_item.charged_value
+ amount -= amount_to_reduce
+ amount -= transaction_item.authorize_pending_value
+ amount -= transaction_item.charge_pending_value
+
+ return amount if amount >= Decimal(0) else Decimal(0)
+
+
+class PaymentGatewayInitialize(TransactionSessionBase):
+ gateway_configs = common_types.NonNullList(PaymentGatewayConfig)
+
+ class Arguments:
+ id = graphene.ID(
+ description="The ID of the checkout or order.",
+ required=True,
+ )
+ amount = graphene.Argument(
+ PositiveDecimal,
+ description=(
+ "The amount requested for initializing the payment gateway. "
+ "If not provided, the difference between checkout.total - "
+ "transactions that are already processed will be send."
+ ),
+ )
+ payment_gateways = graphene.List(
+ graphene.NonNull(PaymentGatewayToInitialize),
+ description="List of payment gateways to initialize.",
+ required=False,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+ description = (
+ "Initializes a payment gateway session. It triggers the webhook "
+ "`PAYMENT_GATEWAY_INITIALIZE_SESSION`, to the requested `paymentGateways`. "
+ "If `paymentGateways` is not provided, the webhook will be send to all "
+ "subscribed payment gateways." + ADDED_IN_313 + PREVIEW_FEATURE
+ )
+ error_type_class = common_types.PaymentGatewayInitializeError
+
+ @classmethod
+ def prepare_response(
+ cls,
+ payment_gateways_input: list[PaymentGatewayData],
+ payment_gateways_response: list[PaymentGatewayData],
+ ) -> list[PaymentGatewayConfig]:
+ response = []
+ payment_gateways_response_dict = {
+ gateway.app_identifier: gateway for gateway in payment_gateways_response
+ }
+
+ payment_gateways_input_dict = (
+ {gateway.app_identifier: gateway for gateway in payment_gateways_input}
+ if payment_gateways_input
+ else payment_gateways_response_dict
+ )
+ for identifier in payment_gateways_input_dict:
+ app_identifier = identifier
+ payment_gateway_response = payment_gateways_response_dict.get(identifier)
+ if payment_gateway_response:
+ response_data = payment_gateway_response.data
+ errors = []
+ if payment_gateway_response.error:
+ code = common_types.PaymentGatewayConfigErrorCode.INVALID.value
+ errors = [
+ {
+ "field": "id",
+ "message": payment_gateway_response.error,
+ "code": code,
+ }
+ ]
+
+ else:
+ response_data = None
+ code = common_types.PaymentGatewayConfigErrorCode.NOT_FOUND.value
+ msg = (
+ "Active app with `HANDLE_PAYMENT` permissions or "
+ "app webhook not found."
+ )
+ errors = [
+ {
+ "field": "id",
+ "message": msg,
+ "code": code,
+ }
+ ]
+ data_to_return = response_data.get("data") if response_data else None
+ response.append(
+ PaymentGatewayConfig(
+ id=app_identifier, data=data_to_return, errors=errors
+ )
+ )
+ return response
+
+ @classmethod
+ def perform_mutation(cls, root, info, *, id, amount=None, payment_gateways=None):
+ discounts = load_discounts(info.context)
+ manager = get_plugin_manager_promise(info.context).get()
+ source_object = cls.clean_source_object(
+ info,
+ id,
+ PaymentGatewayInitializeErrorCode.INVALID.value,
+ PaymentGatewayInitializeErrorCode.NOT_FOUND.value,
+ discounts=discounts,
+ manager=manager,
+ )
+ payment_gateways_data = []
+ if payment_gateways:
+ payment_gateways_data = [
+ PaymentGatewayData(
+ app_identifier=gateway["id"], data=gateway.get("data")
+ )
+ for gateway in payment_gateways
+ ]
+ amount = cls.get_amount(source_object, amount)
+ response_data = manager.payment_gateway_initialize_session(
+ amount, payment_gateways_data, source_object
+ )
+ return cls(
+ gateway_configs=cls.prepare_response(payment_gateways_data, response_data),
+ errors=[],
+ )
+
+
+class TransactionInitialize(TransactionSessionBase):
+ transaction = graphene.Field(
+ TransactionItem, description="The initialized transaction."
+ )
+ transaction_event = graphene.Field(
+ TransactionEvent,
+ description="The event created for the initialized transaction.",
+ )
+ data = graphene.Field(
+ JSON, description="The JSON data required to finalize the payment."
+ )
+
+ class Arguments:
+ id = graphene.ID(
+ description="The ID of the checkout or order.",
+ required=True,
+ )
+ amount = graphene.Argument(
+ PositiveDecimal,
+ description=(
+ "The amount requested for initializing the payment gateway. "
+ "If not provided, the difference between checkout.total - "
+ "transactions that are already processed will be send."
+ ),
+ )
+ action = graphene.Argument(
+ TransactionFlowStrategyEnum,
+ description=(
+ "The expected action called for the transaction. By default, the "
+ "`channel.defaultTransactionFlowStrategy` will be used. The field "
+ "can be used only by app that has `HANDLE_PAYMENTS` permission."
+ ),
+ )
+ payment_gateway = graphene.Argument(
+ PaymentGatewayToInitialize,
+ description="Payment gateway used to initialize the transaction.",
+ required=True,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+ description = (
+ "Initializes a transaction session. It triggers the webhook "
+ "`TRANSACTION_INITIALIZE_SESSION`, to the requested `paymentGateways`. "
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ )
+ error_type_class = common_types.TransactionInitializeError
+
+ @classmethod
+ def clean_action(cls, info, action: Optional[str], channel: "Channel"):
+ if not action:
+ return channel.default_transaction_flow_strategy
+ app = get_app_promise(info.context).get()
+ if not app or not app.has_perm(PaymentPermissions.HANDLE_PAYMENTS):
+ raise PermissionDenied(permissions=[PaymentPermissions.HANDLE_PAYMENTS])
+ return action
+
+ @classmethod
+ def clean_app_from_payment_gateway(cls, payment_gateway: PaymentGatewayData) -> App:
+ app = App.objects.filter(identifier=payment_gateway.app_identifier).first()
+ if not app:
+ raise ValidationError(
+ {
+ "payment_gateway": ValidationError(
+ message="App with provided identifier not found.",
+ code=TransactionInitializeErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+ return app
+
+ @classmethod
+ def perform_mutation(
+ cls, root, info, *, id, payment_gateway, amount=None, action=None
+ ):
+ discounts = load_discounts(info.context)
+ manager = get_plugin_manager_promise(info.context).get()
+ payment_gateway_data = PaymentGatewayData(
+ app_identifier=payment_gateway["id"], data=payment_gateway.get("data")
+ )
+ source_object = cls.clean_source_object(
+ info,
+ id,
+ TransactionInitializeErrorCode.INVALID.value,
+ TransactionInitializeErrorCode.NOT_FOUND.value,
+ discounts=discounts,
+ manager=manager,
+ )
+ action = cls.clean_action(info, action, source_object.channel)
+
+ amount = cls.get_amount(
+ source_object,
+ amount,
+ )
+ app = cls.clean_app_from_payment_gateway(payment_gateway_data)
+ transaction, event, data = handle_transaction_initialize_session(
+ source_object=source_object,
+ payment_gateway=payment_gateway_data,
+ amount=amount,
+ action=action,
+ app=app,
+ manager=manager,
+ discounts=discounts,
+ )
+ return cls(transaction=transaction, transaction_event=event, data=data)
+
+
+class TransactionProcess(BaseMutation):
+ transaction = graphene.Field(
+ TransactionItem, description="The processed transaction."
+ )
+ transaction_event = graphene.Field(
+ TransactionEvent,
+ description="The event created for the processed transaction.",
+ )
+ data = graphene.Field(
+ JSON, description="The json data required to finalize the payment."
+ )
+
+ class Arguments:
+ id = graphene.ID(
+ description="The ID of the transaction to process.",
+ required=True,
+ )
+ data = graphene.Argument(
+ JSON, description="The data that will be passed to the payment gateway."
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PAYMENTS
+ description = (
+ "Processes a transaction session. It triggers the webhook "
+ "`TRANSACTION_PROCESS_SESSION`, to the assigned `paymentGateways`. "
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ )
+ error_type_class = common_types.TransactionProcessError
+
+ @classmethod
+ def get_action(cls, event: payment_models.TransactionEvent, channel: "Channel"):
+ if event.type == TransactionEventType.AUTHORIZATION_REQUEST:
+ return TransactionFlowStrategy.AUTHORIZATION
+ elif event.type == TransactionEventType.CHARGE_REQUEST:
+ return TransactionFlowStrategy.CHARGE
+
+ return channel.default_transaction_flow_strategy
+
+ @classmethod
+ def get_source_object(
+ cls, transaction_item: payment_models.TransactionItem
+ ) -> Union[checkout_models.Checkout, order_models.Order]:
+ if transaction_item.checkout_id:
+ checkout = cast(checkout_models.Checkout, transaction_item.checkout)
+ return checkout
+ if transaction_item.order_id:
+ order = cast(order_models.Order, transaction_item.order)
+ return order
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Transaction doesn't have attached order or checkout.",
+ code=TransactionProcessErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ @classmethod
+ def get_request_event(cls, events: QuerySet) -> payment_models.TransactionEvent:
+ """Get event with details of requested action.
+
+ This searches for a request event with the appropriate type and
+ include_in_calculations set to false. Request events created from
+ transactionInitialize have their include_in_calculation set to false by default.
+ """
+ for event in events:
+ if (
+ event.type
+ in [
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_REQUEST,
+ ]
+ and not event.include_in_calculations
+ ):
+ return event
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Missing call of `transactionInitialize` mutation.",
+ code=TransactionProcessErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ @classmethod
+ def get_already_processed_event(cls, events) -> Optional[TransactionEvent]:
+ for event in events:
+ if (
+ event.type in get_final_session_statuses()
+ and event.include_in_calculations
+ ):
+ return event
+ return None
+
+ @classmethod
+ def clean_payment_app(cls, transaction_item: payment_models.TransactionItem) -> App:
+ if not transaction_item.app_identifier:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Transaction doesn't have attached app that could process the "
+ "request.",
+ code=TransactionProcessErrorCode.MISSING_PAYMENT_APP_RELATION.value,
+ )
+ }
+ )
+ app = App.objects.filter(identifier=transaction_item.app_identifier).first()
+ if not app:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Payment app attached to the transaction, doesn't exist.",
+ code=TransactionProcessErrorCode.MISSING_PAYMENT_APP.value,
+ )
+ }
+ )
+ return app
+
+ @classmethod
+ def perform_mutation(cls, root, info, *, id, data=None):
+ transaction_item = cls.get_node_or_error(
+ info, id, only_type="TransactionItem", field="token"
+ )
+ transaction_item = cast(payment_models.TransactionItem, transaction_item)
+ events = transaction_item.events.all()
+ if processed_event := cls.get_already_processed_event(events):
+ return cls(
+ transaction=transaction_item,
+ transaction_event=processed_event,
+ data=None,
+ )
+ request_event = cls.get_request_event(events)
+ source_object = cls.get_source_object(transaction_item)
+ app = cls.clean_payment_app(transaction_item)
+ app_identifier = app.identifier
+ app_identifier = cast(str, app_identifier)
+ action = cls.get_action(request_event, source_object.channel)
+ manager = get_plugin_manager_promise(info.context).get()
+ discounts = load_discounts(info.context)
+ event, data = handle_transaction_process_session(
+ transaction_item=transaction_item,
+ source_object=source_object,
+ payment_gateway=PaymentGatewayData(
+ app_identifier=app_identifier, data=data
+ ),
+ app=app,
+ action=action,
+ manager=manager,
+ request_event=request_event,
+ discounts=discounts,
+ )
+
+ transaction_item.refresh_from_db()
+ return cls(transaction=transaction_item, transaction_event=event, data=data)
diff --git a/saleor/graphql/payment/schema.py b/saleor/graphql/payment/schema.py
index f7c859c9da..c179a69583 100644
--- a/saleor/graphql/payment/schema.py
+++ b/saleor/graphql/payment/schema.py
@@ -11,11 +11,14 @@ from .filters import PaymentFilterInput
from .mutations import (
PaymentCapture,
PaymentCheckBalance,
+ PaymentGatewayInitialize,
PaymentInitialize,
PaymentRefund,
PaymentVoid,
TransactionCreate,
TransactionEventReport,
+ TransactionInitialize,
+ TransactionProcess,
TransactionRequestAction,
TransactionUpdate,
)
@@ -84,3 +87,7 @@ class PaymentMutations(graphene.ObjectType):
transaction_update = TransactionUpdate.Field()
transaction_request_action = TransactionRequestAction.Field()
transaction_event_report = TransactionEventReport.Field()
+
+ payment_gateway_initialize = PaymentGatewayInitialize.Field()
+ transaction_initialize = TransactionInitialize.Field()
+ transaction_process = TransactionProcess.Field()
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
new file mode 100644
index 0000000000..271edf5a31
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
@@ -0,0 +1,777 @@
+from decimal import Decimal
+
+import mock
+
+from .....checkout.calculations import fetch_checkout_data
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....payment.interface import PaymentGatewayData
+from ....core.enums import PaymentGatewayConfigErrorCode
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+
+PAYMENT_GATEWAY_INITIALIZE = """
+mutation PaymentGatewayInitialize(
+ $id: ID!,
+ $amount: PositiveDecimal,
+ $paymentGateways: [PaymentGatewayToInitialize!]
+) {
+ paymentGatewayInitialize(
+ id: $id
+ amount: $amount
+ paymentGateways: $paymentGateways
+ ) {
+ gatewayConfigs {
+ id
+ data
+ errors {
+ field
+ message
+ code
+ }
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_checkout_without_payment_gateways(
+ mocked_initialize, user_api_client, checkout_with_prices, plugins_manager
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ checkout = checkout_info.checkout
+ expected_app_identifier = "app.id"
+ expected_data = {"json": "data"}
+ expected_response = {"data": expected_data}
+
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+ ]
+
+ variables = {"id": to_global_id_or_none(checkout), "paymentGateways": None}
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": expected_data,
+ "errors": [],
+ }
+ mocked_initialize.assert_called_once_with(checkout.total.gross.amount, [], checkout)
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_order_without_payment_gateways(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "app.id"
+ expected_data = {"json": "data"}
+ expected_response = {"data": expected_data}
+
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+ ]
+
+ variables = {"id": to_global_id_or_none(order), "paymentGateways": None}
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": expected_data,
+ "errors": [],
+ }
+
+ mocked_initialize.assert_called_once_with(order.total.gross.amount, [], order)
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_checkout_with_payment_gateways(
+ mocked_initialize, user_api_client, checkout_with_prices, plugins_manager
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ checkout = checkout_info.checkout
+
+ expected_app_identifier = "app.id"
+ expected_data = {"json": "data"}
+ expected_input_data = {"input": "json"}
+ expected_response = {"data": expected_data}
+
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+ ]
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "paymentGateways": [
+ {"id": expected_app_identifier, "data": expected_input_data}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": expected_data,
+ "errors": [],
+ }
+
+ mocked_initialize.assert_called_once_with(
+ checkout.total.gross.amount,
+ [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_input_data
+ )
+ ],
+ checkout,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_order_with_payment_gateways(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "app.id"
+ expected_data = {"json": "data"}
+ expected_input_data = {"input": "json"}
+ expected_response = {"data": expected_data}
+
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+ ]
+
+ variables = {
+ "id": to_global_id_or_none(order),
+ "paymentGateways": [
+ {"id": expected_app_identifier, "data": expected_input_data}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": expected_data,
+ "errors": [],
+ }
+
+ mocked_initialize.assert_called_once_with(
+ order.total.gross.amount,
+ [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_input_data
+ )
+ ],
+ order,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_checkout_with_payment_gateways_and_amount(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_app_identifier = "app.id"
+ expected_data = {"json": "data"}
+ expected_response = {"data": expected_data}
+ expected_input_data = {"input": "json"}
+ excpected_amount = Decimal(30)
+
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+ ]
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "amount": excpected_amount,
+ "paymentGateways": [
+ {"id": expected_app_identifier, "data": expected_input_data}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": expected_data,
+ "errors": [],
+ }
+
+ mocked_initialize.assert_called_once_with(
+ excpected_amount,
+ [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_input_data
+ )
+ ],
+ checkout,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_order_with_payment_gateways_and_amount(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "app.id"
+ expected_data = {"json": "data"}
+ expected_response = {"data": expected_data}
+ expected_input_data = {"input": "json"}
+ excpected_amount = Decimal(30)
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+ ]
+ variables = {
+ "id": to_global_id_or_none(order),
+ "amount": excpected_amount,
+ "paymentGateways": [
+ {"id": expected_app_identifier, "data": expected_input_data}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": expected_data,
+ "errors": [],
+ }
+
+ mocked_initialize.assert_called_once_with(
+ excpected_amount,
+ [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_input_data
+ )
+ ],
+ order,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_checkout_with_payment_gateways_returns_error(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_app_identifier = "app.id"
+ expected_error_msg = "Cannot fetch."
+ expected_input_data = {"input": "json"}
+ excpected_amount = Decimal(30)
+
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=None, error=expected_error_msg
+ )
+ ]
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "amount": excpected_amount,
+ "paymentGateways": [
+ {"id": expected_app_identifier, "data": expected_input_data}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": None,
+ "errors": [
+ {
+ "field": "id",
+ "message": expected_error_msg,
+ "code": PaymentGatewayConfigErrorCode.INVALID.name,
+ }
+ ],
+ }
+
+ mocked_initialize.assert_called_once_with(
+ excpected_amount,
+ [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_input_data
+ )
+ ],
+ checkout,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_order_with_payment_gateways_returns_error(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "app.id"
+
+ expected_input_data = {"input": "json"}
+ excpected_amount = Decimal(30)
+ expected_error_msg = "Cannot fetch."
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=None, error=expected_error_msg
+ )
+ ]
+ variables = {
+ "id": to_global_id_or_none(order),
+ "amount": excpected_amount,
+ "paymentGateways": [
+ {"id": expected_app_identifier, "data": expected_input_data}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": None,
+ "errors": [
+ {
+ "field": "id",
+ "message": expected_error_msg,
+ "code": PaymentGatewayConfigErrorCode.INVALID.name,
+ }
+ ],
+ }
+
+ mocked_initialize.assert_called_once_with(
+ excpected_amount,
+ [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_input_data
+ )
+ ],
+ order,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_checkout_with_missing_payment_gateway(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_app_identifier = "app.id"
+ expected_error_msg = (
+ "Active app with `HANDLE_PAYMENT` permissions or " "app webhook not found."
+ )
+ expected_input_data = {"input": "json"}
+ excpected_amount = Decimal(30)
+
+ mocked_initialize.return_value = []
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "amount": excpected_amount,
+ "paymentGateways": [
+ {"id": expected_app_identifier, "data": expected_input_data}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": None,
+ "errors": [
+ {
+ "field": "id",
+ "message": expected_error_msg,
+ "code": PaymentGatewayConfigErrorCode.NOT_FOUND.name,
+ }
+ ],
+ }
+
+ mocked_initialize.assert_called_once_with(
+ excpected_amount,
+ [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_input_data
+ )
+ ],
+ checkout,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_order_with_missing_payment_gateway(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "app.id"
+
+ expected_input_data = {"input": "json"}
+ excpected_amount = Decimal(30)
+ expected_error_msg = (
+ "Active app with `HANDLE_PAYMENT` permissions or " "app webhook not found."
+ )
+ mocked_initialize.return_value = []
+ variables = {
+ "id": to_global_id_or_none(order),
+ "amount": excpected_amount,
+ "paymentGateways": [
+ {"id": expected_app_identifier, "data": expected_input_data}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": None,
+ "errors": [
+ {
+ "field": "id",
+ "message": expected_error_msg,
+ "code": PaymentGatewayConfigErrorCode.NOT_FOUND.name,
+ }
+ ],
+ }
+
+ mocked_initialize.assert_called_once_with(
+ excpected_amount,
+ [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_input_data
+ )
+ ],
+ order,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_checkout_with_multiple_payment_gateways(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ checkout = checkout_with_prices
+ excpected_amount = Decimal(30)
+ first_expected_app_identifier = "app.id"
+ first_expected_data = {"json": "data"}
+ first_expected_response = {"data": first_expected_data}
+ first_expected_input_data = {"input": "json"}
+
+ second_expected_input_data = {"input": "json2"}
+ second_error_msg = "Cannot fetch"
+ second_expected_app_identifier = "app.id2"
+
+ third_expected_app_identifier = "app.id3"
+ third_expected_input_data = {"input": "json3"}
+
+ expected_error_msg = (
+ "Active app with `HANDLE_PAYMENT` permissions or " "app webhook not found."
+ )
+
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=first_expected_app_identifier, data=first_expected_response
+ ),
+ PaymentGatewayData(
+ app_identifier=second_expected_app_identifier, error=second_error_msg
+ ),
+ ]
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "amount": excpected_amount,
+ "paymentGateways": [
+ {"id": first_expected_app_identifier, "data": first_expected_input_data},
+ {"id": second_expected_app_identifier, "data": second_expected_input_data},
+ {"id": third_expected_app_identifier, "data": third_expected_input_data},
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 3
+ configs = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]
+ first_gateway = [c for c in configs if c["id"] == first_expected_app_identifier][0]
+ second_gateway = [c for c in configs if c["id"] == second_expected_app_identifier][
+ 0
+ ]
+ third_gateway = [c for c in configs if c["id"] == third_expected_app_identifier][0]
+
+ assert first_gateway == {
+ "id": first_expected_app_identifier,
+ "data": first_expected_data,
+ "errors": [],
+ }
+
+ assert second_gateway == {
+ "id": second_expected_app_identifier,
+ "data": None,
+ "errors": [
+ {
+ "field": "id",
+ "message": second_error_msg,
+ "code": PaymentGatewayConfigErrorCode.INVALID.name,
+ }
+ ],
+ }
+ assert third_gateway == {
+ "id": third_expected_app_identifier,
+ "data": None,
+ "errors": [
+ {
+ "field": "id",
+ "message": expected_error_msg,
+ "code": PaymentGatewayConfigErrorCode.NOT_FOUND.name,
+ }
+ ],
+ }
+ mocked_initialize.assert_called_once_with(
+ excpected_amount,
+ [
+ PaymentGatewayData(
+ app_identifier=first_expected_app_identifier,
+ data=first_expected_input_data,
+ ),
+ PaymentGatewayData(
+ app_identifier=second_expected_app_identifier,
+ data=second_expected_input_data,
+ ),
+ PaymentGatewayData(
+ app_identifier=third_expected_app_identifier,
+ data=third_expected_input_data,
+ ),
+ ],
+ checkout,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_for_order_with_multiple_payment_gateways(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ excpected_amount = Decimal(30)
+ first_expected_app_identifier = "app.id"
+ first_expected_data = {"json": "data"}
+ first_expected_response = {"data": first_expected_data}
+ first_expected_input_data = {"input": "json"}
+
+ second_expected_input_data = {"input": "json2"}
+ second_error_msg = "Cannot fetch"
+ second_expected_app_identifier = "app.id2"
+
+ third_expected_app_identifier = "app.id3"
+ third_expected_input_data = {"input": "json3"}
+
+ expected_error_msg = (
+ "Active app with `HANDLE_PAYMENT` permissions or " "app webhook not found."
+ )
+
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=first_expected_app_identifier, data=first_expected_response
+ ),
+ PaymentGatewayData(
+ app_identifier=second_expected_app_identifier, error=second_error_msg
+ ),
+ ]
+
+ variables = {
+ "id": to_global_id_or_none(order),
+ "amount": excpected_amount,
+ "paymentGateways": [
+ {"id": first_expected_app_identifier, "data": first_expected_input_data},
+ {"id": second_expected_app_identifier, "data": second_expected_input_data},
+ {"id": third_expected_app_identifier, "data": third_expected_input_data},
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 3
+ configs = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]
+ first_gateway = [c for c in configs if c["id"] == first_expected_app_identifier][0]
+ second_gateway = [c for c in configs if c["id"] == second_expected_app_identifier][
+ 0
+ ]
+ third_gateway = [c for c in configs if c["id"] == third_expected_app_identifier][0]
+
+ assert first_gateway == {
+ "id": first_expected_app_identifier,
+ "data": first_expected_data,
+ "errors": [],
+ }
+
+ assert second_gateway == {
+ "id": second_expected_app_identifier,
+ "data": None,
+ "errors": [
+ {
+ "field": "id",
+ "message": second_error_msg,
+ "code": PaymentGatewayConfigErrorCode.INVALID.name,
+ }
+ ],
+ }
+ assert third_gateway == {
+ "id": third_expected_app_identifier,
+ "data": None,
+ "errors": [
+ {
+ "field": "id",
+ "message": expected_error_msg,
+ "code": PaymentGatewayConfigErrorCode.NOT_FOUND.name,
+ }
+ ],
+ }
+ mocked_initialize.assert_called_once_with(
+ excpected_amount,
+ [
+ PaymentGatewayData(
+ app_identifier=first_expected_app_identifier,
+ data=first_expected_input_data,
+ ),
+ PaymentGatewayData(
+ app_identifier=second_expected_app_identifier,
+ data=second_expected_input_data,
+ ),
+ PaymentGatewayData(
+ app_identifier=third_expected_app_identifier,
+ data=third_expected_input_data,
+ ),
+ ],
+ order,
+ )
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index 76a2c469ac..84d59c025b 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -2,7 +2,11 @@ from decimal import Decimal
import graphene
import pytest
+from mock import patch
+from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
+from .....checkout.calculations import fetch_checkout_data
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....order import OrderAuthorizeStatus, OrderEvents
from .....order.utils import update_order_authorize_data, update_order_charge_data
from .....payment import TransactionEventStatus, TransactionEventType
@@ -339,6 +343,10 @@ def test_transaction_create_for_checkout_by_app(
)
# then
+ checkout_with_items.refresh_from_db()
+ assert checkout_with_items.charge_status == CheckoutChargeStatus.NONE
+ assert checkout_with_items.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
transaction = checkout_with_items.payment_transactions.first()
content = get_graphql_content(response)
data = content["data"]["transactionCreate"]["transaction"]
@@ -1021,6 +1029,9 @@ def test_transaction_create_for_checkout_by_staff(
)
# then
+ checkout_with_items.refresh_from_db()
+ assert checkout_with_items.charge_status == CheckoutChargeStatus.NONE
+ assert checkout_with_items.authorize_status == CheckoutAuthorizeStatus.PARTIAL
transaction = checkout_with_items.payment_transactions.first()
content = get_graphql_content(response)
data = content["data"]["transactionCreate"]["transaction"]
@@ -1043,6 +1054,61 @@ def test_transaction_create_for_checkout_by_staff(
assert transaction.user == staff_api_client.user
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_create_for_checkout_fully_paid(
+ mocked_checkout_fully_paid,
+ checkout_with_prices,
+ permission_manage_payments,
+ staff_api_client,
+ plugins_manager,
+):
+ # given
+ status = "Authorized for 10$"
+ type = "Credit Card"
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.VOID.name,
+ ]
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ "amountCharged": {
+ "amount": checkout_info.checkout.total.gross.amount,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+
+ mocked_checkout_fully_paid.assert_called_once_with(checkout)
+
+
@pytest.mark.parametrize(
"amount_field_name, amount_db_field",
[
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index 3365c80bfb..393f75605c 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -1,8 +1,12 @@
from decimal import Decimal
from unittest.mock import patch
+import graphene
from django.utils import timezone
+from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
+from .....checkout.calculations import fetch_checkout_data
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....payment import TransactionEventType
from .....payment.models import TransactionEvent
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
@@ -66,7 +70,7 @@ def test_transaction_event_report_by_app(
message = "Sucesfull charge"
psp_reference = "111-abc"
amount = Decimal("11.00")
- transaction_id = to_global_id_or_none(transaction)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
variables = {
"id": transaction_id,
"type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
@@ -141,7 +145,7 @@ def test_transaction_event_report_by_user(
message = "Sucesfull charge"
psp_reference = "111-abc"
amount = Decimal("11.00")
- transaction_id = to_global_id_or_none(transaction)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
variables = {
"id": transaction_id,
"type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
@@ -209,7 +213,9 @@ def test_transaction_event_report_no_permission(
app_api_client,
):
# given
- transaction_id = to_global_id_or_none(transaction_item_created_by_app)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_app.token
+ )
variables = {
"id": transaction_id,
"type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
@@ -258,7 +264,9 @@ def test_transaction_event_report_called_by_non_app_owner(
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)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_app.token
+ )
variables = {
"id": transaction_id,
"type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
@@ -298,7 +306,9 @@ 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)
+ transaction_id = graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_app.token
+ )
variables = {
"id": transaction_id,
"type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
@@ -352,7 +362,7 @@ def test_transaction_event_report_event_already_exists(
already_existing_event = transaction.events.filter(
type=TransactionEventType.CHARGE_SUCCESS
).get()
- transaction_id = to_global_id_or_none(transaction)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
variables = {
"id": transaction_id,
"type": event_type.name,
@@ -429,7 +439,7 @@ def test_transaction_event_report_incorrect_amount_for_already_existing(
transaction.events.update(
psp_reference=psp_reference,
)
- transaction_id = to_global_id_or_none(transaction)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
variables = {
"id": transaction_id,
@@ -510,7 +520,7 @@ def test_transaction_event_report_calls_amount_recalculations(
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)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
variables = {
"id": transaction_id,
"type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
@@ -577,7 +587,7 @@ def test_transaction_event_updates_order_total_charged(
order_id=order.pk,
charged_value=current_charged_value,
)
- transaction_id = to_global_id_or_none(transaction)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
variables = {
"id": transaction_id,
"type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
@@ -633,7 +643,7 @@ def test_transaction_event_updates_order_total_authorized(
order_id=order.pk,
authorized_value=order.total.gross.amount,
)
- transaction_id = to_global_id_or_none(transaction)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
variables = {
"id": transaction_id,
"type": TransactionEventTypeEnum.AUTHORIZATION_SUCCESS.name,
@@ -689,7 +699,7 @@ def test_transaction_event_updates_search_vector(
order_id=order.pk,
authorized_value=order.total.gross.amount,
)
- transaction_id = to_global_id_or_none(transaction)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
variables = {
"id": transaction_id,
"type": TransactionEventTypeEnum.AUTHORIZATION_SUCCESS.name,
@@ -745,7 +755,7 @@ def test_transaction_event_report_authorize_event_already_exists(
transaction.events.update(
psp_reference="Different psp reference",
)
- transaction_id = to_global_id_or_none(transaction)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
variables = {
"id": transaction_id,
"type": event_type.name,
@@ -806,3 +816,417 @@ def test_transaction_event_report_authorize_event_already_exists(
).first()
assert event
assert event.include_in_calculations is False
+
+
+def test_transaction_event_updates_checkout_payment_statuses(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_items,
+):
+ # given
+ checkout = checkout_with_items
+ current_charged_value = Decimal("20")
+ psp_reference = "111-abc"
+ amount = Decimal("11.00")
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_item_generator(
+ app=app_api_client.app,
+ checkout_id=checkout.pk,
+ charged_value=current_charged_value,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ 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)
+ checkout.refresh_from_db()
+
+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_event_updates_checkout_full_paid_with_charged_amount(
+ mocked_fully_paid,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_items,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_item_generator(
+ app=app_api_client.app,
+ checkout_id=checkout.pk,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": checkout_info.checkout.total.gross.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)
+ checkout.refresh_from_db()
+
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_fully_paid.assert_called_once_with(checkout)
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_event_updates_checkout_full_paid_with_pending_charge_amount(
+ mocked_fully_paid,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_items,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_item_generator(
+ app=app_api_client.app,
+ checkout_id=checkout.pk,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_REQUEST.name,
+ "amount": checkout_info.checkout.total.gross.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)
+ checkout.refresh_from_db()
+
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ mocked_fully_paid.assert_called_once_with(checkout)
+
+
+def test_transaction_event_report_with_info_event(
+ 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 = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.INFO.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "time": event_time.isoformat(),
+ "externalUrl": external_url,
+ "message": message,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ time: $time
+ externalUrl: $externalUrl
+ message: $message
+ ) {
+ ...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.INFO).first()
+ assert event
+ assert event.psp_reference == psp_reference
+ assert event.type == TransactionEventTypeEnum.INFO.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
+
+
+def test_transaction_event_report_accepts_old_id_for_old_transaction(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ transaction = transaction_item_generator(
+ app=app_api_client.app, authorized_value=Decimal("10"), use_old_id=True
+ )
+ 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 = graphene.Node.to_global_id("TransactionItem", transaction.id)
+ 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_doesnt_accept_old_id_for_new_transaction(
+ 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, use_old_id=False
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+
+ 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.NOT_FOUND.name
+ assert error["field"] == "id"
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
new file mode 100644
index 0000000000..51b9ae45d0
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -0,0 +1,1186 @@
+from decimal import Decimal
+
+import mock
+import pytest
+
+from .....channel import TransactionFlowStrategy
+from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
+from .....checkout.calculations import fetch_checkout_data
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....core.prices import quantize_price
+from .....payment import TransactionEventType
+from .....payment.interface import (
+ PaymentGatewayData,
+ TransactionProcessActionData,
+ TransactionSessionData,
+)
+from ....channel.enums import TransactionFlowStrategyEnum
+from ....core.enums import TransactionInitializeErrorCode
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+TRANSACTION_INITIALIZE = """
+mutation TransactionInitialize(
+ $action: TransactionFlowStrategyEnum,
+ $amount: PositiveDecimal,
+ $id: ID!,
+ $paymentGateway: PaymentGatewayToInitialize!
+) {
+ transactionInitialize(
+ action: $action
+ amount: $amount
+ id: $id
+ paymentGateway: $paymentGateway
+ ) {
+ data
+ transaction {
+ id
+ authorizedAmount {
+ currency
+ amount
+ }
+ chargedAmount {
+ currency
+ amount
+ }
+ chargePendingAmount {
+ amount
+ currency
+ }
+ authorizePendingAmount {
+ amount
+ currency
+ }
+ }
+ transactionEvent {
+ amount {
+ currency
+ amount
+ }
+ type
+ createdBy {
+ ... on App {
+ id
+ }
+ }
+ pspReference
+ message
+ externalUrl
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
+def _assert_fields(
+ content,
+ source_object,
+ expected_amount,
+ expected_psp_reference,
+ response_event_type,
+ app_identifier,
+ mocked_initialize,
+ request_event_type=TransactionEventType.CHARGE_REQUEST,
+ action_type=TransactionFlowStrategy.CHARGE,
+ request_event_include_in_calculations=False,
+ authorized_value=Decimal(0),
+ charged_value=Decimal(0),
+ charge_pending_value=Decimal(0),
+ authorize_pending_value=Decimal(0),
+ returned_data=None,
+):
+ assert not content["data"]["transactionInitialize"]["errors"]
+ response_data = content["data"]["transactionInitialize"]
+ assert response_data["data"] == returned_data
+ transaction_data = response_data["transaction"]
+ transaction = source_object.payment_transactions.last()
+ assert transaction
+ assert (
+ quantize_price(
+ Decimal(transaction_data["authorizePendingAmount"]["amount"]),
+ source_object.currency,
+ )
+ == authorize_pending_value
+ == transaction.authorize_pending_value
+ )
+ assert (
+ quantize_price(
+ Decimal(transaction_data["authorizedAmount"]["amount"]),
+ source_object.currency,
+ )
+ == authorized_value
+ == transaction.authorized_value
+ )
+ assert (
+ quantize_price(
+ Decimal(transaction_data["chargePendingAmount"]["amount"]),
+ source_object.currency,
+ )
+ == charge_pending_value
+ == transaction.charge_pending_value
+ )
+
+ assert (
+ quantize_price(
+ Decimal(transaction_data["chargedAmount"]["amount"]), source_object.currency
+ )
+ == charged_value
+ )
+ assert charged_value == transaction.charged_value
+
+ assert response_data["transactionEvent"]
+ assert response_data["transactionEvent"]["type"] == response_event_type.upper()
+ assert (
+ quantize_price(
+ Decimal(response_data["transactionEvent"]["amount"]["amount"]),
+ source_object.currency,
+ )
+ == expected_amount
+ )
+
+ request_event = transaction.events.filter(type=request_event_type).first()
+ assert request_event
+
+ assert request_event.amount_value == expected_amount
+ assert (
+ request_event.include_in_calculations == request_event_include_in_calculations
+ )
+ assert request_event.psp_reference == expected_psp_reference
+ response_event = transaction.events.filter(type=response_event_type).first()
+ assert response_event
+ assert response_event.amount_value == expected_amount
+ assert response_event.include_in_calculations
+ assert response_event.psp_reference == expected_psp_reference
+
+ mocked_initialize.assert_called_with(
+ TransactionSessionData(
+ transaction=transaction,
+ source_object=source_object,
+ action=TransactionProcessActionData(
+ action_type=action_type,
+ amount=expected_amount,
+ currency=source_object.currency,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=app_identifier, data=None, error=None
+ ),
+ )
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_for_checkout_without_payment_gateway_data(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_amount = Decimal("10.00")
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = "CHARGE_SUCCESS"
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=expected_amount,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_for_order_without_payment_gateway_data(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_amount = Decimal("10.00")
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = "CHARGE_SUCCESS"
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(order),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=expected_amount,
+ returned_data=expected_response["data"],
+ )
+ order.refresh_from_db()
+ assert order.total_authorized_amount == Decimal(0)
+ assert order.total_charged_amount == expected_amount
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_with_pending_amount(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_amount = Decimal("10.00")
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_REQUEST.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_REQUEST,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charge_pending_value=expected_amount,
+ request_event_include_in_calculations=True,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_order_with_pending_amount(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_amount = Decimal("10.00")
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_REQUEST.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(order),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_REQUEST,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charge_pending_value=expected_amount,
+ request_event_include_in_calculations=True,
+ returned_data=expected_response["data"],
+ )
+
+ order.refresh_from_db()
+ assert order.total_authorized_amount == Decimal(0)
+ assert order.total_charged_amount == Decimal(0)
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_with_action_required_response(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_amount = Decimal("10.00")
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_ACTION_REQUIRED.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_ACTION_REQUIRED,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.NONE
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_order_with_action_required_response(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_amount = Decimal("10.00")
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_ACTION_REQUIRED.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(order),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_ACTION_REQUIRED,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ returned_data=expected_response["data"],
+ )
+
+ order.refresh_from_db()
+ assert order.total_authorized_amount == Decimal(0)
+ assert order.total_charged_amount == Decimal(0)
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_with_action_required_response_and_missing_psp_reference(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_amount = Decimal("10.00")
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_ACTION_REQUIRED.upper()
+ del expected_response["pspReference"]
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=expected_amount,
+ expected_psp_reference=None,
+ response_event_type=TransactionEventType.CHARGE_ACTION_REQUIRED,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.NONE
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_order_with_action_required_response_and_missing_psp_reference(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_amount = Decimal("10.00")
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_ACTION_REQUIRED.upper()
+ del expected_response["pspReference"]
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(order),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=expected_amount,
+ expected_psp_reference=None,
+ response_event_type=TransactionEventType.CHARGE_ACTION_REQUIRED,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ returned_data=expected_response["data"],
+ )
+
+ order.refresh_from_db()
+ assert order.total_authorized_amount == Decimal(0)
+ assert order.total_charged_amount == Decimal(0)
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_when_amount_is_not_provided(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=checkout.total_gross_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=checkout.total_gross_amount,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_order_when_amount_is_not_provided(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["amount"] = str(order.total_gross_amount)
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(order),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=order.total_gross_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=order.total_gross_amount,
+ returned_data=expected_response["data"],
+ )
+
+ order.refresh_from_db()
+ assert order.total_authorized_amount == Decimal(0)
+ assert order.total_charged_amount == order.total_gross_amount
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_order_with_transaction_when_amount_is_not_provided(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ expected_charged_amount = Decimal("10")
+ expected_authorized_amount = Decimal("3")
+ transaction_item_generator(
+ order_id=order.pk,
+ charged_value=expected_charged_amount,
+ authorized_value=expected_authorized_amount,
+ )
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["amount"] = str(
+ order.total_gross_amount - expected_charged_amount
+ )
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(order),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=order.total_gross_amount - expected_charged_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=order.total_gross_amount - expected_charged_amount,
+ returned_data=expected_response["data"],
+ )
+
+ order.refresh_from_db()
+ assert order.total_authorized_amount == expected_authorized_amount
+ assert order.total_charged_amount == order.total_gross_amount
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_with_transaction_when_amount_is_not_provided(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ checkout = checkout_info.checkout
+
+ expected_charged_amount = Decimal("10")
+ expected_authorized_amount = Decimal("3")
+ transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=expected_charged_amount,
+ authorized_value=expected_authorized_amount,
+ )
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["amount"] = str(
+ checkout.total_gross_amount - expected_charged_amount
+ )
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=checkout.total_gross_amount - expected_charged_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=checkout.total_gross_amount - expected_charged_amount,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_app_with_action_field_and_handle_payments(
+ mocked_initialize,
+ app_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+ permission_manage_payments,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+ app_api_client.app.permissions.set([permission_manage_payments])
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.AUTHORIZATION_SUCCESS.upper()
+ expected_response["amount"] = str(checkout.total_gross_amount)
+ expected_response["pspReference"] = expected_psp_reference
+ del expected_response["data"]
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": TransactionFlowStrategyEnum.AUTHORIZATION.name,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = app_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=checkout.total_gross_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.AUTHORIZATION_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ authorized_value=checkout.total_gross_amount,
+ action_type=TransactionFlowStrategy.AUTHORIZATION,
+ returned_data=None,
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_uses_default_channel_action(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ channel = checkout.channel
+ channel.default_transaction_flow_strategy = TransactionFlowStrategy.AUTHORIZATION
+ channel.save()
+
+ expected_amount = Decimal("10.00")
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = "CHARGE_SUCCESS"
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=expected_amount,
+ action_type=TransactionFlowStrategy.AUTHORIZATION,
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ returned_data=expected_response["data"],
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_app_with_action_field(
+ mocked_initialize,
+ app_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+ permission_manage_payments,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_charged_amount = Decimal("10")
+ expected_authorized_amount = Decimal("3")
+ transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=expected_charged_amount,
+ authorized_value=expected_authorized_amount,
+ )
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = TransactionEventType.AUTHORIZATION_SUCCESS.upper()
+ expected_response["amount"] = str(
+ checkout.total_gross_amount - expected_charged_amount
+ )
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": TransactionFlowStrategyEnum.AUTHORIZATION.name,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = app_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_customer_with_action_field(
+ app_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+ permission_manage_payments,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_charged_amount = Decimal("10")
+ expected_authorized_amount = Decimal("3")
+ transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=expected_charged_amount,
+ authorized_value=expected_authorized_amount,
+ )
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ variables = {
+ "action": TransactionFlowStrategyEnum.AUTHORIZATION.name,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = app_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_incorrect_source_object_id(
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+ permission_manage_payments,
+ product,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_charged_amount = Decimal("10")
+ expected_authorized_amount = Decimal("3")
+ transaction_item_generator(
+ checkout_id=checkout.pk,
+ charged_value=expected_charged_amount,
+ authorized_value=expected_authorized_amount,
+ )
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(product),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ errors = content["data"]["transactionInitialize"]["errors"]
+ assert errors
+ assert len(errors) == 1
+ assert errors[0]["field"] == "id"
+ assert errors[0]["code"] == TransactionInitializeErrorCode.INVALID.name
+
+
+def test_checkout_doesnt_exist(
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+ permission_manage_payments,
+):
+ # given
+ checkout = checkout_with_prices
+
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+ checkout.delete()
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ errors = content["data"]["transactionInitialize"]["errors"]
+ assert errors
+ assert len(errors) == 1
+ assert errors[0]["field"] == "id"
+ assert errors[0]["code"] == TransactionInitializeErrorCode.NOT_FOUND.name
+
+
+def test_order_doesnt_exists(
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+ permission_manage_payments,
+):
+ # given
+ order = order_with_lines
+
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(order),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+ order.delete()
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response, ignore_errors=True)
+ errors = content["data"]["transactionInitialize"]["errors"]
+ assert errors
+ assert len(errors) == 1
+ assert errors[0]["field"] == "id"
+ assert errors[0]["code"] == TransactionInitializeErrorCode.NOT_FOUND.name
+
+
+ "result", [TransactionEventType.CHARGE_REQUEST, TransactionEventType.CHARGE_SUCCESS]
+)
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_checkout_fully_paid(
+ mocked_initialize,
+ mocked_fully_paid,
+ result,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = result.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_initialize.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": None,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionInitialize"]["errors"]
+ checkout.refresh_from_db()
+ mocked_fully_paid.assert_called_once_with(checkout)
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
new file mode 100644
index 0000000000..41c298b712
--- /dev/null
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -0,0 +1,936 @@
+from decimal import Decimal
+
+import graphene
+import mock
+import pytest
+
+from .....channel import TransactionFlowStrategy
+from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
+from .....checkout.calculations import fetch_checkout_data
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....core.prices import quantize_price
+from .....payment import TransactionEventType
+from .....payment.interface import (
+ PaymentGatewayData,
+ TransactionProcessActionData,
+ TransactionSessionData,
+)
+from .....payment.models import TransactionEvent
+from ....core.enums import TransactionProcessErrorCode
+from ....core.utils import to_global_id_or_none
+from ....tests.utils import get_graphql_content
+
+TRANSACTION_PROCESS = """
+mutation TransactionProcess(
+ $id: ID!,
+ $data: JSON
+) {
+ transactionProcess(
+ id: $id
+ data: $data
+ ) {
+ data
+ transaction {
+ id
+ authorizedAmount {
+ currency
+ amount
+ }
+ chargedAmount {
+ currency
+ amount
+ }
+ chargePendingAmount {
+ amount
+ currency
+ }
+ authorizePendingAmount {
+ amount
+ currency
+ }
+ }
+ transactionEvent {
+ id
+ amount {
+ currency
+ amount
+ }
+ type
+ createdBy {
+ ... on App {
+ id
+ }
+ }
+ pspReference
+ message
+ externalUrl
+ }
+ errors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
+def _assert_fields(
+ content,
+ source_object,
+ expected_amount,
+ expected_psp_reference,
+ response_event_type,
+ app_identifier,
+ mocked_process,
+ request_event_type=TransactionEventType.CHARGE_REQUEST,
+ action_type=TransactionFlowStrategy.CHARGE,
+ request_event_include_in_calculations=False,
+ data=None,
+ authorized_value=Decimal(0),
+ charged_value=Decimal(0),
+ charge_pending_value=Decimal(0),
+ authorize_pending_value=Decimal(0),
+ returned_data=None,
+):
+ assert not content["data"]["transactionProcess"]["errors"]
+ response_data = content["data"]["transactionProcess"]
+ assert response_data["data"] == returned_data
+ transaction_data = response_data["transaction"]
+ transaction = source_object.payment_transactions.last()
+ assert transaction
+ assert (
+ quantize_price(
+ Decimal(transaction_data["authorizePendingAmount"]["amount"]),
+ source_object.currency,
+ )
+ == authorize_pending_value
+ == transaction.authorize_pending_value
+ )
+ assert (
+ quantize_price(
+ Decimal(transaction_data["authorizedAmount"]["amount"]),
+ source_object.currency,
+ )
+ == authorized_value
+ == transaction.authorized_value
+ )
+ assert (
+ quantize_price(
+ Decimal(transaction_data["chargePendingAmount"]["amount"]),
+ source_object.currency,
+ )
+ == charge_pending_value
+ == transaction.charge_pending_value
+ )
+
+ assert (
+ quantize_price(
+ Decimal(transaction_data["chargedAmount"]["amount"]), source_object.currency
+ )
+ == charged_value
+ == transaction.charged_value
+ )
+
+ assert response_data["transactionEvent"]
+ assert response_data["transactionEvent"]["type"] == response_event_type.upper()
+ assert (
+ quantize_price(
+ Decimal(response_data["transactionEvent"]["amount"]["amount"]),
+ source_object.currency,
+ )
+ == expected_amount
+ )
+
+ request_event = transaction.events.filter(type=request_event_type).first()
+ assert request_event
+
+ assert request_event.amount_value == expected_amount
+ assert (
+ request_event.include_in_calculations == request_event_include_in_calculations
+ )
+ assert request_event.psp_reference == expected_psp_reference
+ response_event = transaction.events.filter(type=response_event_type).first()
+ assert response_event
+ assert response_event.amount_value == expected_amount
+ assert response_event.include_in_calculations
+ assert response_event.psp_reference == expected_psp_reference
+
+ mocked_process.assert_called_with(
+ TransactionSessionData(
+ transaction=transaction,
+ source_object=source_object,
+ action=TransactionProcessActionData(
+ action_type=action_type,
+ amount=expected_amount,
+ currency=source_object.currency,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=app_identifier, data=data, error=None
+ ),
+ )
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_for_checkout_without_data(
+ mocked_process,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout_with_prices.pk, app=webhook_app
+ )
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=expected_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = expected_amount
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ del expected_response["data"]
+ mocked_process.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "data": None,
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_process=mocked_process,
+ charged_value=expected_amount,
+ returned_data=None,
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_for_order_without_data(
+ mocked_process,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(order_id=order.pk, app=webhook_app)
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=expected_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = expected_amount
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ del expected_response["data"]
+ mocked_process.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "data": None,
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_process=mocked_process,
+ charged_value=expected_amount,
+ returned_data=None,
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_for_checkout_with_data(
+ mocked_process,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout_with_prices.pk, app=webhook_app
+ )
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=expected_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = expected_amount
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+ expected_data = {"some": "json-data"}
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "data": expected_data,
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_process=mocked_process,
+ charged_value=expected_amount,
+ data=expected_data,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_for_order_with_data(
+ mocked_process,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(order_id=order.pk, app=webhook_app)
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=expected_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = expected_amount
+ expected_response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ expected_data = {"some": "json-data"}
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "data": expected_data,
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_process=mocked_process,
+ charged_value=expected_amount,
+ data=expected_data,
+ returned_data=expected_response["data"],
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_checkout_with_pending_amount(
+ mocked_process,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, app=webhook_app
+ )
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=expected_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = expected_amount
+ expected_response["result"] = TransactionEventType.CHARGE_REQUEST.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ checkout.refresh_from_db()
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_REQUEST,
+ app_identifier=webhook_app.identifier,
+ mocked_process=mocked_process,
+ charge_pending_value=expected_amount,
+ request_event_include_in_calculations=True,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_order_with_pending_amount(
+ mocked_process,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(order_id=order.pk, app=webhook_app)
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=expected_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = expected_amount
+ expected_response["result"] = TransactionEventType.CHARGE_REQUEST.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_REQUEST,
+ app_identifier=webhook_app.identifier,
+ mocked_process=mocked_process,
+ charge_pending_value=expected_amount,
+ request_event_include_in_calculations=True,
+ returned_data=expected_response["data"],
+ )
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_checkout_with_action_required_response(
+ mocked_process,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk, app=webhook_app
+ )
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=expected_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = expected_amount
+ expected_response["result"] = TransactionEventType.CHARGE_ACTION_REQUIRED.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ checkout.refresh_from_db()
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_ACTION_REQUIRED,
+ app_identifier=webhook_app.identifier,
+ mocked_process=mocked_process,
+ returned_data=expected_response["data"],
+ )
+ assert checkout.charge_status == CheckoutChargeStatus.NONE
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.NONE
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_order_with_action_required_response(
+ mocked_process,
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(order_id=order.pk, app=webhook_app)
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=expected_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = expected_amount
+ expected_response["result"] = TransactionEventType.CHARGE_ACTION_REQUIRED.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=expected_amount,
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_ACTION_REQUIRED,
+ app_identifier=webhook_app.identifier,
+ mocked_process=mocked_process,
+ returned_data=expected_response["data"],
+ )
+
+
+def test_transaction_already_processed(
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ order_id=order.pk, app=webhook_app, charged_value=Decimal("10")
+ )
+ transaction_event = transaction_item.events.get()
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ assert transaction_item.events.count() == 1
+ content = get_graphql_content(response)
+ response_data = content["data"]["transactionProcess"]
+ transaction_data = response_data["transaction"]
+ assert transaction_data["id"] == graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
+ assert response_data["transactionEvent"]["type"] == transaction_event.type.upper()
+ assert response_data["transactionEvent"]["id"] == to_global_id_or_none(
+ transaction_event
+ )
+
+
+def test_request_event_is_missing(
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ response_data = content["data"]["transactionProcess"]
+ assert len(response_data["errors"]) == 1
+ assert response_data["errors"][0]["field"] == "id"
+ assert (
+ response_data["errors"][0]["code"] == TransactionProcessErrorCode.INVALID.name
+ )
+
+
+def test_transaction_doesnt_have_source_object(
+ user_api_client,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ app=webhook_app,
+ )
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=Decimal("10"),
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ response_data = content["data"]["transactionProcess"]
+ assert len(response_data["errors"]) == 1
+ assert response_data["errors"][0]["field"] == "id"
+ assert (
+ response_data["errors"][0]["code"] == TransactionProcessErrorCode.INVALID.name
+ )
+
+
+def test_transaction_doesnt_have_app_identifier(
+ order_with_lines,
+ user_api_client,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ transaction_item = transaction_item_generator(order_id=order_with_lines.pk)
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=Decimal("10"),
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ response_data = content["data"]["transactionProcess"]
+ assert len(response_data["errors"]) == 1
+ assert response_data["errors"][0]["field"] == "id"
+ assert (
+ response_data["errors"][0]["code"]
+ == TransactionProcessErrorCode.MISSING_PAYMENT_APP_RELATION.name
+ )
+
+
+def test_app_attached_to_transaction_doesnt_exist(
+ order_with_lines,
+ user_api_client,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=webhook_app,
+ )
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=Decimal("10"),
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ webhook_app.delete()
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ response_data = content["data"]["transactionProcess"]
+ assert len(response_data["errors"]) == 1
+ assert response_data["errors"][0]["field"] == "id"
+ assert (
+ response_data["errors"][0]["code"]
+ == TransactionProcessErrorCode.MISSING_PAYMENT_APP.name
+ )
+
+
+ "result", [TransactionEventType.CHARGE_REQUEST, TransactionEventType.CHARGE_SUCCESS]
+)
[email protected]("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
[email protected]("saleor.plugins.manager.PluginsManager.transaction_process_session")
+def test_checkout_fully_paid(
+ mocked_process,
+ mocked_fully_paid,
+ result,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+ plugins_manager,
+ transaction_item_generator,
+):
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ )
+ TransactionEvent.objects.create(
+ include_in_calculations=False,
+ transaction=transaction_item,
+ amount_value=checkout_info.checkout.total_gross_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["amount"] = str(checkout_info.checkout.total_gross_amount)
+ expected_response["result"] = result.upper()
+ expected_response["pspReference"] = expected_psp_reference
+ mocked_process.return_value = PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionProcess"]["errors"]
+
+ checkout.refresh_from_db()
+ mocked_fully_paid.assert_called_once_with(checkout)
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+
+
+def test_transaction_process_doesnt_accept_old_id(
+ user_api_client,
+ order_with_lines,
+ webhook_app,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ transaction_item = transaction_item_generator(
+ order_id=order.pk, app=webhook_app, use_old_id=True
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.pk)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ response_data = content["data"]["transactionProcess"]
+ assert len(response_data["errors"]) == 1
+ assert response_data["errors"][0]["field"] == "id"
+ assert (
+ response_data["errors"][0]["code"] == TransactionProcessErrorCode.INVALID.name
+ )
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 55514d84fd..e88bd819f6 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -94,7 +94,7 @@ def test_transaction_request_charge_action_for_order(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.CHARGE.name,
"amount": charge_amount,
}
@@ -171,7 +171,7 @@ def test_transaction_request_refund_action_for_order(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.REFUND.name,
"amount": refund_amount,
}
@@ -237,7 +237,7 @@ def test_transaction_request_void_action_for_order(
authorized_value=Decimal("10"),
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
@@ -300,7 +300,7 @@ def test_transaction_request_void_action_for_checkout(
authorized_value=Decimal("10"),
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
@@ -371,7 +371,7 @@ def test_transaction_request_charge_action_for_checkout(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.CHARGE.name,
"amount": charge_amount,
}
@@ -443,7 +443,7 @@ def test_transaction_request_refund_action_for_checkout(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.REFUND.name,
"amount": refund_amount,
}
@@ -505,7 +505,7 @@ def test_transaction_action_request_uses_handle_payment_permission(
)
refund_amount = Decimal("1")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.REFUND.name,
"amount": refund_amount,
}
@@ -553,7 +553,7 @@ def test_transaction_request_action_missing_permission(
authorized_value=Decimal("10"),
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
@@ -584,7 +584,7 @@ def test_transaction_request_action_missing_event(
mocked_is_active.side_effect = [False, False]
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
@@ -667,7 +667,7 @@ def test_transaction_request_charge_for_order(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.CHARGE.name,
"amount": charge_amount,
}
@@ -751,7 +751,7 @@ def test_transaction_request_refund_for_order(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.REFUND.name,
"amount": refund_amount,
}
@@ -822,7 +822,7 @@ def test_transaction_request_cancelation_for_order(
app=transaction_request_webhook.app,
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
@@ -893,7 +893,7 @@ def test_transaction_request_cancelation_for_checkout(
app=transaction_request_webhook.app,
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
@@ -971,7 +971,7 @@ def test_transaction_request_charge_for_checkout(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.CHARGE.name,
"amount": charge_amount,
}
@@ -1049,7 +1049,7 @@ def test_transaction_request_refund_for_checkout(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.REFUND.name,
"amount": refund_amount,
}
@@ -1119,7 +1119,7 @@ def test_transaction_request_refund_when_app_reinstalled(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.REFUND.name,
"amount": refund_amount,
}
@@ -1187,7 +1187,7 @@ def test_transaction_request_uses_handle_payment_permission(
)
refund_amount = Decimal("1")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.REFUND.name,
"amount": refund_amount,
}
@@ -1241,7 +1241,7 @@ def test_transaction_request_missing_permission(
app=transaction_request_webhook.app,
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
@@ -1282,7 +1282,7 @@ def test_transaction_request_missing_event(
mocked_is_active.return_value = False
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"action_type": TransactionActionEnum.VOID.name,
}
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index 0ae2aa2c28..c76282f69b 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -2,7 +2,11 @@ from decimal import Decimal
import graphene
import pytest
+from mock import patch
+from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
+from .....checkout.calculations import fetch_checkout_data
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....order import OrderEvents
from .....payment import TransactionEventStatus, TransactionEventType
from .....payment.error_codes import TransactionUpdateErrorCode
@@ -111,7 +115,7 @@ def test_only_owner_can_update_its_transaction_by_app(
status = "Captured for 10$"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"status": status,
},
@@ -133,7 +137,7 @@ def test_transaction_update_status_by_app(
status = "Captured for 10$"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"status": status,
},
@@ -161,7 +165,7 @@ def test_transaction_update_metadata_by_app(
meta_key = "key-name"
meta_value = "key_value"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"metadata": [{"key": meta_key, "value": meta_value}],
},
@@ -191,7 +195,7 @@ def test_transaction_update_metadata_incorrect_key_by_app(
meta_key = ""
meta_value = "key_value"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"metadata": [{"key": meta_key, "value": meta_value}],
},
@@ -220,7 +224,7 @@ def test_transaction_update_private_metadata_by_app(
meta_key = "key-name"
meta_value = "key_value"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"privateMetadata": [{"key": meta_key, "value": meta_value}],
},
@@ -250,7 +254,7 @@ def test_transaction_update_private_metadata_incorrect_key_by_app(
meta_key = ""
meta_value = "key_value"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"privateMetadata": [{"key": meta_key, "value": meta_value}],
},
@@ -278,7 +282,7 @@ def test_transaction_update_type_by_app(
type = "New credit card"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"type": type,
},
@@ -306,7 +310,7 @@ def test_transaction_update_name_by_app(
name = "New credit card"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"name": name,
},
@@ -334,7 +338,7 @@ def test_transaction_update_message_by_app(
message = "Message"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"message": message,
},
@@ -361,7 +365,7 @@ def test_transaction_update_psp_reference_by_app(
transaction = transaction_item_created_by_app
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"pspReference": psp_peference,
},
@@ -390,7 +394,7 @@ def test_transaction_update_available_actions_by_app(
available_actions = [TransactionActionEnum.REFUND.name]
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"availableActions": available_actions,
},
@@ -446,7 +450,7 @@ def test_transaction_update_amounts_by_app(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {field_name: {"amount": value, "currency": "USD"}},
}
@@ -509,7 +513,7 @@ def test_transaction_update_for_order_increases_order_total_authorized_by_app(
authorized_value = transaction.authorized_value + Decimal("10")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountAuthorized": {
"amount": authorized_value,
@@ -560,7 +564,7 @@ def test_transaction_update_for_order_reduces_order_total_authorized_by_app(
authorized_value = transaction.authorized_value - Decimal("5")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountAuthorized": {
"amount": authorized_value,
@@ -611,7 +615,7 @@ def test_transaction_update_for_order_reduces_transaction_authorized_to_zero_by_
authorized_value = Decimal("0")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountAuthorized": {
"amount": authorized_value,
@@ -659,7 +663,7 @@ def test_transaction_update_for_order_increases_order_total_charged_by_app(
charged_value = transaction.charged_value + Decimal("10")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountCharged": {
"amount": charged_value,
@@ -709,7 +713,7 @@ def test_transaction_update_for_order_reduces_order_total_charged_by_app(
charged_value = transaction.charged_value - Decimal("5")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountCharged": {
"amount": charged_value,
@@ -759,7 +763,7 @@ def test_transaction_update_for_order_reduces_transaction_charged_to_zero_by_app
charged_value = Decimal("0")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountCharged": {
"amount": charged_value,
@@ -802,7 +806,7 @@ def test_transaction_update_multiple_amounts_provided_by_app(
canceled_value = Decimal("13")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountAuthorized": {
"amount": authorized_value,
@@ -854,7 +858,7 @@ def test_transaction_update_for_order_missing_permission_by_app(
type = "Credit Card"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"status": status,
"type": type,
@@ -890,7 +894,7 @@ def test_transaction_update_incorrect_currency_by_app(
expected_value = Decimal("10")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
amount_field_name: {
"amount": expected_value,
@@ -926,7 +930,7 @@ def test_transaction_update_adds_transaction_event_to_order_by_app(
transaction_name = "Processing transaction"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction_event": {
"status": transaction_status,
"pspReference": transaction_reference,
@@ -965,7 +969,7 @@ def test_creates_transaction_event_for_order_by_app(
event_reference = "PSP-ref"
event_name = "Failed authorization"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction_event": {
"status": TransactionEventStatusEnum.FAILURE.name,
"pspReference": event_reference,
@@ -1015,7 +1019,7 @@ def test_creates_transaction_event_by_reinstalled_app(
event_reference = "PSP-ref"
event_name = "Failed authorization"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction_event": {
"status": TransactionEventStatusEnum.FAILURE.name,
"pspReference": event_reference,
@@ -1050,7 +1054,7 @@ def test_only_owner_can_update_its_transaction_by_staff(
status = "Captured for 10$"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"status": status,
},
@@ -1072,7 +1076,7 @@ def test_transaction_update_status_by_staff(
status = "Captured for 10$"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"status": status,
},
@@ -1100,7 +1104,7 @@ def test_transaction_update_metadata_by_staff(
meta_key = "key-name"
meta_value = "key_value"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"metadata": [{"key": meta_key, "value": meta_value}],
},
@@ -1130,7 +1134,7 @@ def test_transaction_update_metadata_incorrect_key_by_staff(
meta_key = ""
meta_value = "key_value"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"metadata": [{"key": meta_key, "value": meta_value}],
},
@@ -1159,7 +1163,7 @@ def test_transaction_update_private_metadata_by_staff(
meta_key = "key-name"
meta_value = "key_value"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"privateMetadata": [{"key": meta_key, "value": meta_value}],
},
@@ -1189,7 +1193,7 @@ def test_transaction_update_private_metadata_incorrect_key_by_staff(
meta_key = ""
meta_value = "key_value"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"privateMetadata": [{"key": meta_key, "value": meta_value}],
},
@@ -1217,7 +1221,7 @@ def test_transaction_update_type_by_staff(
type = "New credit card"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"type": type,
},
@@ -1245,7 +1249,7 @@ def test_transaction_update_name_by_staff(
name = "New credit card"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"name": name,
},
@@ -1273,7 +1277,7 @@ def test_transaction_update_message_by_staff(
message = "Message"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"message": message,
},
@@ -1300,7 +1304,7 @@ def test_transaction_update_psp_reference_by_staff(
transaction = transaction_item_created_by_user
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"pspReference": reference,
},
@@ -1327,7 +1331,7 @@ def test_transaction_update_available_actions_by_staff(
available_actions = [TransactionActionEnum.REFUND.name]
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"availableActions": available_actions,
},
@@ -1369,7 +1373,7 @@ def test_transaction_update_amounts_by_staff(
# given
transaction = transaction_item_generator(user=staff_user)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {field_name: {"amount": value, "currency": "USD"}},
}
@@ -1410,7 +1414,7 @@ def test_transaction_update_for_order_increases_order_total_authorized_by_staff(
authorized_value = transaction.authorized_value + Decimal("10")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountAuthorized": {
"amount": authorized_value,
@@ -1461,7 +1465,7 @@ def test_transaction_update_for_order_reduces_order_total_authorized_by_staff(
authorized_value = transaction.authorized_value - Decimal("5")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountAuthorized": {
"amount": authorized_value,
@@ -1513,7 +1517,7 @@ def test_transaction_update_for_order_reduces_transaction_authorized_to_zero_by_
authorized_value = Decimal("0")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountAuthorized": {
"amount": authorized_value,
@@ -1560,7 +1564,7 @@ def test_transaction_update_for_order_increases_order_total_charged_by_staff(
charged_value = transaction.charged_value + Decimal("10")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountCharged": {
"amount": charged_value,
@@ -1610,7 +1614,7 @@ def test_transaction_update_for_order_reduces_order_total_charged_by_staff(
charged_value = transaction.charged_value - Decimal("5")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountCharged": {
"amount": charged_value,
@@ -1660,7 +1664,7 @@ def test_transaction_update_for_order_reduces_transaction_charged_to_zero_by_sta
charged_value = Decimal("0")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountCharged": {
"amount": charged_value,
@@ -1695,7 +1699,7 @@ def test_transaction_update_multiple_amounts_provided_by_staff(
canceled_value = Decimal("13")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountAuthorized": {
"amount": authorized_value,
@@ -1747,7 +1751,7 @@ def test_transaction_update_for_order_missing_permission_by_staff(
type = "Credit Card"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"status": status,
"type": type,
@@ -1783,7 +1787,7 @@ def test_transaction_update_incorrect_currency_by_staff(
expected_value = Decimal("10")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
amount_field_name: {
"amount": expected_value,
@@ -1819,7 +1823,7 @@ def test_transaction_update_adds_transaction_event_to_order_by_staff(
transaction_name = "Processing transaction"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction_event": {
"status": transaction_status,
"pspReference": transaction_reference,
@@ -1858,7 +1862,7 @@ def test_creates_transaction_event_for_order_by_staff(
event_reference = "PSP-ref"
event_name = "Failed authorization"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction_event": {
"status": TransactionEventStatusEnum.FAILURE.name,
"pspReference": event_reference,
@@ -1912,7 +1916,7 @@ def test_transaction_raises_error_when_psp_reference_already_exists_by_staff(
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", second_transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", second_transaction.token),
"transaction": {
"pspReference": psp_reference,
},
@@ -1956,7 +1960,7 @@ def test_transaction_raises_error_when_psp_reference_already_exists_by_app(
app=app,
)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", second_transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", second_transaction.token),
"transaction": {
"pspReference": psp_reference,
},
@@ -1990,7 +1994,7 @@ def test_transaction_update_external_url_by_app(
external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"externalUrl": external_url,
},
@@ -2017,7 +2021,7 @@ def test_transaction_update_external_url_incorrect_url_format_by_app(
external_url = "incorrect"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"externalUrl": external_url,
},
@@ -2045,7 +2049,7 @@ def test_transaction_update_external_url_by_staff(
external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"externalUrl": external_url,
},
@@ -2072,7 +2076,7 @@ def test_transaction_update_external_url_incorrect_url_format_by_staff(
external_url = "incorrect"
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"externalUrl": external_url,
},
@@ -2118,7 +2122,7 @@ def test_transaction_update_creates_calculation_event(
refunded_value = Decimal("15")
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {
"amountAuthorized": {
"amount": authorized_value,
@@ -2439,7 +2443,7 @@ def test_transaction_update_amounts_are_correct(
recalculate_transaction_amounts(transaction)
variables = {
- "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
"transaction": {field_name: {"amount": value, "currency": "USD"}},
}
@@ -2477,3 +2481,153 @@ def test_transaction_update_amounts_are_correct(
transaction.cancel_pending_value,
]
) == sum(provided_amounts.values())
+
+
+def test_transaction_create_for_checkout_updates_payment_statuses(
+ checkout_with_items,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ app,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ transaction = transaction_item_generator(
+ checkout_id=checkout_with_items.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ )
+ authorized_value = Decimal("12")
+ charged_value = Decimal("13")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "amountCharged": {
+ "amount": charged_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ checkout_with_items.refresh_from_db()
+ assert checkout_with_items.charge_status == CheckoutChargeStatus.PARTIAL
+ assert checkout_with_items.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
+
+@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
+def test_transaction_create_for_checkout_fully_paid(
+ mocked_checkout_fully_paid,
+ checkout_with_prices,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ app,
+ plugins_manager,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ transaction = transaction_item_generator(
+ checkout_id=checkout_with_prices.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ )
+
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, discounts=[]
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountCharged": {
+ "amount": checkout_info.checkout.total.gross.amount,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.charge_status == CheckoutChargeStatus.FULL
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+
+ mocked_checkout_fully_paid.assert_called_once_with(checkout)
+
+
+def test_transaction_update_accepts_old_id_for_old_transaction(
+ transaction_item_generator, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_generator(use_old_id=True)
+ status = "Captured for 10$"
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
+ "transaction": {
+ "status": status,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert data["status"] == status
+ assert transaction.status == status
+
+
+def test_transaction_update_doesnt_accept_old_id_for_new_transactions(
+ transaction_item_generator, permission_manage_payments, app_api_client
+):
+ # given
+ transaction = transaction_item_generator(use_old_id=False)
+ 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
+ content = get_graphql_content(response)
+ assert not content["data"]["transactionUpdate"]["transaction"]
+ errors = content["data"]["transactionUpdate"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["code"] == TransactionUpdateErrorCode.NOT_FOUND.name
+ assert error["field"] == "id"
diff --git a/saleor/graphql/payment/tests/queries/test_transaction.py b/saleor/graphql/payment/tests/queries/test_transaction.py
index 2d1b6c7de6..4acf2201fb 100644
--- a/saleor/graphql/payment/tests/queries/test_transaction.py
+++ b/saleor/graphql/payment/tests/queries/test_transaction.py
@@ -1,5 +1,6 @@
from decimal import Decimal
+import graphene
import pytest
from .....payment import TransactionEventStatus, TransactionEventType
@@ -96,6 +97,9 @@ TRANSACTION_QUERY = """
def _assert_transaction_fields(content, transaction_item, event):
data = content["data"]["transaction"]
+ assert data["id"] == graphene.Node.to_global_id(
+ "TransactionItem", transaction_item.token
+ )
assert data["createdAt"] == transaction_item.created_at.isoformat()
assert data["actions"] == [
action.upper() for action in transaction_item.available_actions
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index 40c68c5aa0..ab737073b1 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -1,4 +1,8 @@
+from typing import Any, Optional
+from uuid import UUID
+
import graphene
+from django.db.models import Q
from graphene import relay
from ...core.exceptions import PermissionDenied
@@ -7,6 +11,7 @@ from ...permission.enums import OrderPermissions
from ..account.dataloaders import UserByUserIdLoader
from ..app.dataloaders import AppByIdLoader, AppsByAppIdentifierLoader
from ..checkout.dataloaders import CheckoutByTokenLoader
+from ..core import ResolveInfo
from ..core.connection import CountableConnection
from ..core.descriptions import (
ADDED_IN_31,
@@ -493,6 +498,10 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
interfaces = [relay.Node, ObjectWithMetadata]
model = models.TransactionItem
+ @staticmethod
+ def resolve_id(root: models.TransactionItem, _info: ResolveInfo):
+ return root.token
+
@staticmethod
def resolve_actions(root: models.TransactionItem, _info):
return root.available_actions
@@ -595,3 +604,17 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
@staticmethod
def resolve_message(root: models.TransactionItem, info) -> str:
return root.message or ""
+
+ @classmethod
+ def get_node(cls, _: Any, id: str) -> Optional[models.TransactionItem]:
+ model = cls._meta.model
+ lookup = Q(token=id)
+ try:
+ UUID(str(id))
+ except ValueError:
+ lookup = Q(pk=id) & Q(use_old_id=True)
+
+ try:
+ return model.objects.get(lookup)
+ except model.DoesNotExist:
+ return None
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index aa89bc5c25..5eca80b438 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1790,6 +1790,7 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
A checkout is updated. It also triggers all updates related to the checkout.
"""
CHECKOUT_UPDATED
+ CHECKOUT_FULLY_PAID
"""
A checkout metadata is updated.
@@ -2026,6 +2027,9 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
"""Filter shipping methods for checkout."""
CHECKOUT_FILTER_SHIPPING_METHODS
+ PAYMENT_GATEWAY_INITIALIZE_SESSION
+ TRANSACTION_INITIALIZE_SESSION
+ TRANSACTION_PROCESS_SESSION
}
"""Synchronous webhook event."""
@@ -2113,6 +2117,9 @@ enum WebhookEventTypeSyncEnum @doc(category: "Webhooks") {
"""Filter shipping methods for checkout."""
CHECKOUT_FILTER_SHIPPING_METHODS
+ PAYMENT_GATEWAY_INITIALIZE_SESSION
+ TRANSACTION_INITIALIZE_SESSION
+ TRANSACTION_PROCESS_SESSION
}
"""Asynchronous webhook event."""
@@ -2398,6 +2405,7 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {
A checkout is updated. It also triggers all updates related to the checkout.
"""
CHECKOUT_UPDATED
+ CHECKOUT_FULLY_PAID
"""
A checkout metadata is updated.
@@ -3101,6 +3109,7 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {
PRODUCT_VARIANT_METADATA_UPDATED
CHECKOUT_CREATED
CHECKOUT_UPDATED
+ CHECKOUT_FULLY_PAID
CHECKOUT_METADATA_UPDATED
FULFILLMENT_CREATED
FULFILLMENT_CANCELED
@@ -4925,6 +4934,15 @@ type OrderSettings {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
markAsPaidStrategy: MarkAsPaidStrategyEnum!
+
+ """
+ Determine the transaction flow strategy to be used. Include the selected option in the payload sent to the payment app, as a requested action 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.
+ """
+ defaultTransactionFlowStrategy: TransactionFlowStrategyEnum!
}
"""
@@ -4941,6 +4959,17 @@ enum MarkAsPaidStrategyEnum @doc(category: "Channels") {
PAYMENT_FLOW
}
+"""
+Determine the transaction flow strategy.
+
+ AUTHORIZATION - the processed transaction should be only authorized
+ CHARGE - the processed transaction should be charged.
+"""
+enum TransactionFlowStrategyEnum @doc(category: "Payments") {
+ AUTHORIZATION
+ CHARGE
+}
+
"""Represents shipping method postal code rule."""
type ShippingMethodPostalCodeRule implements Node @doc(category: "Shipping") {
"""The ID of the object."""
@@ -9053,7 +9082,14 @@ type Checkout implements Node & ObjectWithMetadata @doc(category: "Checkout") {
"""
metafields(keys: [String!]): Metadata
created: DateTime!
- lastChange: DateTime!
+
+ """
+ Time of last modification of the given checkout.
+
+ Added in Saleor 3.13.
+ """
+ updatedAt: DateTime!
+ lastChange: DateTime! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `updatedAt` instead.")
user: User
channel: Channel!
billingAddress: Address
@@ -9141,6 +9177,15 @@ type Checkout implements Node & ObjectWithMetadata @doc(category: "Checkout") {
"""
totalPrice: TaxedMoney!
+ """
+ The difference between the paid and the checkout total amount.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ totalBalance: Money!
+
"""Checkout language code."""
languageCode: LanguageCodeEnum!
@@ -9161,6 +9206,24 @@ type Checkout implements Node & ObjectWithMetadata @doc(category: "Checkout") {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
displayGrossPrices: Boolean!
+
+ """
+ The authorize status of the checkout.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ authorizeStatus: CheckoutAuthorizeStatusEnum!
+
+ """
+ The charge status of the checkout.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ chargeStatus: CheckoutChargeStatusEnum!
}
"""
@@ -11132,6 +11195,10 @@ Represents possible event types.
AUTHORIZATION_FAILURE - represents failure authorization.
AUTHORIZATION_ADJUSTMENT - represents authorization adjustment.
AUTHORIZATION_REQUEST - represents authorization request.
+ AUTHORIZATION_ACTION_REQUIRED - represents authorization that needs
+ additional actions from the customer.
+ CHARGE_ACTION_REQUIRED - represents charge that needs
+ additional actions from the customer.
CHARGE_SUCCESS - represents success charge.
CHARGE_FAILURE - represents failure charge.
CHARGE_BACK - represents chargeback.
@@ -11150,6 +11217,8 @@ enum TransactionEventTypeEnum @doc(category: "Payments") {
AUTHORIZATION_FAILURE
AUTHORIZATION_ADJUSTMENT
AUTHORIZATION_REQUEST
+ AUTHORIZATION_ACTION_REQUIRED
+ CHARGE_ACTION_REQUIRED
CHARGE_SUCCESS
CHARGE_FAILURE
CHARGE_BACK
@@ -11166,6 +11235,49 @@ enum TransactionEventTypeEnum @doc(category: "Payments") {
union UserOrApp = User | App
+"""
+Determine a current authorize status for checkout.
+
+ We treat the checkout as fully authorized when the sum of authorized and charged
+ funds cover the checkout.total.
+ We treat the checkout as partially authorized when the sum of authorized and charged
+ funds covers only part of the checkout.total
+ We treat the checkout as not authorized when the sum of authorized and charged funds
+ is 0.
+
+ NONE - the funds are not authorized
+ PARTIAL - the cover funds don't cover fully the checkout's total
+ FULL - the cover funds covers the checkout's total
+"""
+enum CheckoutAuthorizeStatusEnum @doc(category: "Checkout") {
+ NONE
+ PARTIAL
+ FULL
+}
+
+"""
+Determine the current charge status for the checkout.
+
+ The checkout is considered overcharged when the sum of the transactionItem's charge
+ amounts exceeds the value of `checkout.total`.
+ If the sum of the transactionItem's charge amounts equals
+ `checkout.total`, we consider the checkout to be fully charged.
+ If the sum of the transactionItem's charge amounts covers a part of the
+ `checkout.total`, we treat the checkout as partially charged.
+
+
+ NONE - the funds are not charged.
+ PARTIAL - the funds that are charged don't cover the checkout's total
+ FULL - the funds that are charged fully cover the checkout's total
+ OVERCHARGED - the charged funds are bigger than checkout's total
+"""
+enum CheckoutChargeStatusEnum @doc(category: "Checkout") {
+ NONE
+ PARTIAL
+ FULL
+ OVERCHARGED
+}
+
type CheckoutCountableConnection {
"""Pagination data for this connection."""
pageInfo: PageInfo!
@@ -12304,6 +12416,9 @@ input CheckoutFilterInput @doc(category: "Checkout") {
search: String
metadata: [MetadataFilter!]
channels: [ID!]
+ updatedAt: DateRangeInput
+ authorizeStatus: [CheckoutAuthorizeStatusEnum!]
+ chargeStatus: [CheckoutChargeStatusEnum!]
}
type CheckoutLineCountableConnection {
@@ -14016,6 +14131,66 @@ type Mutation {
type: TransactionEventTypeEnum!
): TransactionEventReport @doc(category: "Payments")
+ """
+ Initializes a payment gateway session. It triggers the webhook `PAYMENT_GATEWAY_INITIALIZE_SESSION`, to the requested `paymentGateways`. If `paymentGateways` is not provided, the webhook will be send to all subscribed payment gateways.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ paymentGatewayInitialize(
+ """
+ The amount requested for initializing the payment gateway. If not provided, the difference between checkout.total - transactions that are already processed will be send.
+ """
+ amount: PositiveDecimal
+
+ """The ID of the checkout or order."""
+ id: ID!
+
+ """List of payment gateways to initialize."""
+ paymentGateways: [PaymentGatewayToInitialize!]
+ ): PaymentGatewayInitialize @doc(category: "Payments")
+
+ """
+ Initializes a transaction session. It triggers the webhook `TRANSACTION_INITIALIZE_SESSION`, to the requested `paymentGateways`.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ transactionInitialize(
+ """
+ The expected action called for the transaction. By default, the `channel.defaultTransactionFlowStrategy` will be used. The field can be used only by app that has `HANDLE_PAYMENTS` permission.
+ """
+ action: TransactionFlowStrategyEnum
+
+ """
+ The amount requested for initializing the payment gateway. If not provided, the difference between checkout.total - transactions that are already processed will be send.
+ """
+ amount: PositiveDecimal
+
+ """The ID of the checkout or order."""
+ id: ID!
+
+ """Payment gateway used to initialize the transaction."""
+ paymentGateway: PaymentGatewayToInitialize!
+ ): TransactionInitialize @doc(category: "Payments")
+
+ """
+ Processes a transaction session. It triggers the webhook `TRANSACTION_PROCESS_SESSION`, to the assigned `paymentGateways`.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ transactionProcess(
+ """The data that will be passed to the payment gateway."""
+ data: JSON
+
+ """The ID of the transaction to process."""
+ id: ID!
+ ): TransactionProcess @doc(category: "Payments")
+
"""
Creates a new page.
@@ -20802,6 +20977,158 @@ enum TransactionEventReportErrorCode @doc(category: "Payments") {
ALREADY_EXISTS
}
+"""
+Initializes a payment gateway session. It triggers the webhook `PAYMENT_GATEWAY_INITIALIZE_SESSION`, to the requested `paymentGateways`. If `paymentGateways` is not provided, the webhook will be send to all subscribed payment gateways.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type PaymentGatewayInitialize @doc(category: "Payments") {
+ gatewayConfigs: [PaymentGatewayConfig!]
+ errors: [PaymentGatewayInitializeError!]!
+}
+
+type PaymentGatewayConfig {
+ """The app identifier."""
+ id: String!
+
+ """The JSON data required to initialize the payment gateway."""
+ data: JSON
+ errors: [PaymentGatewayConfigError!]
+}
+
+scalar JSON
+
+type PaymentGatewayConfigError {
+ """
+ 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: PaymentGatewayConfigErrorCode!
+}
+
+"""An enumeration."""
+enum PaymentGatewayConfigErrorCode @doc(category: "Payments") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+}
+
+type PaymentGatewayInitializeError {
+ """
+ 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: PaymentGatewayInitializeErrorCode!
+}
+
+"""An enumeration."""
+enum PaymentGatewayInitializeErrorCode @doc(category: "Payments") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+}
+
+input PaymentGatewayToInitialize @doc(category: "Payments") {
+ """The identifier of the payment gateway app to initialize."""
+ id: String!
+
+ """The data that will be passed to the payment gateway."""
+ data: JSON
+}
+
+"""
+Initializes a transaction session. It triggers the webhook `TRANSACTION_INITIALIZE_SESSION`, to the requested `paymentGateways`.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionInitialize @doc(category: "Payments") {
+ """The initialized transaction."""
+ transaction: TransactionItem
+
+ """The event created for the initialized transaction."""
+ transactionEvent: TransactionEvent
+
+ """The JSON data required to finalize the payment."""
+ data: JSON
+ errors: [TransactionInitializeError!]!
+}
+
+type TransactionInitializeError {
+ """
+ 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: TransactionInitializeErrorCode!
+}
+
+"""An enumeration."""
+enum TransactionInitializeErrorCode @doc(category: "Payments") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+}
+
+"""
+Processes a transaction session. It triggers the webhook `TRANSACTION_PROCESS_SESSION`, to the assigned `paymentGateways`.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionProcess @doc(category: "Payments") {
+ """The processed transaction."""
+ transaction: TransactionItem
+
+ """The event created for the processed transaction."""
+ transactionEvent: TransactionEvent
+
+ """The json data required to finalize the payment."""
+ data: JSON
+ errors: [TransactionProcessError!]!
+}
+
+type TransactionProcessError {
+ """
+ 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: TransactionProcessErrorCode!
+}
+
+"""An enumeration."""
+enum TransactionProcessErrorCode @doc(category: "Payments") {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ TRANSACTION_ALREADY_PROCESSED
+ MISSING_PAYMENT_APP_RELATION
+ MISSING_PAYMENT_APP
+}
+
"""
Creates a new page.
@@ -23798,6 +24125,15 @@ input OrderSettingsInput @doc(category: "Orders") {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
markAsPaidStrategy: MarkAsPaidStrategyEnum
+
+ """
+ Determine the transaction flow strategy to be used. Include the selected option in the payload sent to the payment app, as a requested action 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.
+ """
+ defaultTransactionFlowStrategy: TransactionFlowStrategyEnum
}
"""
@@ -27450,6 +27786,30 @@ type CheckoutUpdated implements Event @doc(category: "Checkout") {
checkout: Checkout
}
+"""
+Event sent when checkout is fully paid with transactions.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type CheckoutFullyPaid implements Event @doc(category: "Checkout") {
+ """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
+
+ """The checkout the event relates to."""
+ checkout: Checkout
+}
+
"""
Event sent when checkout metadata is updated.
@@ -28765,11 +29125,124 @@ type TaxableObjectLine @doc(category: "Taxes") {
union TaxSourceLine = CheckoutLine | OrderLine
+"""
+Event sent when user wants to initialize the payment gateway.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type PaymentGatewayInitializeSession 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
+
+ """Checkout or order"""
+ sourceObject: OrderOrCheckout!
+
+ """Payment gateway data in JSON format, recieved from storefront."""
+ data: JSON
+
+ """Amount requested for initializing the payment gateway."""
+ amount: PositiveDecimal
+}
+
+union OrderOrCheckout = Checkout | Order
+
+"""
+Event sent when user starts processing the payment.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionInitializeSession 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!
+
+ """Checkout or order"""
+ sourceObject: OrderOrCheckout!
+
+ """Payment gateway data in JSON format, recieved from storefront."""
+ data: JSON
+
+ """Merchant reference assigned to this payment."""
+ merchantReference: String!
+
+ """Action to proceed for the transaction"""
+ action: TransactionProcessAction!
+}
+
+type TransactionProcessAction {
+ """Transaction amount to process."""
+ amount: PositiveDecimal!
+
+ """Currency of the amount."""
+ currency: String!
+ actionType: TransactionFlowStrategyEnum!
+}
+
+"""
+Event sent when user has additional payment action to process.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type TransactionProcessSession 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!
+
+ """Checkout or order"""
+ sourceObject: OrderOrCheckout!
+
+ """Payment gateway data in JSON format, recieved from storefront."""
+ data: JSON
+
+ """Merchant reference assigned to this payment."""
+ merchantReference: String!
+
+ """Action to proceed for the transaction"""
+ action: TransactionProcessAction!
+}
+
"""_Any value scalar as defined by Federation spec."""
scalar _Any
"""_Entity union as defined by Federation spec."""
-union _Entity = App | Address | User | Group | ProductVariant | Product | ProductType | ProductMedia | Category | Collection | PageType | Order
+union _Entity = App | Address | User | Group | ProductVariant | Product | ProductType | ProductMedia | Category | Collection | Order | PageType
"""_Service manifest as defined by Federation spec."""
type _Service {
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index f339a14528..618824e10f 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -443,6 +443,9 @@ class OrderSettingsUpdate(BaseMutation):
channel.automatically_fulfill_non_shippable_gift_card
),
mark_as_paid_strategy=channel.order_mark_as_paid_strategy,
+ default_transaction_flow_strategy=(
+ channel.default_transaction_flow_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 a8a0a0c5f9..a2c78248b3 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -15,6 +15,7 @@ from ....shipping.models import ShippingMethod
from ....site import GiftCardSettingsExpiryType
from ....site.models import Site
from ...account.enums import CountryCodeEnum
+from ...channel.enums import TransactionFlowStrategyEnum
from ...core.utils import str_to_enum
from ...tests.utils import assert_no_permission, get_graphql_content
@@ -1333,6 +1334,7 @@ ORDER_SETTINGS_UPDATE_MUTATION = """
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
markAsPaidStrategy
+ defaultTransactionFlowStrategy
}
}
}
@@ -1356,6 +1358,11 @@ def test_order_settings_update_by_staff(
response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]
assert response_settings["automaticallyConfirmAllNewOrders"] is False
assert response_settings["automaticallyFulfillNonShippableGiftCard"] is False
+ assert (
+ response_settings["defaultTransactionFlowStrategy"]
+ == TransactionFlowStrategyEnum.CHARGE.name
+ == channel_USD.default_transaction_flow_strategy.upper()
+ )
channel_PLN.refresh_from_db()
channel_USD.refresh_from_db()
assert channel_PLN.automatically_confirm_all_new_orders is False
@@ -1418,6 +1425,11 @@ def test_order_settings_update_by_app(
response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]
assert response_settings["automaticallyConfirmAllNewOrders"] is False
assert response_settings["automaticallyFulfillNonShippableGiftCard"] is False
+ assert (
+ response_settings["defaultTransactionFlowStrategy"]
+ == TransactionFlowStrategyEnum.CHARGE.name
+ == channel_USD.default_transaction_flow_strategy.upper()
+ )
channel_PLN.refresh_from_db()
channel_USD.refresh_from_db()
assert channel_PLN.automatically_confirm_all_new_orders is False
diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.py
index 4668fb0910..5a843ab10c 100644
--- a/saleor/graphql/webhook/subscription_payload.py
+++ b/saleor/graphql/webhook/subscription_payload.py
@@ -10,7 +10,6 @@ from promise import Promise
from ...app.models import App
from ...core.exceptions import PermissionDenied
-from ...plugins.manager import PluginsManager
from ...settings import get_host
from ..core import SaleorContext
from ..utils import format_error
@@ -19,7 +18,10 @@ logger = get_task_logger(__name__)
def initialize_request(
- requestor=None, sync_event=False, allow_replica=True
+ requestor=None,
+ sync_event=False,
+ allow_replica=True,
+ event_type: Optional[str] = None,
) -> SaleorContext:
"""Prepare a request object for webhook subscription.
@@ -28,9 +30,6 @@ def initialize_request(
return: HttpRequest
"""
- def _get_plugins(requestor_getter):
- return PluginsManager(settings.PLUGINS, requestor_getter)
-
request_time = timezone.now()
request = SaleorContext()
request.path = "/graphql/"
@@ -42,6 +41,7 @@ def initialize_request(
request.META["SERVER_PORT"] = "443"
setattr(request, "sync_event", sync_event)
+ setattr(request, "event_type", event_type)
request.requestor = requestor
request.request_time = request_time
request.allow_replica = allow_replica
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 6ea3f635ed..1fddfc7893 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -11,7 +11,7 @@ from ...discount.models import SaleTranslation, VoucherTranslation
from ...menu.models import MenuItemTranslation
from ...order.utils import get_all_shipping_methods_for_order
from ...page.models import PageTranslation
-from ...payment.interface import TransactionActionData
+from ...payment.interface import TransactionActionData, TransactionSessionData
from ...product.models import (
CategoryTranslation,
CollectionTranslation,
@@ -25,6 +25,7 @@ from ..account.types import User as UserType
from ..app.types import App as AppType
from ..channel import ChannelContext
from ..channel.dataloaders import ChannelByIdLoader
+from ..channel.enums import TransactionFlowStrategyEnum
from ..core import ResolveInfo
from ..core.descriptions import (
ADDED_IN_32,
@@ -39,8 +40,9 @@ from ..core.descriptions import (
ADDED_IN_313,
PREVIEW_FEATURE,
)
-from ..core.scalars import PositiveDecimal
+from ..core.scalars import JSON, PositiveDecimal
from ..core.types import NonNullList, SubscriptionObjectType
+from ..core.types.order_or_checkout import OrderOrCheckout
from ..order.dataloaders import OrderByIdLoader
from ..payment.enums import TransactionActionEnum
from ..payment.types import TransactionItem
@@ -1225,6 +1227,18 @@ class CheckoutUpdated(SubscriptionObjectType, CheckoutBase):
)
+class CheckoutFullyPaid(SubscriptionObjectType, CheckoutBase):
+ class Meta:
+ root_type = "Checkout"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = (
+ "Event sent when checkout is fully paid with transactions."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ )
+
+
class CheckoutMetadataUpdated(SubscriptionObjectType, CheckoutBase):
class Meta:
root_type = "Checkout"
@@ -1603,6 +1617,137 @@ class TransactionCancelationRequested(TransactionActionBase, SubscriptionObjectT
)
+class PaymentGatewayInitializeSession(SubscriptionObjectType):
+ source_object = graphene.Field(
+ OrderOrCheckout, description="Checkout or order", required=True
+ )
+ data = graphene.Field(
+ JSON,
+ description="Payment gateway data in JSON format, recieved from storefront.",
+ )
+ amount = graphene.Field(
+ PositiveDecimal,
+ description="Amount requested for initializing the payment gateway.",
+ )
+
+ class Meta:
+ interfaces = (Event,)
+ root_type = None
+ enable_dry_run = False
+ description = (
+ "Event sent when user wants to initialize the payment gateway."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ )
+
+ @staticmethod
+ def resolve_source_object(root, _info: ResolveInfo):
+ _, objects = root
+ source_object, _, _ = objects
+ return source_object
+
+ @staticmethod
+ def resolve_data(root, _info: ResolveInfo):
+ _, objects = root
+ _, data, _ = objects
+ return data
+
+ @staticmethod
+ def resolve_amount(root, _info: ResolveInfo):
+ _, objects = root
+ _, _, amount = objects
+ return amount
+
+
+class TransactionProcessAction(SubscriptionObjectType, AbstractType):
+ amount = PositiveDecimal(
+ description="Transaction amount to process.", required=True
+ )
+ currency = graphene.String(description="Currency of the amount.", required=True)
+ action_type = graphene.Field(TransactionFlowStrategyEnum, required=True)
+
+
+class TransactionSessionBase(SubscriptionObjectType, AbstractType):
+ transaction = graphene.Field(
+ TransactionItem, description="Look up a transaction.", required=True
+ )
+ source_object = graphene.Field(
+ OrderOrCheckout, description="Checkout or order", required=True
+ )
+ data = graphene.Field(
+ JSON,
+ description="Payment gateway data in JSON format, recieved from storefront.",
+ )
+ merchant_reference = graphene.String(
+ description="Merchant reference assigned to this payment.", required=True
+ )
+ action = graphene.Field(
+ TransactionProcessAction,
+ description="Action to proceed for the transaction",
+ required=True,
+ )
+
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def resolve_transaction(
+ cls, root: tuple[str, TransactionSessionData], _info: ResolveInfo
+ ):
+ _, transaction_session_data = root
+ return transaction_session_data.transaction
+
+ @classmethod
+ def resolve_source_object(
+ cls, root: tuple[str, TransactionSessionData], _info: ResolveInfo
+ ):
+ _, transaction_session_data = root
+ return transaction_session_data.source_object
+
+ @classmethod
+ def resolve_data(cls, root: tuple[str, TransactionSessionData], _info: ResolveInfo):
+ _, transaction_session_data = root
+ return transaction_session_data.payment_gateway.data
+
+ @classmethod
+ def resolve_merchant_reference(
+ cls, root: tuple[str, TransactionSessionData], _info: ResolveInfo
+ ):
+ transaction = cls.resolve_transaction(root, _info)
+ return graphene.Node.to_global_id("TransactionItem", transaction.token)
+
+ @classmethod
+ def resolve_action(
+ cls, root: tuple[str, TransactionSessionData], _info: ResolveInfo
+ ):
+ _, transaction_session_data = root
+ return transaction_session_data.action
+
+
+class TransactionInitializeSession(TransactionSessionBase):
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent when user starts processing the payment."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ )
+
+
+class TransactionProcessSession(TransactionSessionBase):
+ class Meta:
+ root_type = None
+ enable_dry_run = False
+ interfaces = (Event,)
+ description = (
+ "Event sent when user has additional payment action to process."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ )
+
+
class TransactionItemMetadataUpdated(SubscriptionObjectType):
transaction = graphene.Field(
TransactionItem,
@@ -2078,6 +2223,7 @@ WEBHOOK_TYPES_MAP = {
WebhookEventAsyncType.COLLECTION_METADATA_UPDATED: CollectionMetadataUpdated,
WebhookEventAsyncType.CHECKOUT_CREATED: CheckoutCreated,
WebhookEventAsyncType.CHECKOUT_UPDATED: CheckoutUpdated,
+ WebhookEventAsyncType.CHECKOUT_FULLY_PAID: CheckoutFullyPaid,
WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED: CheckoutMetadataUpdated,
WebhookEventAsyncType.PAGE_CREATED: PageCreated,
WebhookEventAsyncType.PAGE_UPDATED: PageUpdated,
@@ -2134,4 +2280,9 @@ WEBHOOK_TYPES_MAP = {
),
WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES: CalculateTaxes,
WebhookEventSyncType.ORDER_CALCULATE_TAXES: CalculateTaxes,
+ WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION: (
+ PaymentGatewayInitializeSession
+ ),
+ WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION: TransactionInitializeSession,
+ WebhookEventSyncType.TRANSACTION_PROCESS_SESSION: TransactionProcessSession,
}
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 a5a758bbad..0c117daa40 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
@@ -279,6 +279,7 @@ def async_subscription_webhooks_with_root_objects(
subscription_collection_metadata_updated_webhook,
subscription_checkout_created_webhook,
subscription_checkout_updated_webhook,
+ subscription_checkout_fully_paid_webhook,
subscription_checkout_metadata_updated_webhook,
subscription_page_created_webhook,
subscription_page_updated_webhook,
@@ -338,6 +339,8 @@ def async_subscription_webhooks_with_root_objects(
order = fulfilled_order
invoice = order.invoices.first()
page_type = page.page_type
+ transaction_item_created_by_app.use_old_id = True
+ transaction_item_created_by_app.save()
return {
events.ADDRESS_UPDATED: [subscription_address_updated_webhook, address],
@@ -492,6 +495,10 @@ def async_subscription_webhooks_with_root_objects(
],
events.CHECKOUT_CREATED: [subscription_checkout_created_webhook, checkout],
events.CHECKOUT_UPDATED: [subscription_checkout_updated_webhook, checkout],
+ events.CHECKOUT_FULLY_PAID: [
+ subscription_checkout_fully_paid_webhook,
+ checkout,
+ ],
events.CHECKOUT_METADATA_UPDATED: [
subscription_checkout_metadata_updated_webhook,
checkout,
@@ -584,7 +591,6 @@ def test_webhook_dry_run_root_type(
for event_name, event_type in WEBHOOK_TYPES_MAP.items():
if not event_type._meta.enable_dry_run:
continue
-
webhook = async_subscription_webhooks_with_root_objects[event_name][0]
object = async_subscription_webhooks_with_root_objects[event_name][1]
object_id = graphene.Node.to_global_id(object.__class__.__name__, object.pk)
@@ -598,3 +604,27 @@ def test_webhook_dry_run_root_type(
# then
assert not content["data"]["webhookDryRun"]["errors"]
assert content["data"]["webhookDryRun"]["payload"]
+
+
+def test_webhook_dry_run_root_type_for_transaction_item_metadata_updated(
+ superuser_api_client,
+ transaction_item_generator,
+ subscription_transaction_item_metadata_updated_webhook,
+):
+ # given
+ query = WEBHOOK_DRY_RUN_MUTATION
+ transaction = transaction_item_generator(use_old_id=False)
+ webhook = subscription_transaction_item_metadata_updated_webhook
+
+ object_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+
+ variables = {"objectId": object_id, "query": webhook.subscription_query}
+
+ # when
+ response = superuser_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["webhookDryRun"]["errors"]
+ payload = content["data"]["webhookDryRun"]["payload"]
+ assert json.loads(payload)["transaction"]["id"] == object_id
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 2815075792..ae4b16f71d 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -86,7 +86,7 @@ class OrderFulfillmentLineInfo(TypedDict):
def order_created(
order_info: "OrderInfo",
- user: User,
+ user: Optional[User],
app: Optional["App"],
manager: "PluginsManager",
from_draft: bool = False,
@@ -123,7 +123,7 @@ def order_created(
def order_confirmed(
order: "Order",
- user: User,
+ user: Optional[User],
app: Optional["App"],
manager: "PluginsManager",
send_confirmation_email: bool = False,
diff --git a/saleor/order/search.py b/saleor/order/search.py
index e0d5e2d232..391ef64551 100644
--- a/saleor/order/search.py
+++ b/saleor/order/search.py
@@ -89,7 +89,7 @@ def generate_order_transactions_search_vector_value(
]:
transaction_vectors.append(
NoValidationSearchVector(
- Value(graphene.Node.to_global_id("TransactionItem", transaction.id)),
+ Value(graphene.Node.to_global_id("TransactionItem", transaction.token)),
config="simple",
weight="D",
)
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 6d8a970176..9a9f57e772 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -177,6 +177,10 @@ class TransactionEventType:
AUTHORIZATION_FAILURE - represents failure authorization.
AUTHORIZATION_ADJUSTMENT - represents authorization adjustment.
AUTHORIZATION_REQUEST - represents authorization request.
+ AUTHORIZATION_ACTION_REQUIRED - represents authorization that needs
+ additional actions from the customer.
+ CHARGE_ACTION_REQUIRED - represents charge that needs
+ additional actions from the customer.
CHARGE_SUCCESS - represents success charge.
CHARGE_FAILURE - represents failure charge.
CHARGE_BACK - represents chargeback.
@@ -195,9 +199,11 @@ class TransactionEventType:
AUTHORIZATION_FAILURE = "authorization_failure"
AUTHORIZATION_ADJUSTMENT = "authorization_adjustment"
AUTHORIZATION_REQUEST = "authorization_request"
+ AUTHORIZATION_ACTION_REQUIRED = "authorization_action_required"
CHARGE_SUCCESS = "charge_success"
CHARGE_FAILURE = "charge_failure"
CHARGE_BACK = "charge_back"
+ CHARGE_ACTION_REQUIRED = "charge_action_required"
CHARGE_REQUEST = "charge_request"
REFUND_SUCCESS = "refund_success"
REFUND_FAILURE = "refund_failure"
@@ -213,6 +219,11 @@ class TransactionEventType:
(AUTHORIZATION_FAILURE, "Represents failure authorization"),
(AUTHORIZATION_ADJUSTMENT, "Represents authorization adjustment"),
(AUTHORIZATION_REQUEST, "Represents authorization request"),
+ (
+ AUTHORIZATION_ACTION_REQUIRED,
+ "Represents additional actions required for authorization.",
+ ),
+ (CHARGE_ACTION_REQUIRED, "Represents additional actions required for charge."),
(CHARGE_SUCCESS, "Represents success charge"),
(CHARGE_FAILURE, "Represents failure charge"),
(CHARGE_BACK, "Represents chargeback."),
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index ff94397a8f..5d10fc825a 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -54,3 +54,30 @@ class TransactionEventReportErrorCode(Enum):
NOT_FOUND = "not_found"
INCORRECT_DETAILS = "incorrect_details"
ALREADY_EXISTS = "already_exists"
+
+
+class PaymentGatewayConfigErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+
+
+class PaymentGatewayInitializeErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+
+
+class TransactionInitializeErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+
+
+class TransactionProcessErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ TRANSACTION_ALREADY_PROCESSED = "transaction_already_processed"
+ MISSING_PAYMENT_APP_RELATION = "missing_payment_app_relation"
+ MISSING_PAYMENT_APP = "missing_payment_app"
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 4ad87b9071..e0f12671ca 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -8,10 +8,12 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
from ..order import FulfillmentLineData
from ..order.fetch import OrderLineInfo
from ..payment.models import TransactionEvent, TransactionItem
-from . import TransactionEventType
if TYPE_CHECKING:
from ..app.models import App
+ from ..checkout.models import Checkout
+ from ..order.models import Order
+
JSONValue = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
JSONType = Union[Dict[str, JSONValue], List[JSONValue]]
@@ -27,9 +29,9 @@ class TransactionActionData:
@dataclass
class TransactionRequestEventResponse:
- psp_reference: str
- type: "TransactionEventType"
- amount: Optional[Decimal] = None
+ psp_reference: Optional[str]
+ type: str
+ amount: Decimal
time: Optional[datetime] = None
external_url: Optional[str] = ""
message: Optional[str] = ""
@@ -37,7 +39,7 @@ class TransactionRequestEventResponse:
@dataclass
class TransactionRequestResponse:
- psp_reference: str
+ psp_reference: Optional[str]
event: Optional["TransactionRequestEventResponse"] = None
@@ -50,6 +52,28 @@ class TransactionData:
amount: Dict[str, str]
+@dataclass
+class PaymentGatewayData:
+ app_identifier: str
+ data: Optional[Dict[Any, Any]] = None
+ error: Optional[str] = None
+
+
+@dataclass
+class TransactionProcessActionData:
+ action_type: str
+ amount: Decimal
+ currency: str
+
+
+@dataclass
+class TransactionSessionData:
+ transaction: "TransactionItem"
+ source_object: Union["Checkout", "Order"]
+ action: TransactionProcessActionData
+ payment_gateway: PaymentGatewayData
+
+
@dataclass
class PaymentMethodInfo:
"""Uniform way to represent payment method information."""
diff --git a/saleor/payment/migrations/0042_auto_20230320_1252.py b/saleor/payment/migrations/0042_auto_20230320_1252.py
new file mode 100644
index 0000000000..57fba39a59
--- /dev/null
+++ b/saleor/payment/migrations/0042_auto_20230320_1252.py
@@ -0,0 +1,30 @@
+# Generated by Django 3.2.18 on 2023-03-20 12:52
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0041_add_calculation_transaction_events"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="transactionitem",
+ name="token",
+ field=models.UUIDField(null=True, unique=True),
+ ),
+ migrations.AddField(
+ model_name="transactionitem",
+ name="use_old_id",
+ field=models.BooleanField(default=True),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE payment_transactionitem
+ ALTER COLUMN use_old_id
+ SET DEFAULT true;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/payment/migrations/0043_populate_transaction_item_token.py b/saleor/payment/migrations/0043_populate_transaction_item_token.py
new file mode 100644
index 0000000000..c5ddc4f661
--- /dev/null
+++ b/saleor/payment/migrations/0043_populate_transaction_item_token.py
@@ -0,0 +1,48 @@
+# Generated by Django 3.2.18 on 2023-03-20 12:52
+
+from django.contrib.postgres.functions import RandomUUID
+from django.db import migrations
+from django.db.models import Case, When
+
+BATCH_SIZE = 1000
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]
+ pks = list(qs.values_list("pk", flat=True))
+
+ if not pks:
+ break
+
+ yield pks
+
+ start_pk = pks[-1]
+
+
+def update_transaction_token_field_migration(apps, _schema_editor):
+ TransactionItem = apps.get_model("payment", "TransactionItem")
+ queryset = TransactionItem.objects.filter(token__isnull=True)
+ for batch_pks in queryset_in_batches(queryset):
+ TransactionItem.objects.filter(id__in=batch_pks).update(
+ token=Case(When(token__isnull=True, then=RandomUUID()), default="token")
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0042_auto_20230320_1252"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ update_transaction_token_field_migration,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/payment/migrations/0046_alter_transactionevent_type.py b/saleor/payment/migrations/0046_alter_transactionevent_type.py
new file mode 100644
index 0000000000..e72f3f3ea8
--- /dev/null
+++ b/saleor/payment/migrations/0046_alter_transactionevent_type.py
@@ -0,0 +1,46 @@
+# Generated by Django 3.2.18 on 2023-03-10 15:42
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0045_alter_transactionevent_currency"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="transactionevent",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("authorization_success", "Represents success authorization"),
+ ("authorization_failure", "Represents failure authorization"),
+ ("authorization_adjustment", "Represents authorization adjustment"),
+ ("authorization_request", "Represents authorization request"),
+ (
+ "authorization_action_required",
+ "Represents additional actions required for authorization.",
+ ),
+ (
+ "charge_action_required",
+ "Represents additional actions required for charge.",
+ ),
+ ("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 an info event"),
+ ],
+ default="info",
+ max_length=128,
+ ),
+ ),
+ ]
diff --git a/saleor/payment/migrations/0047_merge_20230321_1456.py b/saleor/payment/migrations/0047_merge_20230321_1456.py
new file mode 100644
index 0000000000..812a63b45f
--- /dev/null
+++ b/saleor/payment/migrations/0047_merge_20230321_1456.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.18 on 2023-03-21 14:56
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0043_populate_transaction_item_token"),
+ ("payment", "0046_alter_transactionevent_type"),
+ ]
+
+ operations = []
diff --git a/saleor/payment/migrations/0048_populate_transaction_item_token.py b/saleor/payment/migrations/0048_populate_transaction_item_token.py
new file mode 100644
index 0000000000..e9fb1ca67c
--- /dev/null
+++ b/saleor/payment/migrations/0048_populate_transaction_item_token.py
@@ -0,0 +1,26 @@
+from django.contrib.postgres.functions import RandomUUID
+from django.db import migrations
+from django.db.models import Case, When
+
+
+# This data migration is handled in the 0043 with celery tasks.
+# 0043 is due to zero-downtime policy, this migration is to ensure
+# that we can change token to non-nullable.
+def populate_transaction_item_token(apps, schema_editor):
+ TransactionItem = apps.get_model("payment", "TransactionItem")
+
+ TransactionItem.objects.filter(token__isnull=True).update(
+ token=Case(When(token__isnull=True, then=RandomUUID()), default="token")
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0047_merge_20230321_1456"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_transaction_item_token, migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/payment/migrations/0049_auto_20230322_0634.py b/saleor/payment/migrations/0049_auto_20230322_0634.py
new file mode 100644
index 0000000000..c6270b3336
--- /dev/null
+++ b/saleor/payment/migrations/0049_auto_20230322_0634.py
@@ -0,0 +1,32 @@
+# Generated by Django 3.2.18 on 2023-03-22 06:34
+
+import uuid
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("payment", "0048_populate_transaction_item_token"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="transactionitem",
+ name="token",
+ field=models.UUIDField(default=uuid.uuid4, unique=True),
+ ),
+ migrations.AlterField(
+ model_name="transactionitem",
+ name="use_old_id",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE payment_transactionitem
+ ALTER COLUMN use_old_id
+ SET DEFAULT False;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 79214f6e39..39d7a741b8 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -1,5 +1,6 @@
from decimal import Decimal
from operator import attrgetter
+from uuid import uuid4
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
@@ -28,6 +29,8 @@ from . import (
class TransactionItem(ModelWithMetadata):
+ token = models.UUIDField(unique=True, default=uuid4)
+ use_old_id = models.BooleanField(default=False)
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="")
diff --git a/saleor/payment/tests/test_transaction_item_calculations.py b/saleor/payment/tests/test_transaction_item_calculations.py
index 5155313ec4..3a7a02de05 100644
--- a/saleor/payment/tests/test_transaction_item_calculations.py
+++ b/saleor/payment/tests/test_transaction_item_calculations.py
@@ -1,42 +1,13 @@
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 ..models import 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"),
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 1a25605bac..4eef915c41 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -21,6 +21,7 @@ from ..utils import (
create_failed_transaction_event,
create_manual_adjustment_events,
create_payment_lines_information,
+ create_transaction_event_for_transaction_session,
create_transaction_event_from_request_and_webhook_response,
get_channel_slug_from_payment,
get_correct_event_types_based_on_request_type,
@@ -320,9 +321,11 @@ def test_parse_transaction_action_data_with_incorrect_result():
def test_parse_transaction_action_data_with_event_only_mandatory_fields():
# given
expected_psp_reference = "psp:122:222"
+ expected_amount = Decimal("10.00")
response_data = {
"pspReference": expected_psp_reference,
"result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ "amount": expected_amount,
}
# when
@@ -337,7 +340,7 @@ def test_parse_transaction_action_data_with_event_only_mandatory_fields():
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.amount == expected_amount
assert parsed_data.event.time == timezone.now()
assert parsed_data.event.external_url == ""
assert parsed_data.event.message == ""
@@ -908,3 +911,232 @@ def test_create_manual_adjustment_events_additional_cancel(
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)
+
+
+ "response_result, transaction_amount_field_name",
+ [
+ (TransactionEventType.AUTHORIZATION_REQUEST, "authorize_pending_value"),
+ (TransactionEventType.AUTHORIZATION_SUCCESS, "authorized_value"),
+ (TransactionEventType.CHARGE_REQUEST, "charge_pending_value"),
+ (TransactionEventType.CHARGE_SUCCESS, "charged_value"),
+ ],
+)
+def test_create_transaction_event_for_transaction_session_success_response(
+ response_result,
+ transaction_amount_field_name,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+):
+ # given
+ expected_amount = Decimal("15")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+ response["amount"] = expected_amount
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction, include_in_calculations=False
+ )
+ # when
+ response_event = create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ discounts=[],
+ transaction_webhook_response=response,
+ )
+
+ # then
+ assert response_event.include_in_calculations
+ assert response_event.amount_value == expected_amount
+ transaction.refresh_from_db()
+ assert getattr(transaction, transaction_amount_field_name) == expected_amount
+
+
+ "response_result, transaction_amount_field_name",
+ [
+ (TransactionEventType.AUTHORIZATION_REQUEST, "authorize_pending_value"),
+ (TransactionEventType.AUTHORIZATION_SUCCESS, "authorized_value"),
+ (TransactionEventType.CHARGE_REQUEST, "charge_pending_value"),
+ (TransactionEventType.CHARGE_SUCCESS, "charged_value"),
+ ],
+)
+def test_create_transaction_event_for_transaction_session_success_response_with_0(
+ response_result,
+ transaction_amount_field_name,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+):
+ # given
+ expected_amount = Decimal("0")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+ response["amount"] = expected_amount
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction, include_in_calculations=False
+ )
+ # when
+ response_event = create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ discounts=[],
+ transaction_webhook_response=response,
+ )
+
+ # then
+ assert response_event.include_in_calculations
+ assert response_event.amount_value == expected_amount
+ transaction.refresh_from_db()
+ assert getattr(transaction, transaction_amount_field_name) == expected_amount
+
+
+ "response_result",
+ [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+)
+def test_create_transaction_event_for_transaction_session_not_success_events(
+ response_result,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+):
+ # given
+ expected_amount = Decimal("15")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+ response["amount"] = expected_amount
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction,
+ include_in_calculations=False,
+ amount_value=expected_amount,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ # when
+ response_event = create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ discounts=[],
+ transaction_webhook_response=response,
+ )
+
+ # then
+ assert response_event.amount_value == expected_amount
+ assert response_event.type in [response_result, TransactionEventType.CHARGE_FAILURE]
+ transaction.refresh_from_db()
+ assert transaction.authorized_value == Decimal("0")
+ assert transaction.charged_value == Decimal("0")
+ assert transaction.authorize_pending_value == Decimal("0")
+ assert transaction.charge_pending_value == Decimal("0")
+
+
+ "response_result",
+ [
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_REQUEST,
+ ],
+)
+def test_create_transaction_event_for_transaction_session_missing_psp_reference(
+ response_result,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+):
+ # given
+ expected_amount = Decimal("15")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+ response["amount"] = expected_amount
+ del response["pspReference"]
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction,
+ include_in_calculations=False,
+ amount_value=expected_amount,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ # when
+ response_event = create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ discounts=[],
+ transaction_webhook_response=response,
+ )
+
+ # then
+ assert response_event.amount_value == expected_amount
+ assert response_event.type == TransactionEventType.CHARGE_FAILURE
+ transaction.refresh_from_db()
+ assert transaction.authorized_value == Decimal("0")
+ assert transaction.charged_value == Decimal("0")
+ assert transaction.authorize_pending_value == Decimal("0")
+ assert transaction.charge_pending_value == Decimal("0")
+
+
+ "response_result",
+ [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ ],
+)
+def test_create_transaction_event_for_transaction_session_missing_reference_with_action(
+ response_result,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+):
+ # given
+ expected_amount = Decimal("15")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+ response["amount"] = expected_amount
+ del response["pspReference"]
+ transaction = transaction_item_generator()
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction,
+ include_in_calculations=False,
+ amount_value=expected_amount,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ # when
+ response_event = create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ discounts=[],
+ transaction_webhook_response=response,
+ )
+
+ # then
+ assert response_event.amount_value == expected_amount
+ assert response_event.type == response_result
+ transaction.refresh_from_db()
+ assert transaction.authorized_value == Decimal("0")
+ assert transaction.charged_value == Decimal("0")
+ assert transaction.authorize_pending_value == Decimal("0")
+ assert transaction.charge_pending_value == Decimal("0")
diff --git a/saleor/payment/transaction_item_calculations.py b/saleor/payment/transaction_item_calculations.py
index f4658cf38f..df147acfcc 100644
--- a/saleor/payment/transaction_item_calculations.py
+++ b/saleor/payment/transaction_item_calculations.py
@@ -349,7 +349,7 @@ def calculate_transaction_amount_based_on_events(transaction: TransactionItem):
_recalculate_cancel_amounts(transaction, cancel_events)
-def recalculate_transaction_amounts(transaction: TransactionItem):
+def recalculate_transaction_amounts(transaction: TransactionItem, save: bool = True):
"""Recalculate transaction amounts.
The function calculates the transaction amounts based on the amounts that
@@ -378,6 +378,27 @@ def recalculate_transaction_amounts(transaction: TransactionItem):
"""
calculate_transaction_amount_based_on_events(transaction)
+ 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)
+
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"))
@@ -394,15 +415,17 @@ def recalculate_transaction_amounts(transaction: TransactionItem):
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",
- ]
- )
+
+ if save:
+ 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 c1e8189079..bced96c855 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -3,7 +3,7 @@ import json
import logging
from datetime import datetime
from decimal import Decimal
-from typing import Any, Dict, Optional, cast, overload
+from typing import Any, Dict, Iterable, Optional, Union, cast, overload
import graphene
from babel.numbers import get_currency_precision
@@ -14,10 +14,13 @@ from django.utils import timezone
from ..account.models import User
from ..app.models import App
+from ..channel import TransactionFlowStrategy
+from ..checkout.actions import transaction_amounts_for_checkout_updated
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 import DiscountInfo
from ..discount.utils import fetch_active_discounts
from ..graphql.core.utils import str_to_enum
from ..order.models import Order
@@ -37,14 +40,17 @@ from .interface import (
AddressData,
GatewayResponse,
PaymentData,
+ PaymentGatewayData,
PaymentLineData,
PaymentLinesData,
PaymentMethodInfo,
RefundData,
StorePaymentMethodEnum,
TransactionData,
+ TransactionProcessActionData,
TransactionRequestEventResponse,
TransactionRequestResponse,
+ TransactionSessionData,
)
from .models import Payment, Transaction, TransactionEvent, TransactionItem
from .transaction_item_calculations import recalculate_transaction_amounts
@@ -690,6 +696,17 @@ def payment_owned_by_user(payment_pk: int, user) -> bool:
)
+def get_final_session_statuses():
+ return [
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_REQUEST,
+ ]
+
+
def get_correct_event_types_based_on_request_type(request_type: str) -> list[str]:
type_map = {
TransactionEventType.AUTHORIZATION_REQUEST: [
@@ -709,6 +726,11 @@ def get_correct_event_types_based_on_request_type(request_type: str) -> list[str
TransactionEventType.CANCEL_FAILURE,
TransactionEventType.CANCEL_SUCCESS,
],
+ "session-request": [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ *get_final_session_statuses(),
+ ],
}
return type_map.get(request_type, [])
@@ -717,10 +739,15 @@ def parse_transaction_event_data(
event_data: dict,
parsed_event_data: dict,
error_field_msg: list[str],
- psp_reference: str,
+ psp_reference: Optional[str],
request_type: str,
+ event_is_optional: bool = True,
):
- if event_data.get("amount") is None and not event_data.get("result"):
+ if (
+ event_is_optional
+ and 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."
@@ -753,14 +780,16 @@ def parse_transaction_event_data(
logger.warning(missing_msg, "result")
error_field_msg.append(missing_msg % "result")
- if amount_data := event_data.get("amount"):
+ amount_data = event_data.get("amount")
+ if amount_data is not None:
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
+ logger.warning(missing_msg, "amount")
+ error_field_msg.append(missing_msg % "amount")
if event_time_data := event_data.get("time"):
try:
@@ -781,7 +810,10 @@ error_msg = str
def parse_transaction_action_data(
- response_data: Any, request_type: str
+ response_data: Any,
+ request_type: str,
+ event_is_optional: bool = True,
+ psp_reference_is_optional: bool = False,
) -> tuple[Optional["TransactionRequestResponse"], Optional[error_msg]]:
"""Parse response from transaction action webhook.
@@ -790,7 +822,7 @@ def parse_transaction_action_data(
If unable to parse, None will be returned.
"""
psp_reference: str = response_data.get("pspReference")
- if not psp_reference:
+ if not psp_reference and not psp_reference_is_optional:
msg: str = "Missing `pspReference` field in the response."
logger.error(msg)
return None, msg
@@ -803,6 +835,7 @@ def parse_transaction_action_data(
error_field_msg=error_field_msg,
psp_reference=psp_reference,
request_type=request_type,
+ event_is_optional=event_is_optional,
)
if error_field_msg:
@@ -885,6 +918,14 @@ def authorization_success_already_exists(transaction_id: int) -> bool:
def get_already_existing_event(event: TransactionEvent) -> Optional[TransactionEvent]:
+ if event.type in [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ TransactionEventType.INFO,
+ ]:
+ # We don't need to take into account the events that are only a record of
+ # additional action required from the payment app.
+ return None
existing_event = (
TransactionEvent.objects.filter(
transaction_id=event.transaction_id,
@@ -946,18 +987,178 @@ def deduplicate_event(
return event, error_message
-def create_transaction_event_from_request_and_webhook_response(
+def _create_event_from_response(
+ response: TransactionRequestEventResponse,
+ app: App,
+ transaction_id: int,
+ currency: str,
+) -> tuple[Optional[TransactionEvent], Optional[error_msg]]:
+ app_identifier = None
+ if app and app.identifier:
+ app_identifier = app.identifier
+ event = TransactionEvent(
+ psp_reference=response.psp_reference,
+ created_at=response.time or timezone.now(),
+ type=response.type,
+ amount_value=response.amount,
+ external_url=response.external_url,
+ currency=currency,
+ transaction_id=transaction_id,
+ message=response.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 None, error_msg
+ if not event.pk:
+ event.save()
+ return event, None
+
+
+def _get_parsed_transaction_action_data(
+ transaction_webhook_response: Optional[Dict[str, Any]],
+ event_type: str,
+ event_is_optional: bool = True,
+ psp_reference_is_optional: bool = False,
+) -> tuple[Optional["TransactionRequestResponse"], Optional[error_msg]]:
+ if transaction_webhook_response is None:
+ return None, "Failed to delivery request."
+
+ transaction_request_response, error_msg = parse_transaction_action_data(
+ transaction_webhook_response,
+ event_type,
+ event_is_optional=event_is_optional,
+ psp_reference_is_optional=psp_reference_is_optional,
+ )
+ if not transaction_request_response:
+ return None, error_msg or ""
+ return transaction_request_response, None
+
+
+def update_order_with_transaction_details(transaction: TransactionItem):
+ if transaction.order_id:
+ order = cast(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",
+ ]
+ )
+
+
+def create_transaction_event_for_transaction_session(
request_event: TransactionEvent,
app: App,
+ manager: "PluginsManager",
+ discounts: Optional[Iterable["DiscountInfo"]],
transaction_webhook_response: Optional[Dict[str, Any]] = None,
):
- if transaction_webhook_response is None:
+ request_event_type = "session-request"
+
+ transaction_request_response, error_msg = _get_parsed_transaction_action_data(
+ transaction_webhook_response=transaction_webhook_response,
+ event_type=request_event_type,
+ event_is_optional=False,
+ psp_reference_is_optional=True,
+ )
+ if not transaction_request_response or not transaction_request_response.event:
+ return create_failed_transaction_event(request_event, cause=error_msg or "")
+
+ event = None
+ request_event_update_fields = []
+ response_event = transaction_request_response.event
+ if not response_event.psp_reference and response_event.type not in [
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ ]:
return create_failed_transaction_event(
- request_event, cause="Failed to delivery request."
+ request_event,
+ cause=(
+ f"Providing `pspReference` is required for "
+ f"{response_event.type.upper()}"
+ ),
)
- request_event_type = request_event.type
- transaction_request_response, error_msg = parse_transaction_action_data(
- transaction_webhook_response, request_event_type
+ elif response_event.type in [
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_REQUEST,
+ ]:
+ request_event.type = response_event.type
+ request_event.amount_value = response_event.amount
+ request_event.psp_reference = response_event.psp_reference
+ request_event.include_in_calculations = True
+ request_event_update_fields.extend(
+ [
+ "type",
+ "amount_value",
+ "psp_reference",
+ "include_in_calculations",
+ ]
+ )
+ event = request_event
+ else:
+ event, error_message = _create_event_from_response(
+ response_event,
+ app=app,
+ transaction_id=request_event.transaction_id,
+ currency=request_event.currency,
+ )
+ if not event:
+ return create_failed_transaction_event(
+ request_event, cause=error_message or ""
+ )
+ request_event.psp_reference = event.psp_reference
+ request_event_update_fields.append("psp_reference")
+ if request_event_update_fields:
+ request_event.save(update_fields=request_event_update_fields)
+
+ if event.type in [
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.CHARGE_SUCCESS,
+ ]:
+ transaction_item = event.transaction
+ transaction_item.psp_reference = event.psp_reference
+ recalculate_transaction_amounts(transaction_item, save=False)
+ transaction_item.save(
+ update_fields=[
+ "authorized_value",
+ "charged_value",
+ "refunded_value",
+ "canceled_value",
+ "authorize_pending_value",
+ "charge_pending_value",
+ "refund_pending_value",
+ "cancel_pending_value",
+ "psp_reference",
+ ]
+ )
+ if transaction_item.order_id:
+ update_order_with_transaction_details(transaction_item)
+ elif transaction_item.checkout_id:
+ transaction_amounts_for_checkout_updated(
+ transaction_item, discounts, manager
+ )
+ return event
+
+
+def create_transaction_event_from_request_and_webhook_response(
+ request_event: TransactionEvent,
+ app: App,
+ transaction_webhook_response: Optional[Dict[str, Any]] = None,
+):
+ transaction_request_response, error_msg = _get_parsed_transaction_action_data(
+ transaction_webhook_response=transaction_webhook_response,
+ event_type=request_event.type,
)
if not transaction_request_response:
return create_failed_transaction_event(request_event, cause=error_msg or "")
@@ -967,45 +1168,24 @@ def create_transaction_event_from_request_and_webhook_response(
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,
+ event, error_msg = _create_event_from_response(
+ response_event,
app=app,
- include_in_calculations=True,
+ transaction_id=request_event.transaction_id,
+ currency=request_event.currency,
)
- 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()
+ if error_msg:
+ return create_failed_transaction_event(request_event, cause=error_msg)
+
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",
- ]
- )
+ update_order_with_transaction_details(transaction_item)
+ elif transaction_item.checkout_id:
+ discounts = fetch_active_discounts()
+ manager = get_plugins_manager()
+ transaction_amounts_for_checkout_updated(transaction_item, discounts, manager)
return event
@@ -1124,6 +1304,23 @@ def create_manual_adjustment_events(
return []
+def create_transaction_item(
+ source_object: Union[Checkout, Order],
+ user: Optional[User],
+ app: Optional[App],
+ psp_reference: Optional[str],
+):
+ return TransactionItem.objects.create(
+ checkout_id=source_object.pk if isinstance(source_object, Checkout) else None,
+ order_id=source_object.pk if isinstance(source_object, Order) else None,
+ currency=source_object.currency,
+ app=app,
+ app_identifier=app.identifier if app else None,
+ user=user,
+ psp_reference=psp_reference,
+ )
+
+
def create_transaction_for_order(
order: "Order",
user: Optional["User"],
@@ -1131,13 +1328,8 @@ def create_transaction_for_order(
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,
+ transaction = create_transaction_item(
+ source_object=order, user=user, app=app, psp_reference=psp_reference
)
create_manual_adjustment_events(
transaction=transaction,
@@ -1147,3 +1339,83 @@ def create_transaction_for_order(
)
recalculate_transaction_amounts(transaction=transaction)
return transaction
+
+
+def handle_transaction_initialize_session(
+ source_object: Union[Checkout, Order],
+ payment_gateway: PaymentGatewayData,
+ amount: Decimal,
+ action: str,
+ app: App,
+ manager: PluginsManager,
+ discounts: Optional[Iterable["DiscountInfo"]],
+):
+ transaction_item = create_transaction_item(
+ source_object=source_object, user=None, app=app, psp_reference=None
+ )
+ session_data = TransactionSessionData(
+ transaction=transaction_item,
+ source_object=source_object,
+ payment_gateway=payment_gateway,
+ action=TransactionProcessActionData(
+ action_type=action, currency=source_object.currency, amount=amount
+ ),
+ )
+
+ request_event = transaction_item.events.create(
+ include_in_calculations=False,
+ type=TransactionEventType.CHARGE_REQUEST
+ if action == TransactionFlowStrategy.CHARGE
+ else TransactionEventType.AUTHORIZATION_REQUEST,
+ currency=transaction_item.currency,
+ amount_value=amount,
+ )
+ response = manager.transaction_initialize_session(session_data)
+
+ response_data = response.data if response else None
+
+ created_event = create_transaction_event_for_transaction_session(
+ request_event,
+ app,
+ transaction_webhook_response=response_data,
+ manager=manager,
+ discounts=discounts,
+ )
+ data_to_return = response_data.get("data") if response_data else None
+ return created_event.transaction, created_event, data_to_return
+
+
+def handle_transaction_process_session(
+ transaction_item: TransactionItem,
+ source_object: Union[Checkout, Order],
+ payment_gateway: PaymentGatewayData,
+ action: str,
+ app: App,
+ manager: PluginsManager,
+ request_event: TransactionEvent,
+ discounts: Optional[Iterable["DiscountInfo"]],
+):
+ session_data = TransactionSessionData(
+ transaction=transaction_item,
+ source_object=source_object,
+ payment_gateway=payment_gateway,
+ action=TransactionProcessActionData(
+ action_type=action,
+ currency=source_object.currency,
+ amount=request_event.amount_value,
+ ),
+ )
+
+ response = manager.transaction_process_session(session_data)
+
+ response_data = response.data if response else None
+
+ created_event = create_transaction_event_for_transaction_session(
+ request_event,
+ app,
+ transaction_webhook_response=response_data,
+ manager=manager,
+ discounts=discounts,
+ )
+ data_to_return = response_data.get("data") if response_data else None
+ return created_event, data_to_return
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index a7ef49e63f..baae094f04 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -53,6 +53,7 @@ if TYPE_CHECKING:
from ..menu.models import Menu, MenuItem
from ..order.models import Fulfillment, Order, OrderLine
from ..page.models import Page, PageType
+ from ..payment.interface import PaymentGatewayData, TransactionSessionData
from ..payment.models import TransactionItem
from ..product.models import (
Category,
@@ -391,6 +392,12 @@ class BasePlugin:
# updated.
checkout_updated: Callable[["Checkout", Any], Any]
+ # Trigger when checkout is fully paid with transactions.
+ #
+ # Overwrite this method if you need to trigger specific logic when a checkout is
+ # updated.
+ checkout_fully_paid: Callable[["Checkout", Any], Any]
+
# Trigger when checkout metadata is updated.
#
# Overwrite this method if you need to trigger specific logic when a checkout
@@ -776,6 +783,24 @@ class BasePlugin:
transaction_refund_requested: Callable[["TransactionActionData", None], None]
+ payment_gateway_initialize_session: Callable[
+ [
+ Decimal,
+ Optional[list["PaymentGatewayData"]],
+ Union["Checkout", "Order"],
+ None,
+ ],
+ list["PaymentGatewayData"],
+ ]
+
+ transaction_initialize_session: Callable[
+ ["TransactionSessionData", None], "PaymentGatewayData"
+ ]
+
+ transaction_process_session: Callable[
+ ["TransactionSessionData", None], "PaymentGatewayData"
+ ]
+
# 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/manager.py b/saleor/plugins/manager.py
index 1dbf4731d4..8e03123f75 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -56,8 +56,10 @@ if TYPE_CHECKING:
InitializedPaymentResponse,
PaymentData,
PaymentGateway,
+ PaymentGatewayData,
TokenConfig,
TransactionActionData,
+ TransactionSessionData,
)
from ..payment.models import TransactionItem
from ..product.models import (
@@ -896,6 +898,15 @@ class PluginsManager(PaymentInterface):
channel_slug=checkout.channel.slug,
)
+ def checkout_fully_paid(self, checkout: "Checkout"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "checkout_fully_paid",
+ default_value,
+ checkout,
+ channel_slug=checkout.channel.slug,
+ )
+
def checkout_metadata_updated(self, checkout: "Checkout"):
default_value = None
return self.__run_method_on_plugins(
@@ -994,6 +1005,46 @@ class PluginsManager(PaymentInterface):
channel_slug=channel_slug,
)
+ def payment_gateway_initialize_session(
+ self,
+ amount: Decimal,
+ payment_gateways: Optional[list["PaymentGatewayData"]],
+ source_object: Union["Order", "Checkout"],
+ ) -> list["PaymentGatewayData"]:
+ default_value = None
+ return self.__run_method_on_plugins(
+ "payment_gateway_initialize_session",
+ default_value,
+ amount,
+ payment_gateways,
+ source_object,
+ channel_slug=source_object.channel.slug,
+ )
+
+ def transaction_initialize_session(
+ self,
+ transaction_session_data: "TransactionSessionData",
+ ) -> "PaymentGatewayData":
+ default_value = None
+ return self.__run_method_on_plugins(
+ "transaction_initialize_session",
+ default_value,
+ transaction_session_data,
+ channel_slug=transaction_session_data.source_object.channel.slug,
+ )
+
+ def transaction_process_session(
+ self,
+ transaction_session_data: "TransactionSessionData",
+ ) -> "PaymentGatewayData":
+ default_value = None
+ return self.__run_method_on_plugins(
+ "transaction_process_session",
+ default_value,
+ transaction_session_data,
+ channel_slug=transaction_session_data.source_object.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/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index d9f63fb85d..15a0f804b0 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -20,6 +20,7 @@ from prices import Money, TaxedMoney
from ...account.models import User
from ...core.taxes import TaxData, TaxLineData, TaxType
from ...order.interface import OrderTaxedPricesData
+from ...payment.interface import PaymentGatewayData, TransactionSessionData
from ..base_plugin import BasePlugin, ConfigurationTypeField, ExternalAccessTokens
if TYPE_CHECKING:
@@ -309,6 +310,32 @@ class PluginSample(BasePlugin):
) -> Optional[Union[ExecutionResult, GraphQLError]]:
return None
+ def payment_gateway_initialize_session(
+ self,
+ amount: Decimal,
+ payment_gateways: Optional[list["PaymentGatewayData"]],
+ source_object: Union["Order", "Checkout"],
+ previous_value: Any,
+ ):
+ return [PaymentGatewayData(app_identifier="123", data={"some": "json-data"})]
+
+ def transaction_initialize_session(
+ self,
+ transaction_session_data: "TransactionSessionData",
+ previous_value: Any,
+ ):
+ return PaymentGatewayData(app_identifier="123", data=None, error="Some error")
+
+ def transaction_process_session(
+ self,
+ transaction_session_data: "TransactionSessionData",
+ previous_value: Any,
+ ):
+ return PaymentGatewayData(app_identifier="321", data=None, error="Some error")
+
+ def checkout_fully_paid(self, checkout):
+ return None
+
class ChannelPluginSample(PluginSample):
PLUGIN_ID = "channel.plugin.sample"
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 9298c9e6b7..22a5c2d9c8 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -5,14 +5,21 @@ from unittest import mock
import pytest
from django.http import HttpResponseNotFound, JsonResponse
+from mock import patch
from prices import Money, TaxedMoney
+from ...channel import TransactionFlowStrategy
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...core.prices import quantize_price
from ...core.taxes import TaxType, zero_money, zero_taxed_money
from ...discount.utils import fetch_catalogue_info
from ...graphql.discount.mutations.utils import convert_catalogue_info_to_global_ids
-from ...payment.interface import PaymentGateway
+from ...payment.interface import (
+ PaymentGateway,
+ PaymentGatewayData,
+ TransactionProcessActionData,
+ TransactionSessionData,
+)
from ...product.models import Product
from ..base_plugin import ExternalAccessTokens
from ..manager import PluginsManager, get_plugins_manager
@@ -1173,3 +1180,124 @@ def test_manager_is_event_active_for_any_plugin(channel_USD):
assert manager.is_event_active_for_any_plugin(
"calculate_checkout_total", channel_USD.slug
)
+
+
+def test_manager_payment_gateway_initialize_session(channel_USD, checkout):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ manager = PluginsManager(plugins=plugins)
+
+ # when
+ response = manager.payment_gateway_initialize_session(
+ amount=Decimal("10.00"),
+ payment_gateways=None,
+ source_object=checkout,
+ )
+
+ # then
+ assert isinstance(response, list)
+ assert len(response) == 1
+
+
+def test_manager_transaction_initialize_session(
+ channel_USD, checkout, webhook_app, transaction_item_generator
+):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ manager = PluginsManager(plugins=plugins)
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ transaction_session_data = TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=Decimal("10"),
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ )
+ # when
+ response = manager.transaction_initialize_session(
+ transaction_session_data=transaction_session_data
+ )
+
+ # then
+ assert isinstance(response, PaymentGatewayData)
+
+
+def test_manager_transaction_process_session(
+ channel_USD, checkout, webhook_app, transaction_item_generator
+):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ manager = PluginsManager(plugins=plugins)
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ transaction_session_data = TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=Decimal("10"),
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ )
+ # when
+ response = manager.transaction_process_session(
+ transaction_session_data=transaction_session_data
+ )
+
+ # then
+ assert isinstance(response, PaymentGatewayData)
+
+
+@patch("saleor.plugins.tests.sample_plugins.PluginSample.checkout_fully_paid")
+def test_checkout_fully_paid(mocked_sample_method, checkout):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ manager = PluginsManager(plugins=plugins)
+
+ # when
+ manager.checkout_fully_paid(checkout)
+
+ # then
+
+ mocked_sample_method.assert_called_once_with(checkout, previous_value=None)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 99ea2c7c51..7dfeebdbea 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -1,16 +1,28 @@
import json
import logging
+from decimal import Decimal
from typing import TYPE_CHECKING, Any, DefaultDict, List, Optional, Set, Union
import graphene
from ...app.models import App
+from ...checkout.models import Checkout
from ...core import EventDeliveryStatus
from ...core.models import EventDelivery
from ...core.notify_events import NotifyEventType
from ...core.taxes import TaxData, TaxType
from ...core.utils.json_serializer import CustomJsonEncoder
+from ...graphql.core.context import SaleorContext
+from ...graphql.webhook.subscription_payload import initialize_request
from ...payment import PaymentError, TransactionKind
+from ...payment.interface import (
+ GatewayResponse,
+ PaymentData,
+ PaymentGateway,
+ PaymentGatewayData,
+ TransactionActionData,
+ TransactionSessionData,
+)
from ...payment.models import Payment, TransactionItem
from ...thumbnail.models import Thumbnail
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
@@ -40,6 +52,7 @@ from ...webhook.payloads import (
generate_sale_toggle_payload,
generate_thumbnail_payload,
generate_transaction_action_request_payload,
+ generate_transaction_session_payload,
generate_translation_payload,
)
from ...webhook.utils import get_webhooks_for_event
@@ -70,19 +83,12 @@ if TYPE_CHECKING:
from ...account.models import Address, Group, User
from ...attribute.models import Attribute, AttributeValue
from ...channel.models import Channel
- from ...checkout.models import Checkout
from ...discount.models import Sale, Voucher
from ...giftcard.models import GiftCard
from ...invoice.models import Invoice
from ...menu.models import Menu, MenuItem
from ...order.models import Fulfillment, Order
from ...page.models import Page, PageType
- from ...payment.interface import (
- GatewayResponse,
- PaymentData,
- PaymentGateway,
- TransactionActionData,
- )
from ...product.models import (
Category,
Collection,
@@ -96,6 +102,7 @@ if TYPE_CHECKING:
from ...tax.models import TaxClass
from ...translation.models import Translation
from ...warehouse.models import Stock, Warehouse
+ from ...webhook.models import Webhook
logger = logging.getLogger(__name__)
@@ -977,6 +984,16 @@ class WebhookPlugin(BasePlugin):
checkout_data, event_type, webhooks, checkout, self.requestor
)
+ def checkout_fully_paid(self, checkout: "Checkout", previous_value: Any) -> Any:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
+ if webhooks := get_webhooks_for_event(event_type):
+ checkout_data = generate_checkout_payload(checkout, self.requestor)
+ trigger_webhooks_async(
+ checkout_data, event_type, webhooks, checkout, self.requestor
+ )
+
def checkout_metadata_updated(
self, checkout: "Checkout", previous_value: Any
) -> Any:
@@ -1465,6 +1482,8 @@ class WebhookPlugin(BasePlugin):
for app in apps:
webhook = get_webhooks_for_event(event_type, app.webhooks.all()).first()
+ if not webhook:
+ raise PaymentError(f"No payment webhook found for event: {event_type}.")
response_data = trigger_webhook_sync(
event_type, webhook_payload, webhook, subscribable_object=payment
)
@@ -1480,6 +1499,157 @@ class WebhookPlugin(BasePlugin):
"no response from the app."
)
+ def _payment_gateway_initialize_session_for_single_webhook(
+ self,
+ webhook: "Webhook",
+ gateways: dict[str, "PaymentGatewayData"],
+ response_gateway: dict[str, "PaymentGatewayData"],
+ amount: Decimal,
+ source_object: Union["Order", "Checkout"],
+ request: SaleorContext,
+ ):
+ if not webhook.app.identifier:
+ logger.debug(
+ "Skipping app with id %s as identifier is not provided.",
+ webhook.app.pk,
+ )
+ return
+ if webhook.app.identifier in response_gateway:
+ logger.debug(
+ "Skipping next call for %s as app has been already processed.",
+ webhook.app.identifier,
+ )
+ return
+
+ gateway = gateways.get(webhook.app.identifier)
+ gateway_data = None
+ if gateway:
+ gateway_data = gateway.data
+
+ source_object_id = graphene.Node.to_global_id(
+ source_object.__class__.__name__, source_object.pk
+ )
+ payload = {"id": source_object_id, "data": gateway_data, "amount": amount}
+ subscribable_object = (source_object, gateway_data, amount)
+ response_data = trigger_webhook_sync(
+ event_type=WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ data=json.dumps(payload, cls=CustomJsonEncoder),
+ webhook=webhook,
+ subscribable_object=subscribable_object,
+ request=request,
+ )
+ error_msg = None
+ if response_data is None:
+ error_msg = "Unable to process a payment gateway response."
+ response_gateway[webhook.app.identifier] = PaymentGatewayData(
+ app_identifier=webhook.app.identifier,
+ data=response_data,
+ error=error_msg,
+ )
+
+ def payment_gateway_initialize_session(
+ self,
+ amount: Decimal,
+ payment_gateways: Optional[list[PaymentGatewayData]],
+ source_object: Union["Order", "Checkout"],
+ previous_value,
+ ) -> list[PaymentGatewayData]:
+ if not self.active:
+ return previous_value
+ response_gateway: dict[str, PaymentGatewayData] = {}
+ apps_identifiers = None
+
+ gateways = {}
+ if payment_gateways:
+ gateways = {gateway.app_identifier: gateway for gateway in payment_gateways}
+ apps_identifiers = list(gateways.keys())
+
+ webhooks = get_webhooks_for_event(
+ WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ apps_identifier=apps_identifiers,
+ )
+
+ request = initialize_request(
+ self.requestor,
+ sync_event=True,
+ event_type=WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ )
+
+ for webhook in webhooks:
+ self._payment_gateway_initialize_session_for_single_webhook(
+ webhook=webhook,
+ gateways=gateways,
+ response_gateway=response_gateway,
+ amount=amount,
+ source_object=source_object,
+ request=request,
+ )
+ return list(response_gateway.values())
+
+ def _transaction_session_base(
+ self, transaction_session_data: TransactionSessionData, webhook_event: str
+ ):
+ if not transaction_session_data.payment_gateway.app_identifier:
+ error = "Missing app identifier"
+ return PaymentGatewayData(
+ app_identifier=transaction_session_data.payment_gateway.app_identifier,
+ error=error,
+ )
+ webhook = get_webhooks_for_event(
+ webhook_event,
+ apps_identifier=[transaction_session_data.payment_gateway.app_identifier],
+ ).first()
+ if not webhook:
+ error = (
+ "Unable to find an active webhook for "
+ f"`{webhook_event.upper()}` event."
+ )
+ return PaymentGatewayData(
+ app_identifier=transaction_session_data.payment_gateway.app_identifier,
+ error=error,
+ )
+
+ payload = generate_transaction_session_payload(
+ transaction_session_data.action,
+ transaction_session_data.transaction,
+ transaction_session_data.source_object,
+ transaction_session_data.payment_gateway,
+ )
+
+ response_data = trigger_webhook_sync(
+ event_type=webhook_event,
+ data=payload,
+ webhook=webhook,
+ subscribable_object=transaction_session_data,
+ )
+ error_msg = None
+ if response_data is None:
+ error_msg = "Unable to parse a transaction initialize response."
+ return PaymentGatewayData(
+ app_identifier=transaction_session_data.payment_gateway.app_identifier,
+ data=response_data,
+ error=error_msg,
+ )
+
+ def transaction_initialize_session(
+ self, transaction_session_data: TransactionSessionData, previous_value
+ ) -> PaymentGatewayData:
+ if not self.active:
+ return previous_value
+ return self._transaction_session_base(
+ transaction_session_data,
+ WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION,
+ )
+
+ def transaction_process_session(
+ self, transaction_session_data: TransactionSessionData, previous_value
+ ) -> PaymentGatewayData:
+ if not self.active:
+ return previous_value
+ return self._transaction_session_base(
+ transaction_session_data, WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ )
+
def token_is_required_as_payment_input(self, previous_value):
return False
@@ -1494,6 +1664,9 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventSyncType.PAYMENT_LIST_GATEWAYS
webhooks = get_webhooks_for_event(event_type)
for webhook in webhooks:
+ if not webhook:
+ raise PaymentError(f"No payment webhook found for event: {event_type}.")
+
response_data = trigger_webhook_sync(
event_type=event_type,
data=generate_list_gateways_payload(currency, checkout),
@@ -1509,6 +1682,26 @@ class WebhookPlugin(BasePlugin):
gtw for gtw in app_gateways if currency in gtw.currencies
]
gateways.extend(app_gateways)
+ currency = checkout.currency if checkout else currency
+ if currency:
+ webhooks = get_webhooks_for_event(
+ WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ )
+ for webhook in webhooks:
+ app = webhook.app
+ if not app or not app.identifier:
+ continue
+ name = app.name or ""
+ gateways.append(
+ PaymentGateway(
+ id=app.identifier,
+ name=name,
+ currencies=[
+ currency,
+ ],
+ config=[],
+ )
+ )
return gateways
def transaction_item_metadata_updated(
@@ -1622,6 +1815,10 @@ class WebhookPlugin(BasePlugin):
if webhooks:
payload = generate_checkout_payload(checkout, self.requestor)
for webhook in webhooks:
+ if not webhook:
+ raise PaymentError(
+ f"No payment webhook found for event: {event_type}."
+ )
response_data = trigger_webhook_sync(
event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
data=payload,
diff --git a/saleor/plugins/webhook/shipping.py b/saleor/plugins/webhook/shipping.py
index 39c7ab9d5e..273104221c 100644
--- a/saleor/plugins/webhook/shipping.py
+++ b/saleor/plugins/webhook/shipping.py
@@ -110,6 +110,8 @@ def get_excluded_shipping_methods_or_fetch(
excluded_methods = []
# Gather responses from webhooks
for webhook in webhooks:
+ if not webhook:
+ continue
response_data = trigger_webhook_sync(
event_type,
payload,
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index a39d76f8ed..61096e4377 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -105,7 +105,7 @@ def create_deliveries_for_subscriptions(
subscribable_object=subscribable_object,
subscription_query=webhook.subscription_query,
request=initialize_request(
- requestor, event_type in WebhookEventSyncType.ALL
+ requestor, event_type in WebhookEventSyncType.ALL, event_type=event_type
),
app=webhook.app,
)
@@ -152,7 +152,9 @@ def create_delivery_for_subscription_sync_event(
return None
if not request:
- request = initialize_request(requestor, event_type in WebhookEventSyncType.ALL)
+ request = initialize_request(
+ requestor, event_type in WebhookEventSyncType.ALL, event_type=event_type
+ )
data = generate_payload_from_subscription(
event_type=event_type,
@@ -225,18 +227,18 @@ def group_webhooks_by_subscription(webhooks):
def trigger_webhook_sync(
event_type: str,
data: str,
- webhook: Optional["Webhook"],
+ webhook: "Webhook",
subscribable_object=None,
timeout=None,
+ request=None,
) -> Optional[Dict[Any, Any]]:
"""Send a synchronous webhook request."""
- if not webhook:
- raise PaymentError(f"No payment webhook found for event: {event_type}.")
if webhook.subscription_query:
delivery = create_delivery_for_subscription_sync_event(
event_type=event_type,
subscribable_object=subscribable_object,
webhook=webhook,
+ request=request,
)
if not delivery:
return None
@@ -280,7 +282,10 @@ def trigger_all_webhooks_sync(
if webhook.subscription_query:
if request_context is None:
request_context = initialize_request(
- requestor, event_type in WebhookEventSyncType.ALL, allow_replica
+ requestor,
+ event_type in WebhookEventSyncType.ALL,
+ allow_replica,
+ event_type=event_type,
)
delivery = create_delivery_for_subscription_sync_event(
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index 935fb36f34..dd3aa8f32a 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -628,6 +628,13 @@ def subscription_checkout_updated_webhook(subscription_webhook):
)
+def subscription_checkout_fully_paid_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.CHECKOUT_FULLY_PAID, WebhookEventAsyncType.CHECKOUT_FULLY_PAID
+ )
+
+
@pytest.fixture
def subscription_checkout_metadata_updated_webhook(subscription_webhook):
return subscription_webhook(
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
index a6586398e7..8663bf0d9b 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -1283,6 +1283,18 @@ CHECKOUT_UPDATED = """
}
"""
+CHECKOUT_FULLY_PAID = """
+ subscription{
+ event{
+ ...on CheckoutFullyPaid{
+ checkout{
+ id
+ }
+ }
+ }
+ }
+"""
+
CHECKOUT_METADATA_UPDATED = """
subscription{
event{
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_session.py
new file mode 100644
index 0000000000..d5176c9291
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_session.py
@@ -0,0 +1,161 @@
+import json
+from decimal import Decimal
+
+import graphene
+
+from .....webhook.event_types import WebhookEventSyncType
+from .....webhook.models import Webhook
+from ...tasks import create_deliveries_for_subscriptions
+
+PAYMENT_GATEWAY_INITIALIZE_SESSION = """
+subscription {
+ event{
+ ...on PaymentGatewayInitializeSession{
+ data
+ sourceObject{
+ __typename
+ ... on Checkout{
+ id
+ totalPrice{
+ gross{
+ amount
+ }
+ }
+ }
+ ... on Order{
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_payment_gateway_initialize_session_checkout_with_data(
+ checkout, webhook_app, permission_manage_payments
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = {"some": "json data"}
+ amount = Decimal("10")
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, (checkout, payload_data, amount), [webhook]
+ )[0]
+
+ # then
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "data": payload_data,
+ "sourceObject": {
+ "__typename": "Checkout",
+ "id": checkout_id,
+ "totalPrice": {"gross": {"amount": 0.0}},
+ },
+ }
+
+
+def test_payment_gateway_initialize_session_checkout_without_data(
+ checkout, webhook_app, permission_manage_payments
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = None
+ amount = Decimal("10")
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, (checkout, payload_data, amount), [webhook]
+ )[0]
+
+ # then
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "data": None,
+ "sourceObject": {
+ "__typename": "Checkout",
+ "id": checkout_id,
+ "totalPrice": {"gross": {"amount": 0.0}},
+ },
+ }
+
+
+def test_payment_gateway_initialize_session_order_with_data(
+ order, webhook_app, permission_manage_payments
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = {"some": "json data"}
+ amount = Decimal("10")
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, (order, payload_data, amount), [webhook]
+ )[0]
+
+ # then
+
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "data": payload_data,
+ "sourceObject": {"__typename": "Order", "id": order_id},
+ }
+
+
+def test_payment_gateway_initialize_session_order_without_data(
+ order, webhook_app, permission_manage_payments
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = None
+ amount = Decimal("10")
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, (order, payload_data, amount), [webhook]
+ )[0]
+
+ # then
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "data": None,
+ "sourceObject": {"__typename": "Order", "id": order_id},
+ }
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 783d4c4a2c..029aff950c 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
@@ -1592,6 +1592,23 @@ def test_checkout_update(checkout, subscription_checkout_updated_webhook):
assert deliveries[0].webhook == webhooks[0]
+def test_checkout_fully_paid(checkout, subscription_checkout_fully_paid_webhook):
+ # given
+ webhooks = [subscription_checkout_fully_paid_webhook]
+ event_type = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, checkout, webhooks)
+
+ # then
+ expected_payload = json.dumps({"checkout": {"id": checkout_id}})
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_checkout_metadata_updated(
checkout, subscription_checkout_metadata_updated_webhook
):
@@ -1925,7 +1942,7 @@ def test_transaction_item_metadata_updated(
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_created_by_app.id
+ "TransactionItem", transaction_item_created_by_app.token
)
# when
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 f02637b9a1..7c54719a1e 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
@@ -88,7 +88,7 @@ def test_transaction_refund_action_request(
event_type = WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST
webhook.events.create(event_type=event_type)
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
transaction_data = TransactionActionData(
transaction=transaction,
action_type=TransactionAction.REFUND,
@@ -160,7 +160,7 @@ def test_transaction_charge_action_request(
event_type = WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST
webhook.events.create(event_type=event_type)
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
action_value = Decimal("5.00")
transaction_data = TransactionActionData(
transaction=transaction,
@@ -233,7 +233,7 @@ def test_transaction_void_action_request(
event_type = WebhookEventAsyncType.TRANSACTION_ACTION_REQUEST
webhook.events.create(event_type=event_type)
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
transaction_data = TransactionActionData(
transaction=transaction,
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
index 06deea9580..720c1bc7e4 100644
--- 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
@@ -62,7 +62,7 @@ def test_transaction_void_request(order, webhook_app, permission_manage_payments
event_type = WebhookEventSyncType.TRANSACTION_CANCELATION_REQUESTED
webhook.events.create(event_type=event_type)
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
transaction_data = TransactionActionData(
transaction=transaction,
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
index 37af9faffe..d54cb247c0 100644
--- 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
@@ -64,7 +64,7 @@ def test_transaction_charge_request(order, webhook_app, permission_manage_paymen
event_type = WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED
webhook.events.create(event_type=event_type)
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
transaction_data = TransactionActionData(
transaction=transaction,
action_type=TransactionAction.CHARGE,
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py
new file mode 100644
index 0000000000..001c139c81
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py
@@ -0,0 +1,299 @@
+import json
+from decimal import Decimal
+
+import graphene
+
+from .....channel import TransactionFlowStrategy
+from .....payment.interface import (
+ PaymentGatewayData,
+ TransactionProcessActionData,
+ TransactionSessionData,
+)
+from .....webhook.event_types import WebhookEventSyncType
+from .....webhook.models import Webhook
+from ...tasks import create_deliveries_for_subscriptions
+
+TRANSACTION_INITIALIZE_SESSION = """
+subscription {
+ event{
+ ...on TransactionInitializeSession{
+ merchantReference
+ action{
+ amount
+ currency
+ actionType
+ }
+ data
+ sourceObject{
+ __typename
+ ... on Checkout{
+ id
+ totalPrice{
+ gross{
+ amount
+ }
+ }
+ }
+ ... on Order{
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_transaction_initialize_session_checkout_with_data(
+ checkout, webhook_app, permission_manage_payments, transaction_item_generator
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = {"some": "json data"}
+ amount = Decimal("10")
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ subscribable_object = TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=payload_data, error=None
+ ),
+ )
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, subscribable_object, [webhook]
+ )[0]
+
+ # then
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "currency": "USD",
+ "actionType": action_type.upper(),
+ },
+ "data": payload_data,
+ "sourceObject": {
+ "__typename": "Checkout",
+ "id": checkout_id,
+ "totalPrice": {"gross": {"amount": 0.0}},
+ },
+ }
+
+
+def test_transaction_initialize_session_checkout_without_data(
+ checkout, webhook_app, permission_manage_payments, transaction_item_generator
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = None
+ amount = Decimal("10")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ subscribable_object = TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=payload_data, error=None
+ ),
+ )
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, subscribable_object, [webhook]
+ )[0]
+
+ # then
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "currency": "USD",
+ "actionType": action_type.upper(),
+ },
+ "data": payload_data,
+ "sourceObject": {
+ "__typename": "Checkout",
+ "id": checkout_id,
+ "totalPrice": {"gross": {"amount": 0.0}},
+ },
+ }
+
+
+def test_transaction_initialize_session_order_with_data(
+ order, webhook_app, permission_manage_payments, transaction_item_generator
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = {"some": "json data"}
+ amount = Decimal("10")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ subscribable_object = TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=payload_data, error=None
+ ),
+ )
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, subscribable_object, [webhook]
+ )[0]
+
+ # then
+
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "currency": "USD",
+ "actionType": action_type.upper(),
+ },
+ "data": payload_data,
+ "sourceObject": {
+ "__typename": "Order",
+ "id": order_id,
+ },
+ }
+
+
+def test_transaction_initialize_session_order_without_data(
+ order, webhook_app, permission_manage_payments, transaction_item_generator
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = None
+ amount = Decimal("10")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ subscribable_object = TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=payload_data, error=None
+ ),
+ )
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, subscribable_object, [webhook]
+ )[0]
+
+ # then
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "currency": "USD",
+ "actionType": action_type.upper(),
+ },
+ "data": payload_data,
+ "sourceObject": {
+ "__typename": "Order",
+ "id": order_id,
+ },
+ }
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py
new file mode 100644
index 0000000000..ee3c6e421e
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py
@@ -0,0 +1,299 @@
+import json
+from decimal import Decimal
+
+import graphene
+
+from .....channel import TransactionFlowStrategy
+from .....payment.interface import (
+ PaymentGatewayData,
+ TransactionProcessActionData,
+ TransactionSessionData,
+)
+from .....webhook.event_types import WebhookEventSyncType
+from .....webhook.models import Webhook
+from ...tasks import create_deliveries_for_subscriptions
+
+TRANSACTION_PROCESS_SESSION = """
+subscription {
+ event{
+ ...on TransactionProcessSession{
+ merchantReference
+ action{
+ amount
+ currency
+ actionType
+ }
+ data
+ sourceObject{
+ __typename
+ ... on Checkout{
+ id
+ totalPrice{
+ gross{
+ amount
+ }
+ }
+ }
+ ... on Order{
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_transaction_process_session_checkout_with_data(
+ checkout, webhook_app, permission_manage_payments, transaction_item_generator
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_PROCESS_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = {"some": "json data"}
+ amount = Decimal("10")
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ subscribable_object = TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=payload_data, error=None
+ ),
+ )
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, subscribable_object, [webhook]
+ )[0]
+
+ # then
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "currency": "USD",
+ "actionType": action_type.upper(),
+ },
+ "data": payload_data,
+ "sourceObject": {
+ "__typename": "Checkout",
+ "id": checkout_id,
+ "totalPrice": {"gross": {"amount": 0.0}},
+ },
+ }
+
+
+def test_transaction_process_session_checkout_without_data(
+ checkout, webhook_app, permission_manage_payments, transaction_item_generator
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_PROCESS_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = None
+ amount = Decimal("10")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ subscribable_object = TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=payload_data, error=None
+ ),
+ )
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, subscribable_object, [webhook]
+ )[0]
+
+ # then
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "currency": "USD",
+ "actionType": action_type.upper(),
+ },
+ "data": payload_data,
+ "sourceObject": {
+ "__typename": "Checkout",
+ "id": checkout_id,
+ "totalPrice": {"gross": {"amount": 0.0}},
+ },
+ }
+
+
+def test_transaction_process_session_order_with_data(
+ order, webhook_app, permission_manage_payments, transaction_item_generator
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_PROCESS_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = {"some": "json data"}
+ amount = Decimal("10")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ subscribable_object = TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=payload_data, error=None
+ ),
+ )
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, subscribable_object, [webhook]
+ )[0]
+
+ # then
+
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "currency": "USD",
+ "actionType": action_type.upper(),
+ },
+ "data": payload_data,
+ "sourceObject": {
+ "__typename": "Order",
+ "id": order_id,
+ },
+ }
+
+
+def test_transaction_process_session_order_without_data(
+ order, webhook_app, permission_manage_payments, transaction_item_generator
+):
+ # given
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_PROCESS_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ payload_data = None
+ amount = Decimal("10")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ subscribable_object = TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=payload_data, error=None
+ ),
+ )
+
+ # when
+ delivery = create_deliveries_for_subscriptions(
+ event_type, subscribable_object, [webhook]
+ )[0]
+
+ # then
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ assert delivery.payload
+ assert delivery.payload.payload
+ assert json.loads(delivery.payload.payload) == {
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "currency": "USD",
+ "actionType": action_type.upper(),
+ },
+ "data": payload_data,
+ "sourceObject": {
+ "__typename": "Order",
+ "id": order_id,
+ },
+ }
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
index cf14eba037..4b647e5e54 100644
--- 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
@@ -64,7 +64,7 @@ def test_transaction_refund_request(order, webhook_app, permission_manage_paymen
event_type = WebhookEventSyncType.TRANSACTION_REFUND_REQUESTED
webhook.events.create(event_type=event_type)
- transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.id)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
transaction_data = TransactionActionData(
transaction=transaction,
action_type=TransactionAction.REFUND,
diff --git a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py
new file mode 100644
index 0000000000..fe2db2a60d
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py
@@ -0,0 +1,416 @@
+import json
+from decimal import Decimal
+from unittest import mock
+
+import graphene
+from freezegun import freeze_time
+
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery, EventPayload
+from ....payment.interface import PaymentGatewayData
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook
+
+PAYMENT_GATEWAY_INITIALIZE_SESSION = """
+subscription {
+ event{
+ ...on PaymentGatewayInitializeSession{
+ data
+ amount
+ sourceObject{
+ __typename
+ ... on Checkout{
+ id
+ }
+ ... on Order{
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def _assert_with_subscription(
+ transaction_object,
+ request_data,
+ amount,
+ webhook,
+ expected_data,
+ response,
+ mock_request,
+):
+ object_id = graphene.Node.to_global_id(
+ transaction_object.__class__.__name__, transaction_object.pk
+ )
+ payload = {
+ "data": request_data,
+ "amount": amount,
+ "sourceObject": {
+ "__typename": transaction_object.__class__.__name__,
+ "id": object_id,
+ },
+ }
+ _assert_fields(payload, webhook, expected_data, response, mock_request)
+
+
+def _assert_with_static_payload(
+ transaction_object,
+ request_data,
+ amount,
+ webhook,
+ expected_data,
+ response,
+ mock_request,
+):
+ transaction_object_id = graphene.Node.to_global_id(
+ transaction_object.__class__.__name__, transaction_object.pk
+ )
+ payload = {"id": transaction_object_id, "data": request_data, "amount": str(amount)}
+ _assert_fields(payload, webhook, expected_data, response, mock_request)
+
+
+def _assert_fields(payload, webhook, expected_data, response, mock_request):
+ webhook_app = webhook.app
+ event_payload = EventPayload.objects.get()
+ assert json.loads(event_payload.payload) == payload
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert (
+ delivery.event_type == WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ )
+ assert delivery.payload == event_payload
+ assert delivery.webhook == webhook
+ mock_request.assert_called_once_with(webhook.app.name, delivery)
+ assert response == [
+ PaymentGatewayData(app_identifier=webhook_app.identifier, data=expected_data)
+ ]
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_gateway_initialize_checkout_without_request_data_and_static_payload(
+ mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
+):
+ # given
+ expected_data = {"some": "json data"}
+ mock_request.return_value = expected_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+ # when
+ response = plugin.payment_gateway_initialize_session(
+ amount=amount,
+ payment_gateways=None,
+ source_object=checkout,
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ checkout, None, amount, webhook, expected_data, response, mock_request
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_gateway_initialize_checkout_with_request_data_and_static_payload(
+ mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
+):
+ # given
+ data = {"some": "request-data"}
+ expected_data = {"some": "json data"}
+ mock_request.return_value = expected_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ # when
+ response = plugin.payment_gateway_initialize_session(
+ amount=amount,
+ payment_gateways=[
+ PaymentGatewayData(app_identifier=webhook_app.identifier, data=data)
+ ],
+ source_object=checkout,
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ checkout, data, amount, webhook, expected_data, response, mock_request
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_gateway_initialize_checkout_without_request_data(
+ mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
+):
+ # given
+ expected_data = {"some": "json data"}
+ mock_request.return_value = expected_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ # when
+ response = plugin.payment_gateway_initialize_session(
+ amount=amount,
+ payment_gateways=None,
+ source_object=checkout,
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ checkout, None, amount, webhook, expected_data, response, mock_request
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_gateway_initialize_checkout_with_request_data(
+ mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
+):
+ # given
+ data = {"some": "request-data"}
+ expected_data = {"some": "json data"}
+ mock_request.return_value = expected_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ # when
+ response = plugin.payment_gateway_initialize_session(
+ amount=amount,
+ payment_gateways=[
+ PaymentGatewayData(app_identifier=webhook_app.identifier, data=data)
+ ],
+ source_object=checkout,
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ checkout, data, amount, webhook, expected_data, response, mock_request
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_gateway_initialize_session_skips_app_without_identifier(
+ mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
+):
+ # given
+ plugin = webhook_plugin()
+
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ # when
+ response = plugin.payment_gateway_initialize_session(
+ amount=amount,
+ payment_gateways=None,
+ source_object=checkout,
+ previous_value=None,
+ )
+
+ # then
+ assert not EventPayload.objects.first()
+ assert not EventDelivery.objects.first()
+ assert not mock_request.called
+ assert response == []
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_gateway_initialize_order_without_request_data_static_payload(
+ mock_request, webhook_plugin, webhook_app, order, permission_manage_payments
+):
+ # given
+ expected_data = {"some": "json data"}
+ mock_request.return_value = expected_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+ # when
+ response = plugin.payment_gateway_initialize_session(
+ amount=amount,
+ payment_gateways=None,
+ source_object=order,
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ order, None, amount, webhook, expected_data, response, mock_request
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_gateway_initialize_order_with_request_data_static_payload(
+ mock_request, webhook_plugin, webhook_app, order, permission_manage_payments
+):
+ # given
+ data = {"some": "request-data"}
+ expected_data = {"some": "json data"}
+ mock_request.return_value = expected_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ # when
+ response = plugin.payment_gateway_initialize_session(
+ amount=amount,
+ payment_gateways=[
+ PaymentGatewayData(app_identifier=webhook_app.identifier, data=data)
+ ],
+ source_object=order,
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ order, data, amount, webhook, expected_data, response, mock_request
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_gateway_initialize_session_for_order_without_request_data(
+ mock_request, webhook_plugin, webhook_app, order, permission_manage_payments
+):
+ # given
+ expected_data = {"some": "json data"}
+ mock_request.return_value = expected_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+
+ amount = Decimal("10.00")
+
+ # when
+ response = plugin.payment_gateway_initialize_session(
+ amount=amount,
+ payment_gateways=None,
+ source_object=order,
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ order, None, amount, webhook, expected_data, response, mock_request
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_gateway_initialize_session_for_order_with_request_data(
+ mock_request, webhook_plugin, webhook_app, order, permission_manage_payments
+):
+ # given
+ data = {"some": "request-data"}
+ expected_data = {"some": "json data"}
+ mock_request.return_value = expected_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+
+ amount = Decimal("10.00")
+
+ # when
+ response = plugin.payment_gateway_initialize_session(
+ amount=amount,
+ payment_gateways=[
+ PaymentGatewayData(app_identifier=webhook_app.identifier, data=data)
+ ],
+ source_object=order,
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ order, data, amount, webhook, expected_data, response, mock_request
+ )
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index 9abe396234..ae608370ce 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py
@@ -12,6 +12,7 @@ from ....app.models import App
from ....core import EventDeliveryStatus
from ....core.models import EventDelivery, EventDeliveryAttempt, EventPayload
from ....payment import PaymentError, TransactionKind
+from ....payment.interface import PaymentGateway
from ....payment.utils import create_payment_information
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....webhook.models import Webhook, WebhookEvent
@@ -78,15 +79,6 @@ def test_trigger_webhook_sync_with_subscription(
mock_request.assert_called_once_with(payment_app.name, fake_delivery)
-def test_trigger_webhook_sync_no_webhook_available():
- app = App.objects.create(name="Dummy app", is_active=True)
- # should raise an error for app with no payment webhooks
- with pytest.raises(PaymentError):
- trigger_webhook_sync(
- WebhookEventSyncType.PAYMENT_REFUND, {}, app.webhooks.first()
- )
-
-
@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
@mock.patch("saleor.plugins.webhook.tasks.requests.post")
def test_send_webhook_request_sync_failed_attempt(
@@ -306,6 +298,64 @@ def test_get_payment_gateways(
assert response_data[1] == expected_response_2[0]
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_get_payment_gateways_with_transactions(
+ mock_send_request, permission_manage_payments, webhook_plugin
+):
+ # given
+ app_name = "Payment App 2"
+ app_identifier = "app2"
+ app = App.objects.create(name=app_name, is_active=True, identifier=app_identifier)
+ app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="payment-webhook-2",
+ app=app,
+ target_url="https://payment-gateway-2.com/api/",
+ )
+ WebhookEvent.objects.create(
+ event_type=WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION, webhook=webhook
+ )
+
+ plugin = webhook_plugin()
+
+ # when
+ response_data = plugin.get_payment_gateways("USD", None, None)
+
+ # then
+ assert len(response_data) == 1
+ assert response_data[0] == PaymentGateway(
+ id=app_identifier, name=app_name, currencies=["USD"], config=[]
+ )
+ assert not mock_send_request.called
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_get_payment_gateways_with_transactions_and_app_without_identifier(
+ mock_send_request, permission_manage_payments, webhook_plugin
+):
+ # given
+ app_name = "Payment App 2"
+ app_identifier = None
+ app = App.objects.create(name=app_name, is_active=True, identifier=app_identifier)
+ app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="payment-webhook-2",
+ app=app,
+ target_url="https://payment-gateway-2.com/api/",
+ )
+ WebhookEvent.objects.create(
+ event_type=WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION, webhook=webhook
+ )
+
+ plugin = webhook_plugin()
+
+ # when
+ response_data = plugin.get_payment_gateways("USD", None, None)
+
+ # then
+ assert len(response_data) == 0
+
+
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
def test_get_payment_gateways_multiple_webhooks_in_the_same_app(
mock_send_request, payment_app, permission_manage_payments, webhook_plugin
diff --git a/saleor/plugins/webhook/tests/test_tasks.py b/saleor/plugins/webhook/tests/test_tasks.py
index 9705ea5eef..348cbfcbe2 100644
--- a/saleor/plugins/webhook/tests/test_tasks.py
+++ b/saleor/plugins/webhook/tests/test_tasks.py
@@ -143,7 +143,9 @@ def test_trigger_transaction_request_with_webhook_subscription(
assert generated_delivery
assert json.loads(generated_payload.payload) == {
"transaction": {
- "id": Node.to_global_id("TransactionItem", transaction_data.transaction.id),
+ "id": Node.to_global_id(
+ "TransactionItem", transaction_data.transaction.token
+ ),
},
"action": {"amount": 10.0, "actionType": "REFUND"},
}
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
index f90ef1acff..d77e8fb366 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py
@@ -187,7 +187,7 @@ def test_get_taxes_for_order_with_sync_subscription(
@freeze_time()
[email protected]("saleor.checkout.calculations.fetch_checkout_prices_if_expired")
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
def test_get_taxes_for_checkout_with_sync_subscription(
mock_request,
diff --git a/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py b/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py
new file mode 100644
index 0000000000..3e2f233830
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py
@@ -0,0 +1,724 @@
+import json
+from decimal import Decimal
+from unittest import mock
+
+import graphene
+from freezegun import freeze_time
+
+from ....channel import TransactionFlowStrategy
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery, EventPayload
+from ....payment.interface import (
+ PaymentGatewayData,
+ TransactionProcessActionData,
+ TransactionSessionData,
+)
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook
+
+TRANSACTION_INITIALIZE_SESSION = """
+subscription {
+ event{
+ ...on TransactionInitializeSession{
+ merchantReference
+ action{
+ amount
+ currency
+ actionType
+ }
+ data
+ sourceObject{
+ __typename
+ ... on Checkout{
+ id
+ }
+ ... on Order{
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def _assert_with_subscription(
+ source_object,
+ transaction,
+ request_data,
+ amount,
+ action_type,
+ webhook,
+ expected_response,
+ response,
+ mock_request,
+):
+ object_id = graphene.Node.to_global_id(
+ source_object.__class__.__name__, source_object.pk
+ )
+ payload = {
+ "data": request_data,
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "actionType": action_type.upper(),
+ "currency": transaction.currency,
+ },
+ "sourceObject": {
+ "__typename": source_object.__class__.__name__,
+ "id": object_id,
+ },
+ }
+ _assert_fields(payload, webhook, expected_response, response, mock_request)
+
+
+def _assert_with_static_payload(
+ source_object,
+ transaction,
+ request_data,
+ amount,
+ action_type,
+ webhook,
+ expected_response,
+ response,
+ mock_request,
+):
+ source_object_id = graphene.Node.to_global_id(
+ source_object.__class__.__name__, source_object.pk
+ )
+ payload = {
+ "id": source_object_id,
+ "data": request_data,
+ "amount": str(amount),
+ "currency": "USD",
+ "action_type": action_type.upper(),
+ "transaction_id": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ }
+ _assert_fields(payload, webhook, expected_response, response, mock_request)
+
+
+def _assert_fields(payload, webhook, expected_response, response, mock_request):
+ webhook_app = webhook.app
+ event_payload = EventPayload.objects.get()
+ assert json.loads(event_payload.payload) == payload
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ assert delivery.payload == event_payload
+ assert delivery.webhook == webhook
+ mock_request.assert_called_once_with(webhook_app.name, delivery)
+ assert response == PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=expected_response, error=None
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_initialize_checkout_without_request_data_and_static_payload(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_initialize_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ checkout,
+ transaction,
+ None,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_initialize_checkout_with_request_data_and_static_payload(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_initialize_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ checkout,
+ transaction,
+ data,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_initialize_checkout_without_request_data(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_initialize_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ checkout,
+ transaction,
+ None,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_initialize_checkout_with_request_data(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_initialize_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ checkout,
+ transaction,
+ data,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_initialize_session_skips_app_without_identifier(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_item_generator,
+ transaction_session_response,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response.copy()
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = ""
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_initialize_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ assert not EventPayload.objects.first()
+ assert not EventDelivery.objects.first()
+ assert not mock_request.called
+ assert response == PaymentGatewayData(
+ app_identifier="", data=None, error="Missing app identifier"
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_initialize_order_without_request_data_and_static_payload(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ order,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_initialize_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ order,
+ transaction,
+ None,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_initialize_order_with_request_data_and_static_payload(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ order,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_initialize_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ order,
+ transaction,
+ data,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_initialize_order_without_request_data(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ order,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_initialize_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ order,
+ transaction,
+ None,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_initialize_order_with_request_data(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ order,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_INITIALIZE_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_INITIALIZE_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_initialize_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ order,
+ transaction,
+ data,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
diff --git a/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py b/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py
new file mode 100644
index 0000000000..41e218b72e
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py
@@ -0,0 +1,724 @@
+import json
+from decimal import Decimal
+from unittest import mock
+
+import graphene
+from freezegun import freeze_time
+
+from ....channel import TransactionFlowStrategy
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery, EventPayload
+from ....payment.interface import (
+ PaymentGatewayData,
+ TransactionProcessActionData,
+ TransactionSessionData,
+)
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook
+
+TRANSACTION_PROCESS_SESSION = """
+subscription {
+ event{
+ ...on TransactionProcessSession{
+ merchantReference
+ action{
+ amount
+ currency
+ actionType
+ }
+ data
+ sourceObject{
+ __typename
+ ... on Checkout{
+ id
+ }
+ ... on Order{
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def _assert_with_subscription(
+ source_object,
+ transaction,
+ request_data,
+ amount,
+ action_type,
+ webhook,
+ expected_response,
+ response,
+ mock_request,
+):
+ object_id = graphene.Node.to_global_id(
+ source_object.__class__.__name__, source_object.pk
+ )
+ payload = {
+ "data": request_data,
+ "merchantReference": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ "action": {
+ "amount": amount,
+ "actionType": action_type.upper(),
+ "currency": transaction.currency,
+ },
+ "sourceObject": {
+ "__typename": source_object.__class__.__name__,
+ "id": object_id,
+ },
+ }
+ _assert_fields(payload, webhook, expected_response, response, mock_request)
+
+
+def _assert_with_static_payload(
+ source_object,
+ transaction,
+ request_data,
+ amount,
+ action_type,
+ webhook,
+ expected_response,
+ response,
+ mock_request,
+):
+ source_object_id = graphene.Node.to_global_id(
+ source_object.__class__.__name__, source_object.pk
+ )
+ payload = {
+ "id": source_object_id,
+ "data": request_data,
+ "amount": str(amount),
+ "currency": "USD",
+ "action_type": action_type.upper(),
+ "transaction_id": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ }
+ _assert_fields(payload, webhook, expected_response, response, mock_request)
+
+
+def _assert_fields(payload, webhook, expected_response, response, mock_request):
+ webhook_app = webhook.app
+ event_payload = EventPayload.objects.get()
+ assert json.loads(event_payload.payload) == payload
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ assert delivery.payload == event_payload
+ assert delivery.webhook == webhook
+ mock_request.assert_called_once_with(webhook_app.name, delivery)
+ assert response == PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=expected_response, error=None
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_process_checkout_without_request_data_and_static_payload(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_process_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ checkout,
+ transaction,
+ None,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_process_checkout_with_request_data_and_static_payload(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_process_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ checkout,
+ transaction,
+ data,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_process_checkout_without_request_data(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_PROCESS_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_process_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ checkout,
+ transaction,
+ None,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_process_checkout_with_request_data(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_PROCESS_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_process_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ checkout,
+ transaction,
+ data,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_process_session_skips_app_without_identifier(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ checkout,
+ permission_manage_payments,
+ transaction_item_generator,
+ transaction_session_response,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response.copy()
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = ""
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_PROCESS_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ checkout_id=checkout.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_process_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=checkout,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ assert not EventPayload.objects.first()
+ assert not EventDelivery.objects.first()
+ assert not mock_request.called
+ assert response == PaymentGatewayData(
+ app_identifier="", data=None, error="Missing app identifier"
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_process_order_without_request_data_and_static_payload(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ order,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_process_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ order,
+ transaction,
+ None,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_process_order_with_request_data_and_static_payload(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ order,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_process_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_static_payload(
+ order,
+ transaction,
+ data,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_process_order_without_request_data(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ order,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_PROCESS_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_process_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=None, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ order,
+ transaction,
+ None,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
+
+
+@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_transaction_process_order_with_request_data(
+ mock_request,
+ webhook_plugin,
+ webhook_app,
+ order,
+ permission_manage_payments,
+ transaction_session_response,
+ transaction_item_generator,
+):
+ # given
+ data = {"some": "request-data"}
+ expected_response_data = transaction_session_response
+ mock_request.return_value = expected_response_data
+ plugin = webhook_plugin()
+
+ webhook_app.identifier = "app.identifier"
+ webhook_app.save()
+ webhook_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ subscription_query=TRANSACTION_PROCESS_SESSION,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_PROCESS_SESSION
+ webhook.events.create(event_type=event_type)
+ amount = Decimal("10.00")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=webhook_app,
+ psp_reference=None,
+ name=None,
+ message=None,
+ )
+ action_type = TransactionFlowStrategy.CHARGE
+
+ # when
+ response = plugin.transaction_process_session(
+ transaction_session_data=TransactionSessionData(
+ transaction=transaction,
+ source_object=order,
+ action=TransactionProcessActionData(
+ amount=amount,
+ currency=transaction.currency,
+ action_type=action_type,
+ ),
+ payment_gateway=PaymentGatewayData(
+ app_identifier=webhook_app.identifier, data=data, error=None
+ ),
+ ),
+ previous_value=None,
+ )
+
+ # then
+ _assert_with_subscription(
+ order,
+ transaction,
+ data,
+ amount,
+ action_type,
+ webhook,
+ expected_response_data,
+ response,
+ mock_request,
+ )
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 912bc54638..036615e20f 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -862,6 +862,36 @@ def test_checkout_updated(
)
+@freeze_time("2014-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_checkout_fully_paid(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ checkout_with_items,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+
+ # when
+ manager.checkout_fully_paid(checkout_with_items)
+
+ # then
+ expected_data = generate_checkout_payload(checkout_with_items)
+
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data,
+ WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
+ [any_webhook],
+ checkout_with_items,
+ None,
+ )
+
+
@freeze_time("1914-06-28 10:50")
@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 68814b29db..629e7111e9 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -6,7 +6,7 @@ from datetime import timedelta
from decimal import Decimal
from functools import partial
from io import BytesIO
-from typing import List, Optional
+from typing import Callable, List, Optional
from unittest.mock import MagicMock, Mock
import graphene
@@ -37,7 +37,12 @@ from ..attribute.models import (
AttributeValueTranslation,
)
from ..attribute.utils import associate_attribute_values_to_instance
-from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ..checkout import base_calculations
+from ..checkout.fetch import (
+ fetch_active_discounts,
+ fetch_checkout_info,
+ fetch_checkout_lines,
+)
from ..checkout.models import Checkout, CheckoutLine, CheckoutMetadata
from ..checkout.utils import add_variant_to_checkout, add_voucher_to_checkout
from ..core import EventDeliveryStatus, JobStatus
@@ -86,7 +91,7 @@ from ..order.utils import (
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.models import Payment, TransactionEvent, TransactionItem
from ..payment.transaction_item_calculations import recalculate_transaction_amounts
from ..payment.utils import create_manual_adjustment_events
from ..permission.models import Permission
@@ -5525,10 +5530,12 @@ def transaction_item_generator():
charged_value=Decimal(0),
refunded_value=Decimal(0),
canceled_value=Decimal(0),
+ use_old_id=False,
):
if available_actions is None:
available_actions = []
transaction = TransactionItem.objects.create(
+ token=uuid.uuid4(),
name=name,
message=message,
psp_reference=psp_reference,
@@ -5539,6 +5546,7 @@ def transaction_item_generator():
app_identifier=app.identifier if app else None,
app=app,
user=user,
+ use_old_id=use_old_id,
)
create_manual_adjustment_events(
transaction=transaction,
@@ -5557,6 +5565,33 @@ def transaction_item_generator():
return create_transaction
+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
+
+
@pytest.fixture
def transaction_item_created_by_app(order, app, transaction_item_generator):
charged_amount = Decimal("10.0")
@@ -6234,6 +6269,90 @@ def checkout_with_item_for_cc(checkout_for_cc, product_variant_list):
return checkout_for_cc
+def checkout_with_prices(
+ checkout_with_items,
+ address,
+ address_other_country,
+ warehouse,
+ customer_user,
+ shipping_method,
+ voucher,
+):
+ # Need to save shipping_method before fetching checkout info.
+ checkout_with_items.shipping_method = shipping_method
+ checkout_with_items.save(update_fields=["shipping_method"])
+
+ manager = get_plugins_manager()
+ channel = checkout_with_items.channel
+ discounts_info = fetch_active_discounts()
+ lines = checkout_with_items.lines.all()
+ lines_info, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(
+ checkout_with_items, lines, discounts_info, manager
+ )
+
+ for line, line_info in zip(lines, lines_info):
+ line.total_price_net_amount = base_calculations.calculate_base_line_total_price(
+ line_info, channel, discounts_info
+ ).amount
+ line.total_price_gross_amount = line.total_price_net_amount * Decimal("1.230")
+
+ checkout_with_items.discount_amount = Decimal("5.000")
+ checkout_with_items.discount_name = "Voucher 5 USD"
+ checkout_with_items.user = customer_user
+ checkout_with_items.billing_address = address
+ checkout_with_items.shipping_address = address_other_country
+ checkout_with_items.collection_point = warehouse
+ checkout_with_items.subtotal_net_amount = Decimal("100.000")
+ checkout_with_items.subtotal_gross_amount = Decimal("123.000")
+ checkout_with_items.total_net_amount = Decimal("150.000")
+ checkout_with_items.total_gross_amount = Decimal("178.000")
+ shipping_amount = base_calculations.base_checkout_delivery_price(
+ checkout_info, lines_info
+ ).amount
+ checkout_with_items.shipping_price_net_amount = shipping_amount
+ checkout_with_items.shipping_price_gross_amount = shipping_amount * Decimal("1.08")
+ checkout_with_items.metadata_storage.metadata = {"meta_key": "meta_value"}
+ checkout_with_items.metadata_storage.private_metadata = {
+ "priv_meta_key": "priv_meta_value"
+ }
+
+ checkout_with_items.lines.bulk_update(
+ lines,
+ [
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ ],
+ )
+
+ checkout_with_items.save(
+ update_fields=[
+ "discount_amount",
+ "discount_name",
+ "user",
+ "billing_address",
+ "shipping_address",
+ "collection_point",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ "total_net_amount",
+ "total_gross_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ ]
+ )
+ checkout_with_items.metadata_storage.save(
+ update_fields=["metadata", "private_metadata"]
+ )
+
+ user = checkout_with_items.user
+ user.metadata = {"user_public_meta_key": "user_public_meta_value"}
+ user.save(update_fields=["metadata"])
+
+ return checkout_with_items
+
+
@pytest.fixture
def warehouses_with_shipping_zone(warehouses, shipping_zone):
warehouses[0].shipping_zones.add(shipping_zone)
@@ -6731,3 +6850,16 @@ def thumbnail_user(customer_user, image_list, media_root):
size=128,
image=image_list[1],
)
+
+
+def transaction_session_response():
+ return {
+ "pspReference": "psp-123",
+ "data": {"some-json": "data"},
+ "result": "CHARGE_SUCCESS",
+ "amount": "10.00",
+ "time": "2022-11-18T13:25:58.169685+00:00",
+ "externalUrl": "http://127.0.0.1:9090/external-reference",
+ "message": "Message related to the payment",
+ }
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 467960516b..07984c39f6 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -114,6 +114,7 @@ class WebhookEventAsyncType:
CHECKOUT_CREATED = "checkout_created"
CHECKOUT_UPDATED = "checkout_updated"
+ CHECKOUT_FULLY_PAID = "checkout_fully_paid"
CHECKOUT_METADATA_UPDATED = "checkout_metadata_updated"
NOTIFY_USER = "notify_user"
@@ -237,6 +238,7 @@ class WebhookEventAsyncType:
PRODUCT_VARIANT_STOCK_UPDATED: "Product variant stock updated",
CHECKOUT_CREATED: "Checkout created",
CHECKOUT_UPDATED: "Checkout updated",
+ CHECKOUT_FULLY_PAID: "Checkout fully paid",
CHECKOUT_METADATA_UPDATED: "Checkout metadata updated",
FULFILLMENT_CREATED: "Fulfillment created",
FULFILLMENT_CANCELED: "Fulfillment cancelled",
@@ -355,6 +357,7 @@ class WebhookEventAsyncType:
),
(CHECKOUT_CREATED, DISPLAY_LABELS[CHECKOUT_CREATED]),
(CHECKOUT_UPDATED, DISPLAY_LABELS[CHECKOUT_UPDATED]),
+ (CHECKOUT_FULLY_PAID, DISPLAY_LABELS[CHECKOUT_FULLY_PAID]),
(CHECKOUT_METADATA_UPDATED, DISPLAY_LABELS[CHECKOUT_METADATA_UPDATED]),
(FULFILLMENT_CREATED, DISPLAY_LABELS[FULFILLMENT_CREATED]),
(FULFILLMENT_CANCELED, DISPLAY_LABELS[FULFILLMENT_CANCELED]),
@@ -477,6 +480,7 @@ class WebhookEventAsyncType:
PRODUCT_VARIANT_STOCK_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
CHECKOUT_CREATED: CheckoutPermissions.MANAGE_CHECKOUTS,
CHECKOUT_UPDATED: CheckoutPermissions.MANAGE_CHECKOUTS,
+ CHECKOUT_FULLY_PAID: CheckoutPermissions.MANAGE_CHECKOUTS,
CHECKOUT_METADATA_UPDATED: CheckoutPermissions.MANAGE_CHECKOUTS,
FULFILLMENT_CREATED: OrderPermissions.MANAGE_ORDERS,
FULFILLMENT_CANCELED: OrderPermissions.MANAGE_ORDERS,
@@ -539,6 +543,10 @@ class WebhookEventSyncType:
CHECKOUT_FILTER_SHIPPING_METHODS = "checkout_filter_shipping_methods"
ORDER_FILTER_SHIPPING_METHODS = "order_filter_shipping_methods"
+ PAYMENT_GATEWAY_INITIALIZE_SESSION = "payment_gateway_initialize_session"
+ TRANSACTION_INITIALIZE_SESSION = "transaction_initialize_session"
+ TRANSACTION_PROCESS_SESSION = "transaction_process_session"
+
DISPLAY_LABELS = {
PAYMENT_AUTHORIZE: "Authorize payment",
PAYMENT_CAPTURE: "Capture payment",
@@ -555,6 +563,9 @@ class WebhookEventSyncType:
SHIPPING_LIST_METHODS_FOR_CHECKOUT: "Shipping list methods for checkout",
ORDER_FILTER_SHIPPING_METHODS: "Filter order shipping methods",
CHECKOUT_FILTER_SHIPPING_METHODS: "Filter checkout shipping methods",
+ PAYMENT_GATEWAY_INITIALIZE_SESSION: "Initialize payment gateway session",
+ TRANSACTION_INITIALIZE_SESSION: "Initialize transaction session",
+ TRANSACTION_PROCESS_SESSION: "Process transaction session",
}
CHOICES = [
@@ -582,6 +593,15 @@ class WebhookEventSyncType:
CHECKOUT_FILTER_SHIPPING_METHODS,
DISPLAY_LABELS[CHECKOUT_FILTER_SHIPPING_METHODS],
),
+ (
+ PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ DISPLAY_LABELS[PAYMENT_GATEWAY_INITIALIZE_SESSION],
+ ),
+ (
+ TRANSACTION_INITIALIZE_SESSION,
+ DISPLAY_LABELS[TRANSACTION_INITIALIZE_SESSION],
+ ),
+ (TRANSACTION_PROCESS_SESSION, DISPLAY_LABELS[TRANSACTION_PROCESS_SESSION]),
]
ALL = [event[0] for event in CHOICES]
@@ -596,6 +616,12 @@ class WebhookEventSyncType:
PAYMENT_VOID,
]
+ ALLOWED_IN_CIRCULAR_QUERY = [
+ PAYMENT_GATEWAY_INITIALIZE_SESSION,
+ TRANSACTION_INITIALIZE_SESSION,
+ TRANSACTION_PROCESS_SESSION,
+ ]
+
PERMISSIONS = {
PAYMENT_AUTHORIZE: PaymentPermissions.HANDLE_PAYMENTS,
PAYMENT_CAPTURE: PaymentPermissions.HANDLE_PAYMENTS,
@@ -612,4 +638,7 @@ class WebhookEventSyncType:
SHIPPING_LIST_METHODS_FOR_CHECKOUT: ShippingPermissions.MANAGE_SHIPPING,
ORDER_FILTER_SHIPPING_METHODS: OrderPermissions.MANAGE_ORDERS,
CHECKOUT_FILTER_SHIPPING_METHODS: CheckoutPermissions.MANAGE_CHECKOUTS,
+ PAYMENT_GATEWAY_INITIALIZE_SESSION: PaymentPermissions.HANDLE_PAYMENTS,
+ TRANSACTION_INITIALIZE_SESSION: PaymentPermissions.HANDLE_PAYMENTS,
+ TRANSACTION_PROCESS_SESSION: PaymentPermissions.HANDLE_PAYMENTS,
}
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 20cba22e3f..5f539e9eb0 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -3,7 +3,17 @@ import uuid
from collections import defaultdict
from dataclasses import asdict
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, DefaultDict, Dict, Iterable, List, Optional, Set
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ DefaultDict,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Set,
+ Union,
+)
import graphene
from django.db.models import F, QuerySet, Sum
@@ -53,12 +63,17 @@ if TYPE_CHECKING:
# pylint: disable=unused-import
from ..product.models import ProductVariant
+from ..payment.models import Payment, TransactionItem
if TYPE_CHECKING:
from ..discount.models import Sale
from ..invoice.models import Invoice
- from ..payment.interface import PaymentData, TransactionActionData
- from ..payment.models import Payment
+ from ..payment.interface import (
+ PaymentData,
+ PaymentGatewayData,
+ TransactionActionData,
+ TransactionProcessActionData,
+ )
from ..plugins.base_plugin import RequestorOrLazyObject
from ..translation.models import Translation
@@ -140,11 +155,10 @@ def generate_metadata_updated_payload(
):
serializer = PayloadSerializer()
- if isinstance(instance, Checkout):
+ if isinstance(instance, Checkout) or isinstance(instance, TransactionItem):
pk_field_name = "token"
else:
pk_field_name = "id"
-
return serializer.serialize(
[instance],
fields=[],
@@ -1494,6 +1508,29 @@ def generate_transaction_action_request_payload(
return json.dumps(payload, cls=CustomJsonEncoder)
+def generate_transaction_session_payload(
+ transaction_process_action: "TransactionProcessActionData",
+ transaction: "TransactionItem",
+ transaction_object: Union["Order", "Checkout"],
+ payment_gateway: "PaymentGatewayData",
+):
+ transaction_object_id = graphene.Node.to_global_id(
+ transaction_object.__class__.__name__, transaction_object.pk
+ )
+
+ payload = {
+ "id": transaction_object_id,
+ "data": payment_gateway.data,
+ "amount": transaction_process_action.amount,
+ "currency": transaction_process_action.currency,
+ "action_type": transaction_process_action.action_type.upper(),
+ "transaction_id": graphene.Node.to_global_id(
+ "TransactionItem", transaction.token
+ ),
+ }
+ return json.dumps(payload, cls=CustomJsonEncoder)
+
+
@traced_payload_generator
def generate_thumbnail_payload(thumbnail: Thumbnail):
thumbnail_id = graphene.Node.to_global_id("Thumbnail", thumbnail.id)
diff --git a/saleor/webhook/tests/conftest.py b/saleor/webhook/tests/conftest.py
index 32f381c65a..b2f66c16d8 100644
--- a/saleor/webhook/tests/conftest.py
+++ b/saleor/webhook/tests/conftest.py
@@ -1,100 +1,7 @@
-from decimal import Decimal
from unittest.mock import Mock, patch
import pytest
-from ...checkout import base_calculations
-from ...checkout.fetch import (
- fetch_active_discounts,
- fetch_checkout_info,
- fetch_checkout_lines,
-)
-from ...plugins.manager import get_plugins_manager
-
-
-def checkout_with_prices(
- checkout_with_items,
- address,
- address_other_country,
- warehouse,
- customer_user,
- shipping_method,
- voucher,
-):
- # Need to save shipping_method before fetching checkout info.
- checkout_with_items.shipping_method = shipping_method
- checkout_with_items.save(update_fields=["shipping_method"])
-
- manager = get_plugins_manager()
- channel = checkout_with_items.channel
- discounts_info = fetch_active_discounts()
- lines = checkout_with_items.lines.all()
- lines_info, _ = fetch_checkout_lines(checkout_with_items)
- checkout_info = fetch_checkout_info(
- checkout_with_items, lines, discounts_info, manager
- )
-
- for line, line_info in zip(lines, lines_info):
- line.total_price_net_amount = base_calculations.calculate_base_line_total_price(
- line_info, channel, discounts_info
- ).amount
- line.total_price_gross_amount = line.total_price_net_amount * Decimal("1.230")
-
- checkout_with_items.discount_amount = Decimal("5.000")
- checkout_with_items.discount_name = "Voucher 5 USD"
- checkout_with_items.user = customer_user
- checkout_with_items.billing_address = address
- checkout_with_items.shipping_address = address_other_country
- checkout_with_items.collection_point = warehouse
- checkout_with_items.subtotal_net_amount = Decimal("100.000")
- checkout_with_items.subtotal_gross_amount = Decimal("123.000")
- checkout_with_items.total_net_amount = Decimal("150.000")
- checkout_with_items.total_gross_amount = Decimal("178.000")
- shipping_amount = base_calculations.base_checkout_delivery_price(
- checkout_info, lines_info
- ).amount
- checkout_with_items.shipping_price_net_amount = shipping_amount
- checkout_with_items.shipping_price_gross_amount = shipping_amount * Decimal("1.08")
- checkout_with_items.metadata_storage.metadata = {"meta_key": "meta_value"}
- checkout_with_items.metadata_storage.private_metadata = {
- "priv_meta_key": "priv_meta_value"
- }
-
- checkout_with_items.lines.bulk_update(
- lines,
- [
- "total_price_net_amount",
- "total_price_gross_amount",
- ],
- )
-
- checkout_with_items.save(
- update_fields=[
- "discount_amount",
- "discount_name",
- "user",
- "billing_address",
- "shipping_address",
- "collection_point",
- "subtotal_net_amount",
- "subtotal_gross_amount",
- "total_net_amount",
- "total_gross_amount",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- ]
- )
- checkout_with_items.metadata_storage.save(
- update_fields=["metadata", "private_metadata"]
- )
-
- user = checkout_with_items.user
- user.metadata = {"user_public_meta_key": "user_public_meta_value"}
- user.save(update_fields=["metadata"])
-
- return checkout_with_items
-
@pytest.fixture
def mocked_fetch_checkout():
@@ -104,7 +11,7 @@ def mocked_fetch_checkout():
return checkout_info, lines
with patch(
- "saleor.checkout.calculations.fetch_checkout_prices_if_expired",
+ "saleor.checkout.calculations.fetch_checkout_data",
new=Mock(side_effect=mocked_fetch_side_effect),
) as mocked_fetch:
yield mocked_fetch
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 620549a292..3220186c26 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -1235,7 +1235,7 @@ def test_generate_transaction_item_metadata_updated_payload(
# then
assert payload == {
"id": graphene.Node.to_global_id(
- "TransactionItem", transaction_item_created_by_user.id
+ "TransactionItem", transaction_item_created_by_user.token
),
"meta": generate_meta(requestor_data=generate_requestor(customer_user)),
}
diff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.py
index 8c30a0cd1d..a63bd70238 100644
--- a/saleor/webhook/utils.py
+++ b/saleor/webhook/utils.py
@@ -15,6 +15,7 @@ def get_webhooks_for_event(
event_type: str,
webhooks: Optional["QuerySet[Webhook]"] = None,
apps_ids: Optional["list[int]"] = None,
+ apps_identifier: Optional[list[str]] = None,
) -> "QuerySet[Webhook]":
"""Get active webhooks from the database for an event."""
permissions = {}
@@ -31,6 +32,9 @@ def get_webhooks_for_event(
app_kwargs: dict = {"is_active": True, **permissions}
if apps_ids:
app_kwargs["id__in"] = apps_ids
+ if apps_identifier:
+ app_kwargs["identifier__in"] = apps_identifier
+
apps = App.objects.filter(**app_kwargs)
event_types = [event_type]
if event_type in WebhookEventAsyncType.ALL: