Skip to content

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

Gift cards as payment method (#18579)

Marcin Wcisłoe2ebabee9dcf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c54505769..c25548af0b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ All notable, unreleased changes to this project will be documented in this file.
### GraphQL API
+- Gift cards support as payment method within Transaction API (read more in the [docs](https://docs.saleor.io/developer/gift-cards#using-gift-cards-in-checkout)).
### Webhooks
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index 90f939276c..579a7c0f4a 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -9,6 +9,7 @@ from semantic_version import NpmSpec, Version
from semantic_version.base import Range
from .. import __version__
+from ..giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from ..graphql.core.utils import str_to_enum
from ..graphql.webhook.subscription_query import SubscriptionQuery
from ..permission.enums import (
@@ -149,6 +150,15 @@ def clean_manifest_data(manifest_data, raise_for_saleor_version=False):
code=AppErrorCode.UNIQUE.value,
)
)
+
+ if manifest_data.get("id") == GIFT_CARD_PAYMENT_GATEWAY_ID:
+ errors["identifier"].append(
+ ValidationError(
+ "App with this identifier cannot be installed",
+ code=AppErrorCode.UNIQUE.value,
+ )
+ )
+
if not errors:
_clean_extensions(manifest_data, app_permissions, errors)
_clean_webhooks(manifest_data, errors)
diff --git a/saleor/channel/migrations/0027_channel_allow_legacy_gift_card_use.py b/saleor/channel/migrations/0027_channel_allow_legacy_gift_card_use.py
new file mode 100644
index 0000000000..c202e03614
--- /dev/null
+++ b/saleor/channel/migrations/0027_channel_allow_legacy_gift_card_use.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.5 on 2025-12-01 08:12
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("channel", "0026_channel_automatic_completion_cut_off_date"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="channel",
+ name="allow_legacy_gift_card_use",
+ field=models.BooleanField(db_default=True, default=True),
+ ),
+ ]
diff --git a/saleor/channel/models.py b/saleor/channel/models.py
index e33fd0eab6..167065d38f 100644
--- a/saleor/channel/models.py
+++ b/saleor/channel/models.py
@@ -72,6 +72,8 @@ class Channel(ModelWithMetadata):
)
checkout_release_funds_cut_off_date = models.DateTimeField(null=True, blank=True)
+ allow_legacy_gift_card_use = models.BooleanField(default=True, db_default=True)
+
class Meta(ModelWithMetadata.Meta):
ordering = ("slug",)
app_label = "channel"
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index ac0ac599d0..fcea057ce9 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -813,6 +813,16 @@ def add_promo_code_to_checkout(
promo_code,
)
elif promo_code_is_gift_card(promo_code):
+ if not checkout_info.channel.allow_legacy_gift_card_use:
+ raise ValidationError(
+ {
+ "promo_code": ValidationError(
+ "Adding gift card to checkout in this channel is not allowed.",
+ code=CheckoutErrorCode.GIFT_CARD_NOT_APPLICABLE.value,
+ )
+ }
+ )
+
user_email = cast(str, checkout_info.get_customer_email())
add_gift_card_code_to_checkout(
checkout_info.checkout,
diff --git a/saleor/giftcard/const.py b/saleor/giftcard/const.py
new file mode 100644
index 0000000000..7b2cecb94d
--- /dev/null
+++ b/saleor/giftcard/const.py
@@ -0,0 +1,2 @@
+GIFT_CARD_PAYMENT_GATEWAY_ID = "saleor.io.gift-card-payment-gateway"
+GIFT_CARD_PAYMENT_GATEWAY_NAME = "Gift Card Payment Gateway"
diff --git a/saleor/giftcard/gateway.py b/saleor/giftcard/gateway.py
new file mode 100644
index 0000000000..252be8d166
--- /dev/null
+++ b/saleor/giftcard/gateway.py
@@ -0,0 +1,382 @@
+from decimal import Decimal
+from typing import Annotated
+from uuid import uuid4
+
+import pydantic
+from django.db import transaction
+from django.db.models import Exists, F, OuterRef, Q
+from django.utils import timezone
+
+from ..checkout.models import Checkout
+from ..core.prices import quantize_price
+from ..graphql.payment.mutations.transaction.utils import (
+ create_transaction_event_requested,
+)
+from ..order.models import Order
+from ..payment import TransactionAction, TransactionEventType
+from ..payment.interface import (
+ TransactionSessionData,
+ TransactionSessionResult,
+)
+from ..payment.models import TransactionEvent, TransactionItem
+from ..payment.utils import (
+ create_transaction_event_from_request_and_webhook_response,
+)
+from .const import GIFT_CARD_PAYMENT_GATEWAY_ID
+from .models import GiftCard
+
+
+class GiftCardPaymentGatewayDataSchema(pydantic.BaseModel):
+ code: Annotated[
+ str,
+ pydantic.Field(
+ description="Gift card code.",
+ min_length=8,
+ max_length=16,
+ ),
+ ]
+
+
+class GiftCardPaymentGatewayException(Exception):
+ def __init__(self, msg=None):
+ if msg is None:
+ msg = "Gift card payment gateway error"
+ super().__init__(msg)
+
+
+def transaction_initialize_session_with_gift_card_payment_method(
+ transaction_session_data: "TransactionSessionData",
+ source_object: Checkout | Order,
+) -> "TransactionSessionResult":
+ """Initialize session for gift card payment method.
+
+ Attach payment method app identifier to the transaction, validate transaction data and gift card.
+
+ Since gift card funds can be authorized to only one checkout at the time this function also detaches
+ gift card from any checkouts it has been previously attached to.
+ """
+ attach_app_identifier_to_transaction(transaction_session_data)
+ gift_card = None
+
+ try:
+ validate_transaction_session_data(transaction_session_data, source_object)
+ gift_card = validate_and_get_gift_card(transaction_session_data)
+ except GiftCardPaymentGatewayException as exc:
+ return TransactionSessionResult(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ response={
+ "result": TransactionEventType.AUTHORIZATION_FAILURE.upper(),
+ "pspReference": str(uuid4()),
+ "amount": transaction_session_data.action.amount,
+ "message": exc,
+ },
+ )
+ else:
+ return TransactionSessionResult(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ response={
+ "result": TransactionEventType.AUTHORIZATION_SUCCESS.upper(),
+ "pspReference": str(uuid4()),
+ "amount": transaction_session_data.action.amount,
+ "message": f"Gift card (ending: {gift_card.display_code}).",
+ "actions": [TransactionAction.CANCEL.upper()],
+ },
+ )
+ finally:
+ detach_gift_card_from_previous_checkout_transactions(gift_card)
+ attach_gift_card_to_transaction(transaction_session_data, gift_card)
+
+
+def attach_app_identifier_to_transaction(
+ transaction_session_data: "TransactionSessionData",
+):
+ """Attach gift card payment gateway identifier to a transaction."""
+ transaction_session_data.transaction.app_identifier = GIFT_CARD_PAYMENT_GATEWAY_ID
+ transaction_session_data.transaction.save(update_fields=["app_identifier"])
+
+
+def validate_transaction_session_data(
+ transaction_session_data: "TransactionSessionData",
+ source_object: Checkout | Order,
+):
+ """Validate whether object that the gift card is being attached to is a checkout and validate whether transaction data is correct."""
+ if not isinstance(source_object, Checkout):
+ raise GiftCardPaymentGatewayException(
+ msg=f"Cannot initialize transaction for payment gateway: {GIFT_CARD_PAYMENT_GATEWAY_ID} and object type other than Checkout."
+ )
+
+ try:
+ GiftCardPaymentGatewayDataSchema.model_validate(
+ transaction_session_data.payment_gateway_data.data
+ )
+ except pydantic.ValidationError as exc:
+ raise GiftCardPaymentGatewayException(
+ msg="Incorrect payment gateway data."
+ ) from exc
+
+
+def validate_and_get_gift_card(
+ transaction_session_data: "TransactionSessionData",
+):
+ """Check for the existence of given gift card and lock it for use in a database transaction. Check whether gift card has enough funds to cover transaction amount."""
+ try:
+ gift_card = (
+ GiftCard.objects.active(date=timezone.now().date())
+ .filter(
+ code=transaction_session_data.payment_gateway_data.data["code"], # type: ignore[call-overload, index]
+ currency=transaction_session_data.action.currency,
+ )
+ .select_for_update()
+ .get()
+ )
+ except GiftCard.DoesNotExist as exc:
+ raise GiftCardPaymentGatewayException(
+ msg="Gift card code is not valid."
+ ) from exc
+
+ if transaction_session_data.action.amount > gift_card.current_balance_amount:
+ raise GiftCardPaymentGatewayException(
+ msg=f"Gift card has insufficient amount ({quantize_price(gift_card.current_balance_amount, gift_card.currency)}) "
+ f"to cover requested amount ({quantize_price(transaction_session_data.action.amount, transaction_session_data.action.currency)})."
+ )
+
+ return gift_card
+
+
+def attach_gift_card_to_transaction(
+ transaction_session_data: "TransactionSessionData",
+ gift_card: GiftCard | None,
+):
+ """Attach gift card to a transaction."""
+ if not gift_card:
+ return
+
+ transaction_session_data.transaction.gift_card = gift_card
+ transaction_session_data.transaction.save(update_fields=["gift_card"])
+
+
+def detach_gift_card_from_previous_checkout_transactions(
+ gift_card: GiftCard | None,
+):
+ """Find all gift card payment gateway transactions tied to a checkout and perform authorization cancellation for the same amount as authorization was granted.
+
+ The function is used to ensure a single gift card does not authorize funds to more than a single checkout at the time.
+ """
+ if not gift_card:
+ return
+
+ # Detach gift card from the previously attached transaction items and create authorization cancellation events.
+ transactions_to_cancel_qs = TransactionItem.objects.filter(
+ # must cancel transactions for gift card payment gateway
+ Q(app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID),
+ # must cancel transactions for this gift card
+ Q(gift_card=gift_card),
+ # must cancel transactions where checkout identifier is not empty
+ Q(checkout_id__isnull=False),
+ # must cancel transactions where order identifier is empty (transaction is not
+ # tied to an order yet)
+ Q(order_id__isnull=True),
+ )
+
+ for transaction_item in transactions_to_cancel_qs:
+ request_event = create_transaction_event_requested(
+ transaction_item,
+ transaction_item.amount_authorized.amount,
+ TransactionAction.CANCEL,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ )
+
+ response: dict[str, str | Decimal | list | None] = {
+ "result": TransactionEventType.CANCEL_SUCCESS.upper(),
+ "pspReference": str(uuid4()),
+ "amount": transaction_item.amount_authorized.amount,
+ "message": f"Gift card (code ending with: {gift_card.display_code}) has been authorized as payment method in a different checkout or has been authorized in the same checkout again.",
+ "actions": [],
+ }
+
+ create_transaction_event_from_request_and_webhook_response(
+ request_event,
+ None,
+ transaction_webhook_response=response,
+ )
+
+ transactions_to_cancel_qs.update(gift_card=None)
+
+
+def charge_gift_card_transactions(
+ order: "Order",
+):
+ """Find all gift card payment gateway transactions tied to an order and attempt to charge funds from gift cards.
+
+ If gift card cannot be found or has insufficient funds the charge request fails.
+ """
+
+ # Order object may already have prefetched related objects.
+ # Prefetched payment transactions cause logic called a few layers beneath to operate on outdated
+ # order transactions therfore here the cache is dropped.
+ if hasattr(order, "_prefetched_objects_cache"):
+ order._prefetched_objects_cache.pop("payment_transactions", None)
+
+ # Ensure that gift card transaction is not attempted to be charged more than once.
+ gift_card_transactions = order.payment_transactions.filter(
+ ~Exists(
+ TransactionEvent.objects.filter(
+ transaction=OuterRef("pk"), type=TransactionEventType.CHARGE_REQUEST
+ )
+ ),
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ gift_card__isnull=False,
+ authorized_value__gt=Decimal(0),
+ charged_value=Decimal(0),
+ )
+
+ for gift_card_transaction in gift_card_transactions:
+ request_event = create_transaction_event_requested(
+ gift_card_transaction,
+ gift_card_transaction.amount_authorized.amount,
+ TransactionAction.CHARGE,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ )
+
+ response = {
+ "result": TransactionEventType.CHARGE_FAILURE.upper(),
+ "pspReference": str(uuid4()),
+ "amount": gift_card_transaction.amount_authorized.amount,
+ "message": "Gift card could not be found.",
+ }
+
+ if not gift_card_transaction.gift_card_id:
+ create_transaction_event_from_request_and_webhook_response(
+ request_event,
+ None,
+ transaction_webhook_response=response,
+ )
+ continue
+
+ try:
+ with transaction.atomic():
+ gift_card = (
+ GiftCard.objects.filter(id=gift_card_transaction.gift_card_id)
+ .select_for_update()
+ .get()
+ )
+
+ if (
+ gift_card_transaction.authorized_value
+ > gift_card.current_balance_amount
+ ):
+ response["message"] = (
+ f"Gift card has insufficient amount ({quantize_price(gift_card.current_balance_amount, gift_card.currency)}) "
+ f"to cover requested amount ({quantize_price(gift_card_transaction.authorized_value, gift_card_transaction.currency)})."
+ )
+ else:
+ gift_card.current_balance_amount -= (
+ gift_card_transaction.authorized_value
+ )
+ gift_card.save(update_fields=["current_balance_amount"])
+
+ response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ response["message"] = (
+ f"Gift card (ending: {gift_card.display_code})."
+ )
+ response["actions"] = [TransactionAction.REFUND.upper()]
+ except GiftCard.DoesNotExist:
+ # Gift card must have been just deleted.
+ # Eat the exception, failure response dict is already prepared.
+ pass
+
+ create_transaction_event_from_request_and_webhook_response(
+ request_event,
+ None,
+ transaction_webhook_response=response,
+ )
+
+
+def cancel_gift_card_transaction(
+ transaction_item: "TransactionItem", request_event: "TransactionEvent"
+):
+ """Perform authorization cancellation for the same amount as authorization was granted.
+
+ If checkout no longer exists or CANCEL action is not available for the transaction authorization cancellation fails.
+ """
+ response: dict[str, str | Decimal | list | None]
+ amount = request_event.amount_value
+
+ if (
+ not transaction_item.checkout
+ or TransactionAction.CANCEL not in transaction_item.available_actions
+ ):
+ response = {
+ "result": TransactionEventType.CANCEL_FAILURE.upper(),
+ "pspReference": str(uuid4()),
+ "amount": amount,
+ }
+ else:
+ response = {
+ "result": TransactionEventType.CANCEL_SUCCESS.upper(),
+ "pspReference": str(uuid4()),
+ "amount": amount,
+ }
+
+ if amount >= transaction_item.authorized_value:
+ response["actions"] = []
+
+ create_transaction_event_from_request_and_webhook_response(
+ request_event,
+ None,
+ transaction_webhook_response=response,
+ )
+
+
+def refund_gift_card_transaction(
+ transaction_item: "TransactionItem", request_event: "TransactionEvent"
+):
+ """Refund funds to a gift card which previously were charged from the same gift card.
+
+ If gift card no longer exists refund fails.
+ """
+ amount = request_event.amount_value
+
+ response: dict[str, str | Decimal | list | None] = {
+ "result": TransactionEventType.REFUND_FAILURE.upper(),
+ "pspReference": str(uuid4()),
+ "amount": amount,
+ "message": "Gift card could not be found.",
+ }
+
+ if not transaction_item.gift_card_id:
+ create_transaction_event_from_request_and_webhook_response(
+ request_event,
+ None,
+ transaction_webhook_response=response,
+ )
+ return
+
+ try:
+ with transaction.atomic():
+ gift_card = (
+ GiftCard.objects.filter(id=transaction_item.gift_card_id)
+ .select_for_update()
+ .get()
+ )
+ gift_card.current_balance_amount = F("current_balance_amount") + amount
+ gift_card.save(update_fields=["current_balance_amount"])
+ except GiftCard.DoesNotExist:
+ # Gift card must have been just deleted.
+ # Eat the exception, failure response dict is already prepared.
+ pass
+ else:
+ response = {
+ "result": TransactionEventType.REFUND_SUCCESS.upper(),
+ "pspReference": str(uuid4()),
+ "amount": amount,
+ }
+
+ if amount >= transaction_item.charged_value:
+ response["actions"] = []
+
+ create_transaction_event_from_request_and_webhook_response(
+ request_event,
+ None,
+ transaction_webhook_response=response,
+ )
diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.py
index abd63872fa..9735c0d85c 100644
--- a/saleor/graphql/channel/mutations/channel_create.py
+++ b/saleor/graphql/channel/mutations/channel_create.py
@@ -14,6 +14,7 @@ from ...core.descriptions import (
ADDED_IN_320,
ADDED_IN_321,
ADDED_IN_322,
+ ADDED_IN_323,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
)
@@ -129,6 +130,14 @@ class CheckoutSettingsInput(BaseInputObjectType):
+ ADDED_IN_322,
required=False,
)
+ allow_legacy_gift_card_use = graphene.Boolean(
+ description=(
+ "Default to `true`. Determines whether gift cards can be attached to "
+ "a Checkout via `addPromoCode` mutation. Usage of this mutation with gift cards "
+ "is deprecated."
+ )
+ + ADDED_IN_323,
+ )
class Meta:
doc_category = DOC_CATEGORY_CHECKOUT
diff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.py
index f8082bb1d8..7aa2def45f 100644
--- a/saleor/graphql/channel/mutations/utils.py
+++ b/saleor/graphql/channel/mutations/utils.py
@@ -114,6 +114,11 @@ def clean_input_checkout_settings(
):
clean_automatic_completion(checkout_settings, cleaned_input)
+ if "allow_legacy_gift_card_use" in checkout_settings:
+ cleaned_input["allow_legacy_gift_card_use"] = checkout_settings[
+ "allow_legacy_gift_card_use"
+ ]
+
# Handle legacy fields
if "use_legacy_error_flow" in checkout_settings:
cleaned_input["use_legacy_error_flow_for_checkout"] = checkout_settings[
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.py
index 9d1963b43f..7c09a9bbe6 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py
@@ -57,6 +57,7 @@ CHANNEL_CREATE_MUTATION = """
automaticallyCompleteFullyPaidCheckouts
automaticCompletionDelay
automaticCompletionCutOffDate
+ allowLegacyGiftCardUse
}
paymentSettings {
defaultTransactionFlowStrategy
@@ -1495,3 +1496,44 @@ def test_channel_create_set_use_legacy_line_discount_propagation(
== expected_result
)
assert channel.use_legacy_line_discount_propagation_for_order == expected_result
+
+
[email protected]("allow_legacy_gift_card_use", [True, False])
+def test_channel_create_allow_legacy_gift_card_use(
+ allow_legacy_gift_card_use,
+ 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,
+ "checkoutSettings": {"allowLegacyGiftCardUse": allow_legacy_gift_card_use},
+ }
+ }
+
+ # 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["checkoutSettings"]["allowLegacyGiftCardUse"]
+ == allow_legacy_gift_card_use
+ )
+ assert channel.allow_legacy_gift_card_use == allow_legacy_gift_card_use
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index 52aae81a77..e8a85659af 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -1295,6 +1295,7 @@ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """
automaticallyCompleteFullyPaidCheckouts
automaticCompletionDelay
automaticCompletionCutOffDate
+ allowLegacyGiftCardUse
}
}
errors{
@@ -2233,3 +2234,39 @@ def test_channel_update_set_use_legacy_line_discount_propagation(
== expected_result
)
assert channel_USD.use_legacy_line_discount_propagation_for_order == expected_result
+
+
[email protected]("allow_legacy_gift_card_use", [True, False])
+def test_channel_update_allow_legacy_gift_card_use(
+ allow_legacy_gift_card_use,
+ permission_manage_channels,
+ staff_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "checkoutSettings": {"allowLegacyGiftCardUse": allow_legacy_gift_card_use},
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ channel_USD.refresh_from_db()
+ assert (
+ channel_data["checkoutSettings"]["allowLegacyGiftCardUse"]
+ == allow_legacy_gift_card_use
+ )
+ assert channel_USD.allow_legacy_gift_card_use == allow_legacy_gift_card_use
diff --git a/saleor/graphql/channel/tests/queries/test_channel.py b/saleor/graphql/channel/tests/queries/test_channel.py
index 906f0f05fb..eb6a62e08c 100644
--- a/saleor/graphql/channel/tests/queries/test_channel.py
+++ b/saleor/graphql/channel/tests/queries/test_channel.py
@@ -476,6 +476,7 @@ QUERY_CHANNEL_CHECKOUT_SETTINGS = """
checkoutSettings {
useLegacyErrorFlow
automaticallyCompleteFullyPaidCheckouts
+ allowLegacyGiftCardUse
}
}
}
@@ -488,10 +489,12 @@ def test_query_channel_checkout_settings_as_staff_user(
# given
channel_USD.use_legacy_error_flow_for_checkout = False
channel_USD.automatically_complete_fully_paid_checkouts = True
+ channel_USD.allow_legacy_gift_card_use = False
channel_USD.save(
update_fields=[
"use_legacy_error_flow_for_checkout",
"automatically_complete_fully_paid_checkouts",
+ "allow_legacy_gift_card_use",
]
)
@@ -517,6 +520,10 @@ def test_query_channel_checkout_settings_as_staff_user(
channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
== channel_USD.automatically_complete_fully_paid_checkouts
)
+ assert (
+ channel_data["checkoutSettings"]["allowLegacyGiftCardUse"]
+ == channel_USD.allow_legacy_gift_card_use
+ )
def test_query_channel_checkout_settings_as_app(
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index 51a8658ca0..e2f80d2b63 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -22,6 +22,7 @@ from ..core.descriptions import (
ADDED_IN_320,
ADDED_IN_321,
ADDED_IN_322,
+ ADDED_IN_323,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
)
@@ -108,6 +109,15 @@ class CheckoutSettings(ObjectType):
)
+ ADDED_IN_322,
)
+ allow_legacy_gift_card_use = graphene.Boolean(
+ required=True,
+ description=(
+ "Default to `true`. Determines whether gift cards can be attached to "
+ "a Checkout via `addPromoCode` mutation. Usage of this mutation with gift cards "
+ "is deprecated."
+ )
+ + ADDED_IN_323,
+ )
class Meta:
description = "Represents the channel-specific checkout settings."
@@ -529,6 +539,7 @@ class Channel(ModelObjectType):
automatically_complete_fully_paid_checkouts=complete_paid_checkouts,
automatic_completion_delay=root.automatic_completion_delay,
automatic_completion_cut_off_date=root.automatic_completion_cut_off_date,
+ allow_legacy_gift_card_use=root.allow_legacy_gift_card_use,
)
@staticmethod
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index 7b1909953b..f6dcdead7f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -1170,6 +1170,31 @@ def test_checkout_add_gift_card_without_checkout_email_used_by_other_user(
assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_code
+def test_checkout_add_gift_card_disallowed_by_channel_flag(
+ api_client, checkout_with_item, gift_card
+):
+ # given
+ channel = checkout_with_item.channel
+ channel.allow_legacy_gift_card_use = False
+ channel.save(update_fields=["allow_legacy_gift_card_use"])
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "promoCode": gift_card.code,
+ }
+
+ # when
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ # then
+ assert len(data["errors"]) == 1
+ assert data["errors"][0] == {
+ "code": CheckoutErrorCode.GIFT_CARD_NOT_APPLICABLE.name,
+ "field": "promoCode",
+ "message": "Adding gift card to checkout in this channel is not allowed.",
+ }
+
+
@pytest.mark.parametrize("shipping_price", [12, 10, 5])
def test_checkout_add_free_shipping_voucher_do_not_invalidate_shipping_method(
shipping_price,
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 5ead92d29b..2e497d85ed 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -37,6 +37,10 @@ from ....checkout.utils import (
from ....core.db.connection import allow_writer
from ....core.prices import quantize_price
from ....discount import DiscountValueType, VoucherType
+from ....giftcard.const import (
+ GIFT_CARD_PAYMENT_GATEWAY_ID,
+ GIFT_CARD_PAYMENT_GATEWAY_NAME,
+)
from ....payment import TransactionAction
from ....payment.interface import (
ListStoredPaymentMethodsRequestData,
@@ -72,6 +76,18 @@ def expected_dummy_gateway():
}
+def expected_gift_card_payment_gateway():
+ return {
+ "config": [],
+ "currencies": [
+ "USD",
+ ],
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "name": GIFT_CARD_PAYMENT_GATEWAY_NAME,
+ }
+
+
GET_CHECKOUT_PAYMENTS_QUERY = """
query getCheckoutPayments($id: ID) {
checkout(id: $id) {
@@ -93,6 +109,7 @@ def test_checkout_available_payment_gateways(
api_client,
checkout_with_item,
expected_dummy_gateway,
+ expected_gift_card_payment_gateway,
):
query = GET_CHECKOUT_PAYMENTS_QUERY
variables = {"id": to_global_id_or_none(checkout_with_item)}
@@ -102,6 +119,7 @@ def test_checkout_available_payment_gateways(
data = content["data"]["checkout"]
assert data["availablePaymentGateways"] == [
expected_dummy_gateway,
+ expected_gift_card_payment_gateway,
]
@@ -131,6 +149,7 @@ def test_checkout_available_payment_gateways_valid_info_sent(
checkout_info=checkout_info,
checkout_lines=checkout_lines_info,
channel_slug=channel_slug,
+ active_only=True,
)
@@ -138,6 +157,7 @@ def test_checkout_available_payment_gateways_currency_specified_USD(
api_client,
checkout_with_item,
expected_dummy_gateway,
+ expected_gift_card_payment_gateway,
sample_gateway,
):
checkout_with_item.currency = "USD"
@@ -153,6 +173,7 @@ def test_checkout_available_payment_gateways_currency_specified_USD(
assert {gateway["id"] for gateway in data["availablePaymentGateways"]} == {
expected_dummy_gateway["id"],
ActiveDummyPaymentGateway.PLUGIN_ID,
+ expected_gift_card_payment_gateway["id"],
}
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 9b36e4ae46..ce6078d575 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -18,6 +18,7 @@ from ...graphql.core.context import (
SyncWebhookControlContext,
get_database_connection_name,
)
+from ...payment.gateway import get_payment_gateways
from ...payment.interface import ListStoredPaymentMethodsRequestData
from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import (
@@ -1396,7 +1397,8 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
@allow_writer_in_context(info.context)
def get_available_payment_gateways(results):
checkout_info, lines_info = results
- return manager.list_payment_gateways(
+ return get_payment_gateways(
+ manager=manager,
currency=root.node.currency,
checkout_info=checkout_info,
checkout_lines=lines_info,
diff --git a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
index 21312dcd2a..d2968cff60 100644
--- a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
+++ b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
@@ -16,8 +16,9 @@ from .....core.utils import get_client_ip
from .....core.utils.url import validate_storefront_url
from .....payment import StorePaymentMethod
from .....payment.error_codes import PaymentErrorCode
+from .....payment.gateway import is_currency_supported
from .....payment.models import TransactionItem
-from .....payment.utils import create_payment, is_currency_supported
+from .....payment.utils import create_payment
from ....account.i18n import I18nMixin
from ....checkout.mutations.utils import get_checkout
from ....checkout.types import Checkout
diff --git a/saleor/graphql/payment/mutations/payment/payment_check_balance.py b/saleor/graphql/payment/mutations/payment/payment_check_balance.py
index 7929c1d8f5..6226e10522 100644
--- a/saleor/graphql/payment/mutations/payment/payment_check_balance.py
+++ b/saleor/graphql/payment/mutations/payment/payment_check_balance.py
@@ -3,7 +3,7 @@ from django.core.exceptions import ValidationError
from .....payment import PaymentError
from .....payment.error_codes import PaymentErrorCode
-from .....payment.utils import is_currency_supported
+from .....payment.gateway import get_payment_gateways, is_currency_supported
from ....channel.utils import validate_channel
from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
@@ -85,7 +85,7 @@ class PaymentCheckBalance(BaseMutation):
@classmethod
def validate_gateway(cls, gateway_id, manager):
- gateways_id = [gateway.id for gateway in manager.list_payment_gateways()]
+ gateways_id = [gateway.id for gateway in get_payment_gateways(manager=manager)]
if gateway_id not in gateways_id:
raise ValidationError(
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
index 66e7ed92bc..c2fda9a496 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
@@ -9,6 +9,7 @@ from .....channel.models import Channel
from .....checkout import models as checkout_models
from .....checkout.utils import activate_payments, cancel_active_payments
from .....core.exceptions import PermissionDenied
+from .....giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from .....payment import TransactionItemIdempotencyUniqueError
from .....payment.interface import PaymentGatewayData
from .....payment.utils import handle_transaction_initialize_session
@@ -95,7 +96,16 @@ class TransactionInitialize(TransactionSessionBase):
error_type_class = common_types.TransactionInitializeError
@classmethod
- def clean_action(cls, info, action: str | None, channel: "Channel"):
+ def clean_action(
+ cls,
+ info,
+ action: str | None,
+ channel: "Channel",
+ payment_gateway: PaymentGatewayData,
+ ) -> str:
+ if payment_gateway.app_identifier == GIFT_CARD_PAYMENT_GATEWAY_ID:
+ return TransactionFlowStrategyEnum.AUTHORIZATION.value
+
if not action:
return channel.default_transaction_flow_strategy
app = get_app_promise(info.context).get()
@@ -104,7 +114,12 @@ class TransactionInitialize(TransactionSessionBase):
return action
@classmethod
- def clean_app_from_payment_gateway(cls, payment_gateway: PaymentGatewayData) -> App:
+ def clean_app_from_payment_gateway(
+ cls, payment_gateway: PaymentGatewayData
+ ) -> App | None:
+ if payment_gateway.app_identifier == GIFT_CARD_PAYMENT_GATEWAY_ID:
+ return None
+
app = App.objects.filter(
identifier=payment_gateway.app_identifier,
removed_at__isnull=True,
@@ -164,7 +179,9 @@ class TransactionInitialize(TransactionSessionBase):
cls.validate_checkout(source_object)
idempotency_key = cls.clean_idempotency_key(idempotency_key)
- action = cls.clean_action(info, action, source_object.channel)
+ action = cls.clean_action(
+ info, action, source_object.channel, payment_gateway_data
+ )
customer_ip_address = clean_customer_ip_address(
info,
customer_ip_address,
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
index 87ae6be1c8..9fcf031f4b 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
@@ -1,4 +1,3 @@
-import uuid
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Optional, cast
@@ -7,9 +6,14 @@ from django.core.exceptions import ValidationError
from .....app.models import App
from .....core.prices import quantize_price
+from .....giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
+from .....giftcard.gateway import (
+ cancel_gift_card_transaction,
+ refund_gift_card_transaction,
+)
from .....order.models import Order
from .....page.models import Page
-from .....payment import PaymentError, TransactionAction, TransactionEventType
+from .....payment import PaymentError, TransactionAction
from .....payment.error_codes import TransactionRequestActionErrorCode
from .....payment.gateway import (
request_cancelation_action,
@@ -31,7 +35,7 @@ from ....site.dataloaders import get_site_promise
from ...enums import TransactionActionEnum
from ...types import TransactionItem
from ...utils import validate_and_resolve_refund_reason_context
-from .utils import get_transaction_item
+from .utils import create_transaction_event_requested, get_transaction_item
if TYPE_CHECKING:
from .....account.models import User
@@ -91,21 +95,34 @@ class TransactionRequestAction(BaseMutation):
reason: str | None = None,
reason_reference: Page | None = None,
):
+ transaction = action_kwargs["transaction"]
+ app_identifier = (
+ GIFT_CARD_PAYMENT_GATEWAY_ID
+ if transaction.app_identifier == GIFT_CARD_PAYMENT_GATEWAY_ID
+ else None
+ )
+
if action == TransactionAction.CANCEL:
- transaction = action_kwargs["transaction"]
action_value = action_value or transaction.authorized_value
action_value = min(action_value, transaction.authorized_value)
request_event = cls.create_transaction_event_requested(
- transaction, action_value, action, user=user, app=app
- )
- request_cancelation_action(
- **action_kwargs,
- cancel_value=action_value,
- request_event=request_event,
- action=action,
+ transaction,
+ action_value,
+ action,
+ user=user,
+ app=app,
+ app_identifier=app_identifier,
)
+ if transaction.app_identifier == GIFT_CARD_PAYMENT_GATEWAY_ID:
+ cancel_gift_card_transaction(transaction, request_event)
+ else:
+ request_cancelation_action(
+ **action_kwargs,
+ cancel_value=action_value,
+ request_event=request_event,
+ action=action,
+ )
elif action == TransactionAction.CHARGE:
- transaction = action_kwargs["transaction"]
action_value = action_value or transaction.authorized_value
action_value = min(action_value, transaction.authorized_value)
request_event = cls.create_transaction_event_requested(
@@ -115,21 +132,26 @@ class TransactionRequestAction(BaseMutation):
**action_kwargs, charge_value=action_value, request_event=request_event
)
elif action == TransactionAction.REFUND:
- transaction = action_kwargs["transaction"]
action_value = action_value or transaction.charged_value
action_value = min(action_value, transaction.charged_value)
request_event = cls.create_transaction_event_requested(
transaction,
action_value,
- TransactionAction.REFUND,
+ action,
user=user,
app=app,
+ app_identifier=app_identifier,
reason=reason,
reason_reference=reason_reference,
)
- request_refund_action(
- **action_kwargs, refund_value=action_value, request_event=request_event
- )
+ if transaction.app_identifier == GIFT_CARD_PAYMENT_GATEWAY_ID:
+ refund_gift_card_transaction(transaction, request_event)
+ else:
+ request_refund_action(
+ **action_kwargs,
+ refund_value=action_value,
+ request_event=request_event,
+ )
@classmethod
def create_transaction_event_requested(
@@ -139,39 +161,19 @@ class TransactionRequestAction(BaseMutation):
action,
user=None,
app=None,
+ app_identifier=None,
reason=None,
reason_reference: Page | None = None,
):
- message: str | None = None
- reason_reference_to_set = None
-
- if action == TransactionAction.CANCEL:
- type = TransactionEventType.CANCEL_REQUEST
- elif action == TransactionAction.CHARGE:
- type = TransactionEventType.CHARGE_REQUEST
- elif action == TransactionAction.REFUND:
- type = TransactionEventType.REFUND_REQUEST
- message = reason or None
- reason_reference_to_set = reason_reference or None
- else:
- raise ValidationError(
- {
- "actionType": ValidationError(
- "Incorrect action.",
- code=TransactionRequestActionErrorCode.INVALID.value,
- )
- }
- )
- return transaction.events.create(
- amount_value=action_value,
- currency=transaction.currency,
- type=type,
+ return create_transaction_event_requested(
+ transaction,
+ action_value,
+ action,
user=user,
app=app,
- app_identifier=app.identifier if app else None,
- idempotency_key=str(uuid.uuid4()),
- message=message,
- reason_reference=reason_reference_to_set,
+ app_identifier=app_identifier,
+ reason=reason,
+ reason_reference=reason_reference,
)
@classmethod
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py b/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
index e518991423..34a77517c2 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
@@ -1,13 +1,14 @@
-import uuid
from typing import TYPE_CHECKING, cast
import graphene
from django.core.exceptions import ValidationError
+from .....giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
+from .....giftcard.gateway import refund_gift_card_transaction
from .....order import OrderGrantedRefundStatus
from .....order import models as order_models
from .....order.utils import calculate_order_granted_refund_status
-from .....payment import PaymentError, TransactionEventType
+from .....payment import PaymentError, TransactionAction
from .....payment import models as payment_models
from .....payment.error_codes import TransactionRequestActionErrorCode
from .....payment.gateway import request_refund_action
@@ -22,7 +23,7 @@ from ....core.types import common as common_types
from ....core.validators import validate_one_of_args_is_in_mutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import TransactionItem
-from .utils import get_transaction_item
+from .utils import create_transaction_event_requested, get_transaction_item
if TYPE_CHECKING:
pass
@@ -171,31 +172,41 @@ class TransactionRequestRefundForGrantedRefund(BaseMutation):
# granted refund.
assigned_granted_refund = granted_refund
- request_event = transaction_item.events.create(
- amount_value=action_value,
- currency=transaction_item.currency,
- type=TransactionEventType.REFUND_REQUEST,
- idempotency_key=str(uuid.uuid4()),
+ app_identifier = (
+ GIFT_CARD_PAYMENT_GATEWAY_ID
+ if transaction_item.app_identifier == GIFT_CARD_PAYMENT_GATEWAY_ID
+ else None
+ )
+ request_event = create_transaction_event_requested(
+ transaction_item,
+ action_value,
+ TransactionAction.REFUND,
+ app_identifier=app_identifier,
related_granted_refund=assigned_granted_refund,
)
- try:
- request_refund_action(
- transaction=transaction_item,
- manager=manager,
- refund_value=action_value,
- request_event=request_event,
- channel_slug=channel_slug,
- user=info.context.user,
- app=app,
- granted_refund=granted_refund,
- )
- except PaymentError as e:
- error_enum = TransactionRequestActionErrorCode
- code = error_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
- raise ValidationError(str(e), code=code) from e
- finally:
+ if transaction_item.app_identifier == GIFT_CARD_PAYMENT_GATEWAY_ID:
+ refund_gift_card_transaction(transaction_item, request_event)
if assigned_granted_refund:
calculate_order_granted_refund_status(assigned_granted_refund)
+ else:
+ try:
+ request_refund_action(
+ transaction=transaction_item,
+ manager=manager,
+ refund_value=action_value,
+ request_event=request_event,
+ channel_slug=channel_slug,
+ user=info.context.user,
+ app=app,
+ granted_refund=granted_refund,
+ )
+ except PaymentError as e:
+ error_enum = TransactionRequestActionErrorCode
+ code = error_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
+ raise ValidationError(str(e), code=code) from e
+ finally:
+ if assigned_granted_refund:
+ calculate_order_granted_refund_status(assigned_granted_refund)
return cls(transaction=transaction_item)
diff --git a/saleor/graphql/payment/mutations/transaction/utils.py b/saleor/graphql/payment/mutations/transaction/utils.py
index 5fae2a209e..63a55f0447 100644
--- a/saleor/graphql/payment/mutations/transaction/utils.py
+++ b/saleor/graphql/payment/mutations/transaction/utils.py
@@ -1,10 +1,17 @@
+import uuid
+
from django.core.exceptions import ValidationError
from django.core.validators import validate_ipv46_address
from .....core.exceptions import PermissionDenied
from .....core.utils import get_client_ip
+from .....page.models import Page
+from .....payment import TransactionAction, TransactionEventType
from .....payment import models as payment_models
-from .....payment.error_codes import TransactionUpdateErrorCode
+from .....payment.error_codes import (
+ TransactionRequestActionErrorCode,
+ TransactionUpdateErrorCode,
+)
from .....permission.enums import PaymentPermissions
from ....app.dataloaders import get_app_promise
from ....core.utils import from_global_id_or_error
@@ -73,3 +80,50 @@ def clean_customer_ip_address(info, customer_ip_address: str | None, error_code:
}
) from e
return customer_ip_address
+
+
+def create_transaction_event_requested(
+ transaction,
+ action_value,
+ action,
+ user=None,
+ app=None,
+ app_identifier=None,
+ reason=None,
+ reason_reference: Page | None = None,
+ related_granted_refund=None,
+ message: str | None = None,
+):
+ reason_reference_to_set = None
+
+ if action == TransactionAction.CANCEL:
+ type = TransactionEventType.CANCEL_REQUEST
+ elif action == TransactionAction.CHARGE:
+ type = TransactionEventType.CHARGE_REQUEST
+ elif action == TransactionAction.REFUND:
+ type = TransactionEventType.REFUND_REQUEST
+ message = reason or None
+ reason_reference_to_set = reason_reference or None
+ else:
+ raise ValidationError(
+ {
+ "actionType": ValidationError(
+ "Incorrect action.",
+ code=TransactionRequestActionErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ app_identifier = app_identifier or (app.identifier if app else None)
+ return transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=type,
+ user=user,
+ app=app,
+ app_identifier=app_identifier,
+ idempotency_key=str(uuid.uuid4()),
+ message=message,
+ reason_reference=reason_reference_to_set,
+ related_granted_refund=related_granted_refund,
+ )
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index c392ca5ba6..8ef7eac96d 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -1,6 +1,7 @@
import datetime
from decimal import Decimal
from unittest import mock
+from uuid import uuid4
import graphene
import pytest
@@ -14,10 +15,16 @@ from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.complete_checkout import create_order_from_checkout
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....core.prices import quantize_price
+from .....checkout.models import Checkout
+from .....core.prices import Money, quantize_price
+from .....giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderStatus
from .....order.models import Order
-from .....payment import TransactionEventType, TransactionItemIdempotencyUniqueError
+from .....payment import (
+ TransactionAction,
+ TransactionEventType,
+ TransactionItemIdempotencyUniqueError,
+)
from .....payment.interface import (
PaymentGatewayData,
TransactionProcessActionData,
@@ -29,6 +36,7 @@ from .....payment.lock_objects import (
get_order_and_transaction_item_locked_for_update,
)
from .....payment.models import Payment, TransactionItem
+from .....plugins.manager import get_plugins_manager
from .....tests import race_condition
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.models import Webhook
@@ -107,7 +115,7 @@ def _assert_fields(
expected_psp_reference,
response_event_type,
app_identifier,
- mocked_initialize,
+ mocked_initialize=None,
request_event_type=TransactionEventType.CHARGE_REQUEST,
action_type=TransactionFlowStrategy.CHARGE,
request_event_include_in_calculations=False,
@@ -117,6 +125,8 @@ def _assert_fields(
authorize_pending_value=Decimal(0),
returned_data=None,
expected_message=None,
+ gift_card=None,
+ available_actions=None,
):
assert not content["data"]["transactionInitialize"]["errors"]
response_data = content["data"]["transactionInitialize"]
@@ -183,22 +193,29 @@ def _assert_fields(
if expected_message is not None:
assert response_event.message == expected_message
- 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,
- ),
- customer_ip_address="127.0.0.1",
- payment_gateway_data=PaymentGatewayData(
- app_identifier=app_identifier, data=None, error=None
- ),
- idempotency_key=request_event.idempotency_key,
+ if mocked_initialize:
+ 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,
+ ),
+ customer_ip_address="127.0.0.1",
+ payment_gateway_data=PaymentGatewayData(
+ app_identifier=app_identifier, data=None, error=None
+ ),
+ idempotency_key=request_event.idempotency_key,
+ )
)
- )
+
+ assert transaction.gift_card == gift_card
+ assert transaction.app_identifier == app_identifier
+
+ available_actions = available_actions if available_actions else []
+ assert transaction.available_actions == available_actions
@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
@@ -3336,3 +3353,564 @@ def test_invalidate_stored_payment_methods_not_invalidated_for_checkout(
# ensure that cache has not been cleared
cache_delete_mock.assert_not_called()
+
+
+ "data", [None, {}, {"some": "value"}, {"code": None}, {"code": ""}]
+)
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_checkout_with_gift_card_payment_gateway_data_and_incorrect_data_format(
+ mocked_uuid4,
+ user_api_client,
+ checkout_with_prices,
+ data,
+):
+ # given
+ checkout = checkout_with_prices
+ mocked_uuid4.return_value = uuid4()
+
+ variables = {
+ "action": None,
+ "amount": 1,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": GIFT_CARD_PAYMENT_GATEWAY_ID, "data": data},
+ }
+
+ # 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=Decimal(1),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ expected_message="Incorrect payment gateway data.",
+ )
+
+
+ "action",
+ [
+ None,
+ TransactionFlowStrategyEnum.AUTHORIZATION.name,
+ TransactionFlowStrategyEnum.CHARGE.name,
+ ],
+)
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_checkout_with_gift_card_payment_gateway(
+ mocked_uuid4,
+ action,
+ user_api_client,
+ checkout_with_prices,
+ gift_card_created_by_staff,
+):
+ # given
+ checkout = checkout_with_prices
+ mocked_uuid4.return_value = uuid4()
+
+ variables = {
+ "action": action,
+ "amount": 1,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": gift_card_created_by_staff.code},
+ },
+ }
+
+ # 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=Decimal(1),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_SUCCESS,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ authorized_value=Decimal(1),
+ gift_card=gift_card_created_by_staff,
+ expected_message=f"Gift card (ending: {gift_card_created_by_staff.display_code}).",
+ available_actions=[TransactionAction.CANCEL],
+ )
+
+
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_checkout_with_gift_card_payment_gateway_gift_card_does_not_exist(
+ mocked_uuid4,
+ user_api_client,
+ checkout_with_prices,
+):
+ # given
+ checkout = checkout_with_prices
+ mocked_uuid4.return_value = uuid4()
+
+ variables = {
+ "action": None,
+ "amount": 1,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": "not-existing"},
+ },
+ }
+
+ # 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=Decimal(1),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ expected_message="Gift card code is not valid.",
+ )
+
+
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_checkout_with_gift_card_payment_gateway_gift_card_has_different_currency(
+ mocked_uuid4,
+ user_api_client,
+ checkout_with_prices,
+ gift_card_created_by_staff,
+):
+ # given
+ checkout = checkout_with_prices
+ mocked_uuid4.return_value = uuid4()
+
+ gift_card_created_by_staff.currency = "CHF"
+ gift_card_created_by_staff.save(update_fields=["currency"])
+
+ variables = {
+ "action": None,
+ "amount": 1,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": gift_card_created_by_staff.code},
+ },
+ }
+
+ # 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=Decimal(1),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ expected_message="Gift card code is not valid.",
+ )
+
+
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_checkout_with_gift_card_payment_gateway_gift_card_is_inactive(
+ mocked_uuid4,
+ user_api_client,
+ checkout_with_prices,
+ gift_card_created_by_staff,
+):
+ # given
+ checkout = checkout_with_prices
+ mocked_uuid4.return_value = uuid4()
+
+ gift_card_created_by_staff.is_active = False
+ gift_card_created_by_staff.save(update_fields=["is_active"])
+
+ variables = {
+ "action": None,
+ "amount": 1,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": gift_card_created_by_staff.code},
+ },
+ }
+
+ # 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=Decimal(1),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ expected_message="Gift card code is not valid.",
+ )
+
+
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_checkout_with_gift_card_payment_gateway_gift_card_is_expired(
+ mocked_uuid4,
+ user_api_client,
+ checkout_with_prices,
+ gift_card_created_by_staff,
+):
+ # given
+ checkout = checkout_with_prices
+ mocked_uuid4.return_value = uuid4()
+
+ gift_card_created_by_staff.expiry_date = timezone.now() - datetime.timedelta(days=3)
+ gift_card_created_by_staff.save(update_fields=["expiry_date"])
+
+ variables = {
+ "action": None,
+ "amount": 1,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": gift_card_created_by_staff.code},
+ },
+ }
+
+ # 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=Decimal(1),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ expected_message="Gift card code is not valid.",
+ )
+
+
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_checkout_with_gift_card_payment_gateway_gift_card_has_insufficient_funds(
+ mocked_uuid4,
+ user_api_client,
+ checkout_with_prices,
+ gift_card_created_by_staff,
+):
+ # given
+ checkout = checkout_with_prices
+ mocked_uuid4.return_value = uuid4()
+
+ gift_card_created_by_staff.current_balance_amount = Decimal(0.1)
+ gift_card_created_by_staff.save(update_fields=["current_balance_amount"])
+
+ variables = {
+ "action": None,
+ "amount": 1,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": gift_card_created_by_staff.code},
+ },
+ }
+
+ # 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=Decimal(1),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ expected_message="Gift card has insufficient amount (0.10) to cover requested amount (1.00).",
+ )
+
+
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_checkout_with_gift_card_payment_gateway_invalidates_previous_authorizations(
+ mocked_uuid4,
+ user_api_client,
+ checkout_with_prices,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+ order,
+):
+ # given
+ checkout = checkout_with_prices
+ mocked_uuid4.return_value = uuid4()
+
+ another_checkout = Checkout.objects.create(
+ currency=checkout.currency,
+ user=checkout.user,
+ channel=checkout.channel,
+ base_total=Money("15", checkout.currency),
+ base_subtotal=Money("10", checkout.currency),
+ )
+ another_checkout_authorize_transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ checkout_id=another_checkout.pk,
+ gift_card=gift_card_created_by_staff,
+ authorized_value=Decimal(15),
+ )
+
+ manager = get_plugins_manager(allow_replica=False)
+ another_checkout_info = fetch_checkout_info(another_checkout, [], manager)
+ fetch_checkout_data(
+ checkout_info=another_checkout_info,
+ manager=manager,
+ lines=[],
+ )
+ assert (
+ another_checkout_info.checkout.authorize_status == CheckoutAuthorizeStatus.FULL
+ )
+
+ assert (
+ another_checkout_authorize_transaction.events.filter(
+ type=TransactionEventType.CANCEL_REQUEST
+ ).count()
+ == 0
+ )
+ assert (
+ another_checkout_authorize_transaction.events.filter(
+ type=TransactionEventType.CANCEL_SUCCESS
+ ).count()
+ == 0
+ )
+
+ order_authorize_transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=gift_card_created_by_staff,
+ authorized_value=Decimal(25),
+ )
+ assert (
+ order_authorize_transaction.events.filter(
+ type=TransactionEventType.CANCEL_REQUEST
+ ).count()
+ == 0
+ )
+ assert (
+ order_authorize_transaction.events.filter(
+ type=TransactionEventType.CANCEL_SUCCESS
+ ).count()
+ == 0
+ )
+
+ variables = {
+ "action": None,
+ "amount": 1,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": gift_card_created_by_staff.code},
+ },
+ }
+
+ # 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=Decimal(1),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_SUCCESS,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ authorized_value=Decimal(1),
+ gift_card=gift_card_created_by_staff,
+ available_actions=[TransactionAction.CANCEL],
+ )
+
+ another_checkout_authorize_transaction.refresh_from_db()
+ assert another_checkout_authorize_transaction.gift_card is None
+ assert (
+ another_checkout_authorize_transaction.events.filter(
+ type=TransactionEventType.CANCEL_REQUEST
+ ).count()
+ == 1
+ )
+ assert (
+ another_checkout_authorize_transaction.events.filter(
+ type=TransactionEventType.CANCEL_SUCCESS,
+ message=f"Gift card (code ending with: {gift_card_created_by_staff.display_code}) has been authorized as payment method in a different checkout or has been authorized in the same checkout again.",
+ ).count()
+ == 1
+ )
+ assert another_checkout_authorize_transaction.authorized_value == Decimal(0)
+ another_checkout.refresh_from_db()
+ assert another_checkout.authorize_status == CheckoutAuthorizeStatus.NONE
+
+ assert order_authorize_transaction.gift_card is not None
+ assert (
+ order_authorize_transaction.events.filter(
+ type=TransactionEventType.CANCEL_REQUEST
+ ).count()
+ == 0
+ )
+ assert (
+ order_authorize_transaction.events.filter(
+ type=TransactionEventType.CANCEL_SUCCESS
+ ).count()
+ == 0
+ )
+
+
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_order_with_gift_card_payment_gateway(
+ mocked_uuid4,
+ user_api_client,
+ order,
+ gift_card_created_by_staff,
+):
+ # given
+ variables = {
+ "action": None,
+ "amount": 1,
+ "id": to_global_id_or_none(order),
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": gift_card_created_by_staff.code},
+ },
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ order.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=order,
+ expected_amount=Decimal(1),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ expected_message=f"Cannot initialize transaction for payment gateway: {GIFT_CARD_PAYMENT_GATEWAY_ID} and object type other than Checkout.",
+ )
+
+
+ ("first_call_amount", "second_call_amount"),
+ [
+ (1, 1),
+ (1, 2),
+ (2, 1),
+ ],
+)
[email protected]("saleor.giftcard.gateway.uuid4")
+def test_for_checkout_with_gift_card_payment_gateway_initialize_transaction_using_the_same_gift_card(
+ mocked_uuid4,
+ first_call_amount,
+ second_call_amount,
+ user_api_client,
+ checkout_with_prices,
+ gift_card_created_by_staff,
+):
+ # given
+ checkout = checkout_with_prices
+ mocked_uuid4.return_value = uuid4()
+
+ variables = {
+ "action": None,
+ "amount": first_call_amount,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": gift_card_created_by_staff.code},
+ },
+ }
+
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+ content = get_graphql_content(response)
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=Decimal(first_call_amount),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_SUCCESS,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ authorized_value=Decimal(first_call_amount),
+ gift_card=gift_card_created_by_staff,
+ expected_message=f"Gift card (ending: {gift_card_created_by_staff.display_code}).",
+ available_actions=[TransactionAction.CANCEL],
+ )
+ assert checkout.payment_transactions.all().count() == 1
+ assert checkout.payment_transactions.first().events.all().count() == 2
+
+ variables["amount"] = second_call_amount
+
+ # 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=Decimal(second_call_amount),
+ expected_psp_reference=str(mocked_uuid4.return_value),
+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,
+ response_event_type=TransactionEventType.AUTHORIZATION_SUCCESS,
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ authorized_value=Decimal(second_call_amount),
+ gift_card=gift_card_created_by_staff,
+ expected_message=f"Gift card (ending: {gift_card_created_by_staff.display_code}).",
+ available_actions=[TransactionAction.CANCEL],
+ )
+
+ assert checkout.payment_transactions.all().count() == 2
+
+ cancelled_transaction = checkout.payment_transactions.first()
+ assert cancelled_transaction.authorized_value == Decimal(0)
+ assert cancelled_transaction.charged_value == Decimal(0)
+ assert cancelled_transaction.events.count() == 4
+ cancelled_transaction.events.get(type=TransactionEventType.AUTHORIZATION_REQUEST)
+ cancelled_transaction.events.get(type=TransactionEventType.AUTHORIZATION_SUCCESS)
+ cancelled_transaction.events.get(type=TransactionEventType.CANCEL_REQUEST)
+ cancelled_transaction.events.get(
+ type=TransactionEventType.CANCEL_SUCCESS,
+ message=f"Gift card (code ending with: {gift_card_created_by_staff.display_code}) has been authorized as payment method in a different checkout or has been authorized in the same checkout again.",
+ )
+ assert cancelled_transaction.available_actions == []
+
+ latest_transaction = checkout.payment_transactions.last()
+ assert latest_transaction.authorized_value == Decimal(second_call_amount)
+ assert latest_transaction.charged_value == Decimal(0)
+ assert latest_transaction.events.count() == 2
+ latest_transaction.events.get(type=TransactionEventType.AUTHORIZATION_REQUEST)
+ latest_transaction.events.get(type=TransactionEventType.AUTHORIZATION_SUCCESS)
+ assert latest_transaction.available_actions == [TransactionAction.CANCEL]
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 d1501f6554..5de942bb93 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -5,11 +5,15 @@ import graphene
import pytest
from .....app.models import App
+from .....checkout import CheckoutAuthorizeStatus
+from .....checkout.payment_utils import update_checkout_payment_statuses
+from .....giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from .....order import OrderEvents
from .....page.models import Page, PageType
from .....payment import TransactionAction, TransactionEventType
from .....payment.interface import TransactionActionData
from .....payment.models import TransactionEvent, TransactionItem
+from .....tests.e2e.utils import assign_permissions
from .....webhook.event_types import WebhookEventSyncType
from ....core.enums import TransactionRequestActionErrorCode
from ....core.utils import to_global_id_or_none
@@ -2030,3 +2034,334 @@ def test_transaction_request_charge_without_reason_when_refund_reasons_enabled(
assert request_event.reason_reference is None
assert mocked_payment_action_request.called
+
+
+ (
+ "amount",
+ "expected_cancel_amount",
+ "expected_authorize_status",
+ "expected_available_actions",
+ ),
+ [
+ (None, Decimal(10), CheckoutAuthorizeStatus.NONE, []),
+ (
+ Decimal(1),
+ Decimal(1),
+ CheckoutAuthorizeStatus.PARTIAL,
+ [TransactionAction.CANCEL],
+ ),
+ (Decimal(10), Decimal(10), CheckoutAuthorizeStatus.NONE, []),
+ (Decimal(11), Decimal(10), CheckoutAuthorizeStatus.NONE, []),
+ ],
+)
+def test_transaction_request_cancelation_for_checkout_gift_card_authorization(
+ amount,
+ expected_cancel_amount,
+ expected_authorize_status,
+ expected_available_actions,
+ checkout_with_prices,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ assign_permissions(staff_api_client, [permission_manage_payments])
+
+ checkout = checkout_with_prices
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ checkout_id=checkout.pk,
+ gift_card=gift_card_created_by_staff,
+ authorized_value=Decimal(10),
+ available_actions=[TransactionAction.CANCEL],
+ )
+ assert transaction.gift_card is not None
+
+ update_checkout_payment_statuses(
+ checkout, checkout.total.gross, checkout_has_lines=True
+ )
+
+ checkout.refresh_from_db()
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.PARTIAL
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.CANCEL.name,
+ "amount": amount,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["transactionRequestAction"]["errors"] == []
+
+ transaction.refresh_from_db()
+ checkout.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(10) - expected_cancel_amount
+ assert transaction.charged_value == Decimal(0)
+ assert transaction.gift_card is not None
+ assert transaction.available_actions == expected_available_actions
+ assert checkout.authorize_status == expected_authorize_status
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=expected_cancel_amount,
+ )
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_SUCCESS,
+ amount_value=expected_cancel_amount,
+ )
+
+
+def test_transaction_request_cancelation_fails_when_cancel_action_is_not_available(
+ checkout_with_prices,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ assign_permissions(staff_api_client, [permission_manage_payments])
+
+ checkout = checkout_with_prices
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ checkout_id=checkout.pk,
+ gift_card=gift_card_created_by_staff,
+ authorized_value=gift_card_created_by_staff.current_balance_amount,
+ available_actions=[],
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.CANCEL.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["transactionRequestAction"]["errors"] == []
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=gift_card_created_by_staff.current_balance_amount,
+ )
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_FAILURE,
+ amount_value=gift_card_created_by_staff.current_balance_amount,
+ )
+
+
+def test_transaction_request_cancelation_for_type_other_than_checkout(
+ order_with_lines,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ assign_permissions(staff_api_client, [permission_manage_payments])
+
+ order = order_with_lines
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=gift_card_created_by_staff,
+ authorized_value=gift_card_created_by_staff.current_balance_amount,
+ available_actions=[TransactionAction.CANCEL],
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.CANCEL.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["transactionRequestAction"]["errors"] == []
+
+ transaction.refresh_from_db()
+
+ assert (
+ transaction.authorized_value
+ == gift_card_created_by_staff.current_balance_amount
+ )
+ assert transaction.charged_value == Decimal(0)
+ assert transaction.gift_card is not None
+ assert transaction.available_actions == [TransactionAction.CANCEL]
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_REQUEST,
+ amount_value=gift_card_created_by_staff.current_balance_amount,
+ )
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CANCEL_FAILURE,
+ amount_value=gift_card_created_by_staff.current_balance_amount,
+ )
+
+
+ ("amount", "expected_refund_amount", "expected_available_actions"),
+ [
+ (None, Decimal(10), []),
+ (Decimal(1), Decimal(1), [TransactionAction.REFUND]),
+ (Decimal(10), Decimal(10), []),
+ (Decimal(11), Decimal(10), []),
+ ],
+)
+def test_transaction_request_refund_for_order_gift_card_charge(
+ amount,
+ expected_refund_amount,
+ expected_available_actions,
+ order_with_lines,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ assign_permissions(staff_api_client, [permission_manage_payments])
+
+ order = order_with_lines
+
+ gift_card_created_by_staff.current_balance_amount = Decimal(0)
+ gift_card_created_by_staff.save(update_fields=["current_balance_amount"])
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=gift_card_created_by_staff,
+ charged_value=Decimal(10),
+ available_actions=[TransactionAction.REFUND],
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "amount": amount,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["transactionRequestAction"]["errors"] == []
+
+ transaction.refresh_from_db()
+ gift_card_created_by_staff.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(0)
+ assert transaction.charged_value == Decimal(10) - expected_refund_amount
+ assert transaction.refunded_value == expected_refund_amount
+ assert transaction.gift_card is not None
+ assert transaction.available_actions == expected_available_actions
+ assert gift_card_created_by_staff.current_balance_amount == expected_refund_amount
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_refund_amount,
+ )
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_SUCCESS,
+ amount_value=expected_refund_amount,
+ )
+
+
+def test_transaction_request_refund_for_order_gift_card_charge_when_gift_card_does_not_exist_anymore(
+ order_with_lines,
+ transaction_item_generator,
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ assign_permissions(staff_api_client, [permission_manage_payments])
+
+ order = order_with_lines
+ amount = Decimal(10)
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=None,
+ charged_value=amount,
+ available_actions=[TransactionAction.REFUND],
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.REFUND.name,
+ "amount": amount,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["transactionRequestAction"]["errors"] == []
+
+ transaction.refresh_from_db()
+
+ assert transaction.charged_value == amount
+ assert transaction.refunded_value == Decimal(0)
+ assert transaction.gift_card is None
+ assert transaction.available_actions == [TransactionAction.REFUND]
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=amount,
+ )
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_FAILURE,
+ amount_value=amount,
+ message="Gift card could not be found.",
+ )
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
index b48c671f3d..1b9c427be0 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_refund_for_granted_refund.py
@@ -4,10 +4,12 @@ from unittest.mock import patch
import graphene
import pytest
+from .....giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from .....order import OrderGrantedRefundStatus
from .....payment import TransactionAction, TransactionEventType
from .....payment.interface import TransactionActionData
from .....payment.models import TransactionEvent
+from .....tests.e2e.utils import assign_permissions
from .....webhook.event_types import WebhookEventSyncType
from ....core.enums import TransactionRequestRefundForGrantedRefundErrorCode
from ....core.utils import to_global_id_or_none
@@ -755,3 +757,290 @@ def test_trigger_refund_possible_based_on_status_of_granted_refund(
type=TransactionEventType.REFUND_REQUEST,
amount_value=refund_amount,
)
+
+
+ ("granted_refund_amount", "expected_refund_amount", "expected_available_actions"),
+ [
+ (Decimal(10), Decimal(10), []),
+ (Decimal(1), Decimal(1), [TransactionAction.REFUND]),
+ ],
+)
+def test_transaction_request_refund_for_granted_refund_for_order_gift_card_charge(
+ granted_refund_amount,
+ expected_refund_amount,
+ expected_available_actions,
+ order_with_lines,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ assign_permissions(staff_api_client, [permission_manage_payments])
+
+ order = order_with_lines
+
+ gift_card_created_by_staff.current_balance_amount = Decimal(0)
+ gift_card_created_by_staff.save(update_fields=["current_balance_amount"])
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=gift_card_created_by_staff,
+ charged_value=Decimal(10),
+ available_actions=[TransactionAction.REFUND],
+ )
+
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=granted_refund_amount,
+ transaction_item=transaction,
+ )
+
+ variables = {
+ "grantedRefundID": to_global_id_or_none(granted_refund),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["transactionRequestRefundForGrantedRefund"]["errors"] == []
+
+ transaction.refresh_from_db()
+ gift_card_created_by_staff.refresh_from_db()
+ granted_refund.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(0)
+ assert transaction.charged_value == Decimal(10) - expected_refund_amount
+ assert transaction.refunded_value == expected_refund_amount
+ assert transaction.gift_card is not None
+ assert transaction.available_actions == expected_available_actions
+ assert gift_card_created_by_staff.current_balance_amount == expected_refund_amount
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_refund_amount,
+ )
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_SUCCESS,
+ amount_value=expected_refund_amount,
+ )
+
+ assert granted_refund.status == OrderGrantedRefundStatus.SUCCESS
+
+
+ ("granted_refund_amount", "expected_refund_amount", "expected_available_actions"),
+ [
+ (Decimal(10), Decimal(10), []),
+ (Decimal(1), Decimal(1), [TransactionAction.REFUND]),
+ ],
+)
+def test_transaction_request_refund_for_granted_refund_without_transaction_for_order_gift_card_charge(
+ granted_refund_amount,
+ expected_refund_amount,
+ expected_available_actions,
+ order_with_lines,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ assign_permissions(staff_api_client, [permission_manage_payments])
+
+ order = order_with_lines
+
+ gift_card_created_by_staff.current_balance_amount = Decimal(0)
+ gift_card_created_by_staff.save(update_fields=["current_balance_amount"])
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=gift_card_created_by_staff,
+ charged_value=Decimal(10),
+ available_actions=[TransactionAction.REFUND],
+ )
+
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=granted_refund_amount,
+ )
+
+ variables = {
+ "grantedRefundID": to_global_id_or_none(granted_refund),
+ "token": transaction.token,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND_BY_TOKEN,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["transactionRequestRefundForGrantedRefund"]["errors"] == []
+
+ transaction.refresh_from_db()
+ gift_card_created_by_staff.refresh_from_db()
+ granted_refund.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(0)
+ assert transaction.charged_value == Decimal(10) - expected_refund_amount
+ assert transaction.refunded_value == expected_refund_amount
+ assert transaction.gift_card is not None
+ assert transaction.available_actions == expected_available_actions
+ assert gift_card_created_by_staff.current_balance_amount == expected_refund_amount
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=expected_refund_amount,
+ )
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_SUCCESS,
+ amount_value=expected_refund_amount,
+ )
+
+ assert granted_refund.status == OrderGrantedRefundStatus.SUCCESS
+
+
+def test_transaction_request_refund_for_granted_refund_for_order_gift_card_charge_refund_amount_greater_than_transaction_charge_amount(
+ order_with_lines,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ assign_permissions(staff_api_client, [permission_manage_payments])
+
+ order = order_with_lines
+
+ gift_card_created_by_staff.current_balance_amount = Decimal(0)
+ gift_card_created_by_staff.save(update_fields=["current_balance_amount"])
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=gift_card_created_by_staff,
+ charged_value=Decimal(10),
+ available_actions=[TransactionAction.REFUND],
+ )
+
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=Decimal(20),
+ transaction_item=transaction,
+ )
+ assert granted_refund.status == OrderGrantedRefundStatus.NONE
+
+ variables = {
+ "grantedRefundID": to_global_id_or_none(granted_refund),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ errors = content["data"]["transactionRequestRefundForGrantedRefund"]["errors"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["code"]
+ == TransactionRequestRefundForGrantedRefundErrorCode.AMOUNT_GREATER_THAN_AVAILABLE.name
+ )
+ assert errors[0]["field"] == "grantedRefundId"
+
+ granted_refund.refresh_from_db()
+ assert granted_refund.status == OrderGrantedRefundStatus.NONE
+
+ transaction.refresh_from_db()
+ gift_card_created_by_staff.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(0)
+ assert transaction.charged_value == Decimal(10)
+ assert transaction.refunded_value == Decimal(0)
+ assert transaction.gift_card is not None
+ assert transaction.available_actions == [TransactionAction.REFUND]
+ assert gift_card_created_by_staff.current_balance_amount == Decimal(0)
+
+
+def test_transaction_request_refund_for_granted_refund_for_order_gift_card_charge_when_gift_card_does_not_exist_anymore(
+ order_with_lines,
+ transaction_item_generator,
+ staff_api_client,
+ permission_manage_payments,
+):
+ # given
+ assign_permissions(staff_api_client, [permission_manage_payments])
+
+ order = order_with_lines
+ amount = Decimal(10)
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=None,
+ charged_value=amount,
+ available_actions=[TransactionAction.REFUND],
+ )
+
+ granted_refund = order_with_lines.granted_refunds.create(
+ amount_value=amount,
+ transaction_item=transaction,
+ )
+
+ variables = {
+ "grantedRefundID": to_global_id_or_none(granted_refund),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_REQUEST_REFUND_FOR_GRANTED_REFUND,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ assert content["data"]["transactionRequestRefundForGrantedRefund"]["errors"] == []
+
+ transaction.refresh_from_db()
+ granted_refund.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(0)
+ assert transaction.charged_value == amount
+ assert transaction.refunded_value == Decimal(0)
+ assert transaction.gift_card is None
+ assert transaction.available_actions == [TransactionAction.REFUND]
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=amount,
+ )
+
+ TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.REFUND_FAILURE,
+ amount_value=amount,
+ message="Gift card could not be found.",
+ )
+
+ assert granted_refund.status == OrderGrantedRefundStatus.FAILURE
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c1866125a7..1ebe131439 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -5349,6 +5349,13 @@ type CheckoutSettings {
Added in Saleor 3.22.
"""
automaticCompletionCutOffDate: DateTime
+
+ """
+ Default to `true`. Determines whether gift cards can be attached to a Checkout via `addPromoCode` mutation. Usage of this mutation with gift cards is deprecated.
+
+ Added in Saleor 3.23.
+ """
+ allowLegacyGiftCardUse: Boolean!
}
"""Represents the channel-specific payment settings."""
@@ -28798,6 +28805,13 @@ input CheckoutSettingsInput @doc(category: "Checkout") {
Added in Saleor 3.22.
"""
automaticCompletion: CheckoutAutoCompleteInput
+
+ """
+ Default to `true`. Determines whether gift cards can be attached to a Checkout via `addPromoCode` mutation. Usage of this mutation with gift cards is deprecated.
+
+ Added in Saleor 3.23.
+ """
+ allowLegacyGiftCardUse: Boolean
}
input CheckoutAutoCompleteInput @doc(category: "Checkout") {
diff --git a/saleor/graphql/shop/tests/queries/test_shop.py b/saleor/graphql/shop/tests/queries/test_shop.py
index d6ee9d99b7..4558a4fc18 100644
--- a/saleor/graphql/shop/tests/queries/test_shop.py
+++ b/saleor/graphql/shop/tests/queries/test_shop.py
@@ -6,6 +6,10 @@ from django_countries import countries
from ..... import __version__
from .....core.tests.test_taxes import app_factory, tax_app_factory # noqa: F401
+from .....payment.gateway import (
+ GIFT_CARD_PAYMENT_GATEWAY_ID,
+ GIFT_CARD_PAYMENT_GATEWAY_NAME,
+)
from .....permission.enums import get_permissions_codename
from .....shipping import PostalCodeRuleInclusionType
from .....shipping.models import ShippingMethod
@@ -592,10 +596,12 @@ def test_query_available_payment_gateways_specified_currency_USD(
assert {gateway["id"] for gateway in data} == {
"mirumee.payments.dummy",
"sampleDummy.active",
+ GIFT_CARD_PAYMENT_GATEWAY_ID,
}
assert {gateway["name"] for gateway in data} == {
"Dummy",
"SampleDummy",
+ GIFT_CARD_PAYMENT_GATEWAY_NAME,
}
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 50d6ab942d..30ac4d49be 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -9,6 +9,7 @@ from ...app.utils import get_active_tax_apps
from ...channel import models as channel_models
from ...core.models import ModelWithMetadata
from ...core.utils import build_absolute_uri, get_domain, is_ssl_enabled
+from ...payment.gateway import get_payment_gateways
from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import AppPermission, SitePermissions, get_permissions
from ...site import models as site_models
@@ -416,7 +417,11 @@ class Shop(graphene.ObjectType):
def resolve_available_payment_gateways(
_, _info, manager, currency: str | None = None, channel: str | None = None
):
- return manager.list_payment_gateways(currency=currency, channel_slug=channel)
+ return get_payment_gateways(
+ manager=manager,
+ currency=currency,
+ channel_slug=channel,
+ )
@staticmethod
@traced_resolver
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index e336248f31..82154f043f 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -465,6 +465,10 @@ def order_confirmed(
if send_confirmation_email:
send_order_confirmed(order, user, app, manager)
+ from ..giftcard.gateway import charge_gift_card_transactions
+
+ charge_gift_card_transactions(order)
+
def handle_fully_paid_order(
manager: "PluginsManager",
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index 4ce297d5c4..0f91277699 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -8,9 +8,16 @@ from ...channel import MarkAsPaidStrategy
from ...core.models import EventDelivery
from ...core.utils.events import call_event_including_protected_events
from ...giftcard import GiftCardEvents
+from ...giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from ...giftcard.models import GiftCard, GiftCardEvent
from ...order.fetch import OrderLineInfo, fetch_order_info
-from ...payment import ChargeStatus, PaymentError, TransactionEventType, TransactionKind
+from ...payment import (
+ ChargeStatus,
+ PaymentError,
+ TransactionAction,
+ TransactionEventType,
+ TransactionKind,
+)
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
from ...product.models import DigitalContent
@@ -3857,3 +3864,181 @@ def test_order_confirmed_triggers_webhooks(
assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
assert wrapped_call_order_event.called
+
+
+def test_order_confirmed_charges_funds_authorized_from_gift_card(
+ order_with_lines,
+ django_capture_on_commit_callbacks,
+ customer_user,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ manager = get_plugins_manager(False)
+
+ gift_card_created_by_staff.current_balance_amount = Decimal(100)
+ gift_card_created_by_staff.save(update_fields=["current_balance_amount"])
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=gift_card_created_by_staff,
+ authorized_value=order.total_gross_amount,
+ available_actions=[TransactionAction.CANCEL],
+ )
+
+ assert transaction.authorized_value == order.total_gross_amount
+ assert transaction.charged_value == Decimal(0)
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ order_confirmed(order, user=customer_user, app=None, manager=manager)
+
+ # then
+ transaction.refresh_from_db()
+ gift_card_created_by_staff.refresh_from_db()
+ order.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(0)
+ assert transaction.charged_value == order.total_gross_amount
+ assert transaction.available_actions == [TransactionAction.REFUND]
+ assert (
+ gift_card_created_by_staff.current_balance_amount
+ == Decimal(100) - order.total_gross_amount
+ )
+
+ transaction.events.get(type=TransactionEventType.CHARGE_REQUEST)
+ charge_success_event = transaction.events.get(
+ type=TransactionEventType.CHARGE_SUCCESS
+ )
+ assert charge_success_event.message == "Gift card (ending: taff)."
+
+ assert order.authorize_status == OrderAuthorizeStatus.FULL
+ assert order.charge_status == OrderChargeStatus.FULL
+ assert order.total_authorized_amount == Decimal(0)
+ assert order.total_charged_amount == order.total_gross_amount
+
+
+def test_order_confirmed_checks_gift_card_funds_amount_when_charging_funds_authorized_from_gift_card(
+ order_with_lines,
+ django_capture_on_commit_callbacks,
+ customer_user,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ manager = get_plugins_manager(False)
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=gift_card_created_by_staff,
+ authorized_value=Decimal(10),
+ available_actions=[TransactionAction.CANCEL],
+ )
+
+ assert transaction.authorized_value == Decimal(10)
+ assert transaction.charged_value == Decimal(0)
+
+ gift_card_created_by_staff.current_balance_amount = Decimal(5)
+ gift_card_created_by_staff.save(update_fields=["current_balance_amount"])
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ order_confirmed(order, user=customer_user, app=None, manager=manager)
+
+ # then
+ transaction.refresh_from_db()
+ gift_card_created_by_staff.refresh_from_db()
+ order.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(10)
+ assert transaction.charged_value == Decimal(0)
+ assert transaction.available_actions == [TransactionAction.CANCEL]
+ assert gift_card_created_by_staff.current_balance_amount == Decimal(5)
+
+ transaction.events.get(type=TransactionEventType.CHARGE_REQUEST)
+ charge_success_event = transaction.events.get(
+ type=TransactionEventType.CHARGE_FAILURE
+ )
+ assert (
+ charge_success_event.message
+ == "Gift card has insufficient amount (5.00) to cover requested amount (10.00)."
+ )
+
+ assert order.authorize_status == OrderAuthorizeStatus.PARTIAL
+ assert order.charge_status == OrderChargeStatus.NONE
+ assert order.total_authorized_amount == Decimal(10)
+ assert order.total_charged_amount == Decimal(0)
+
+
+def test_order_confirmed_does_not_charge_the_same_authorized_funds_more_than_once(
+ order_with_lines,
+ django_capture_on_commit_callbacks,
+ customer_user,
+ gift_card_created_by_staff,
+ transaction_item_generator,
+):
+ # given
+ order = order_with_lines
+ manager = get_plugins_manager(False)
+
+ transaction = transaction_item_generator(
+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ order_id=order.pk,
+ gift_card=gift_card_created_by_staff,
+ authorized_value=Decimal(10),
+ available_actions=[TransactionAction.CANCEL],
+ )
+
+ with django_capture_on_commit_callbacks(execute=True):
+ order_confirmed(order, user=customer_user, app=None, manager=manager)
+
+ transaction.refresh_from_db()
+ gift_card_created_by_staff.refresh_from_db()
+ order.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(0)
+ assert transaction.charged_value == Decimal(10)
+ assert transaction.available_actions == [TransactionAction.REFUND]
+ assert gift_card_created_by_staff.current_balance_amount == Decimal(0)
+
+ assert (
+ transaction.events.filter(type=TransactionEventType.CHARGE_REQUEST).count() == 1
+ )
+ assert (
+ transaction.events.filter(type=TransactionEventType.CHARGE_SUCCESS).count() == 1
+ )
+
+ assert order.authorize_status == OrderAuthorizeStatus.PARTIAL
+ assert order.charge_status == OrderChargeStatus.PARTIAL
+ assert order.total_authorized_amount == Decimal(0)
+ assert order.total_charged_amount == Decimal(10)
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ order_confirmed(order, user=customer_user, app=None, manager=manager)
+
+ # then
+ transaction.refresh_from_db()
+ gift_card_created_by_staff.refresh_from_db()
+ order.refresh_from_db()
+
+ assert transaction.authorized_value == Decimal(0)
+ assert transaction.charged_value == Decimal(10)
+ assert transaction.available_actions == [TransactionAction.REFUND]
+ assert gift_card_created_by_staff.current_balance_amount == Decimal(0)
+
+ assert (
+ transaction.events.filter(type=TransactionEventType.CHARGE_REQUEST).count() == 1
+ )
+ assert (
+ transaction.events.filter(type=TransactionEventType.CHARGE_SUCCESS).count() == 1
+ )
+
+ assert order.authorize_status == OrderAuthorizeStatus.PARTIAL
+ assert order.charge_status == OrderChargeStatus.PARTIAL
+ assert order.total_authorized_amount == Decimal(0)
+ assert order.total_charged_amount == Decimal(10)
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 24f28edf93..a570b6c9aa 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -5,8 +5,16 @@ from typing import TYPE_CHECKING, Optional, cast
from ..account.models import User
from ..app.models import App
+from ..checkout.fetch import (
+ CheckoutInfo,
+ CheckoutLineInfo,
+)
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
+from ..giftcard.const import (
+ GIFT_CARD_PAYMENT_GATEWAY_ID,
+ GIFT_CARD_PAYMENT_GATEWAY_NAME,
+)
from ..order.events import (
event_transaction_cancel_requested,
event_transaction_charge_requested,
@@ -499,7 +507,7 @@ def list_payment_sources(
def list_gateways(
manager: "PluginsManager", channel_slug: str | None = None
) -> list["PaymentGateway"]:
- return manager.list_payment_gateways(channel_slug=channel_slug)
+ return get_payment_gateways(manager=manager, channel_slug=channel_slug)
def _fetch_gateway_response(fn, *args, **kwargs):
@@ -580,3 +588,45 @@ def _get_success_transaction(
is_success=True,
kind=kind,
).last()
+
+
+def get_payment_gateways(
+ manager: "PluginsManager",
+ currency: str | None = None,
+ checkout_info: Optional["CheckoutInfo"] = None,
+ checkout_lines: list["CheckoutLineInfo"] | None = None,
+ channel_slug: str | None = None,
+ active_only: bool = True,
+):
+ """Use PluginsManager to assemble list of payment gateways.
+
+ Additionally, if currency is passed an additional built-in
+ payment gateway dedicated for gift card payments is returned.
+ """
+ gateways = manager.list_payment_gateways(
+ currency=currency,
+ checkout_info=checkout_info,
+ checkout_lines=checkout_lines,
+ channel_slug=channel_slug,
+ active_only=active_only,
+ )
+
+ if currency:
+ gateways.extend(
+ [
+ PaymentGateway(
+ id=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ name=GIFT_CARD_PAYMENT_GATEWAY_NAME,
+ currencies=[currency],
+ config=[],
+ )
+ ]
+ )
+
+ return gateways
+
+
+def is_currency_supported(currency: str, gateway_id: str, manager: "PluginsManager"):
+ """Return true if the given gateway supports given currency."""
+ available_gateways = get_payment_gateways(manager=manager, currency=currency)
+ return any(gateway.id == gateway_id for gateway in available_gateways)
diff --git a/saleor/payment/migrations/0066_transactionitem_gift_card.py b/saleor/payment/migrations/0066_transactionitem_gift_card.py
new file mode 100644
index 0000000000..866182e32b
--- /dev/null
+++ b/saleor/payment/migrations/0066_transactionitem_gift_card.py
@@ -0,0 +1,23 @@
+# Generated by Django 5.2.5 on 2025-11-06 15:07
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("giftcard", "0022_merge_20250527_1210"),
+ ("payment", "0065_transactionevent_reason_reference"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="transactionitem",
+ name="gift_card",
+ field=models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="giftcard.giftcard",
+ ),
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 66de0ffc80..9cdbfcd4f1 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -176,6 +176,12 @@ class TransactionItem(ModelWithMetadata):
)
payment_method_name = models.CharField(max_length=256, blank=True, null=True)
+ gift_card = models.ForeignKey(
+ "giftcard.GiftCard",
+ null=True,
+ on_delete=models.SET_NULL,
+ )
+
class Meta:
ordering = ("pk",)
indexes = [
diff --git a/saleor/payment/tests/fixtures/transaction_item.py b/saleor/payment/tests/fixtures/transaction_item.py
index c31084f9fb..a9d0a08532 100644
--- a/saleor/payment/tests/fixtures/transaction_item.py
+++ b/saleor/payment/tests/fixtures/transaction_item.py
@@ -14,6 +14,7 @@ def transaction_item_generator():
order_id=None,
checkout_id=None,
app=None,
+ app_identifier=None,
user=None,
psp_reference="PSP ref1",
name="Credit card",
@@ -34,6 +35,7 @@ def transaction_item_generator():
cc_exp_year=None,
metadata=None,
currency="USD",
+ gift_card=None,
):
if available_actions is None:
available_actions = []
@@ -48,7 +50,7 @@ def transaction_item_generator():
currency=currency,
order_id=order_id,
checkout_id=checkout_id,
- app_identifier=app.identifier if app else None,
+ app_identifier=app.identifier if app else app_identifier,
app=app,
user=user,
use_old_id=use_old_id,
@@ -61,6 +63,7 @@ def transaction_item_generator():
cc_exp_month=cc_exp_month,
cc_exp_year=cc_exp_year,
metadata=metadata,
+ gift_card=gift_card,
)
create_manual_adjustment_events(
transaction=transaction,
diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.py
index e5bd5b6eb8..dff263f910 100644
--- a/saleor/payment/tests/test_payment.py
+++ b/saleor/payment/tests/test_payment.py
@@ -17,6 +17,7 @@ from .. import (
gateway,
)
from ..error_codes import PaymentErrorCode
+from ..gateway import is_currency_supported
from ..interface import GatewayResponse, PaymentMethodInfo, TransactionData
from ..models import Payment
from ..utils import (
@@ -26,7 +27,6 @@ from ..utils import (
create_payment,
create_payment_information,
create_transaction,
- is_currency_supported,
payment_owned_by_user,
update_payment,
validate_gateway_response,
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index d01cdb618d..1e96743691 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -22,13 +22,17 @@ from ..checkout.actions import (
transaction_amounts_for_checkout_updated_without_price_recalculation,
update_last_transaction_modified_at_for_checkout,
)
-from ..checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ..checkout.fetch import (
+ fetch_checkout_info,
+ fetch_checkout_lines,
+)
from ..checkout.models import Checkout
from ..checkout.payment_utils import update_refundable_for_checkout
from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
from ..core.utils.text import safe_truncate
+from ..giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from ..graphql.core.utils import str_to_enum
from ..order import OrderStatus
from ..order.actions import order_transaction_updated
@@ -708,12 +712,6 @@ def get_payment_token(payment: Payment):
return auth_transaction.token
-def is_currency_supported(currency: str, gateway_id: str, manager: "PluginsManager"):
- """Return true if the given gateway supports given currency."""
- available_gateways = manager.list_payment_gateways(currency=currency)
- return any(gateway.id == gateway_id for gateway in available_gateways)
-
-
def price_from_minor_unit(value: str, currency: str):
"""Convert minor unit (smallest unit of currency) to decimal value.
@@ -1017,6 +1015,7 @@ def _validate_transaction_session_action_data(
success_schema = transaction_schemas.TransactionSessionSuccessSchema
failure_schema = transaction_schemas.TransactionSessionFailureSchema
action_required_schema = transaction_schemas.TransactionSessionActionRequiredSchema
+ cancel_success_schema = transaction_schemas.TransactionSessionCancelSuccessSchema
result_value = response_data.get("result")
if result_value in get_args(success_schema.model_fields["result"].annotation):
@@ -1027,6 +1026,10 @@ def _validate_transaction_session_action_data(
action_required_schema.model_fields["result"].annotation
):
return action_required_schema.model_validate(response_data)
+ if result_value in get_args(
+ cancel_success_schema.model_fields["result"].annotation
+ ):
+ return cancel_success_schema.model_validate(response_data)
possible_values = ", ".join(
[
value.name
@@ -1147,7 +1150,7 @@ def get_already_existing_event(event: TransactionEvent) -> TransactionEvent | No
def deduplicate_event(
- event: TransactionEvent, app: App
+ event: TransactionEvent, app: App | None
) -> tuple[TransactionEvent, ErrorMsg | None]:
"""Deduplicate the TransactionEvent.
@@ -1186,8 +1189,8 @@ def deduplicate_event(
extra={
"transaction_id": event.transaction_id,
"psp_reference": event.psp_reference,
- "app_identifier": app.identifier,
- "app_id": app.pk,
+ "app_identifier": app.identifier if app else None,
+ "app_id": app.pk if app else None,
},
)
return event, error_message
@@ -1195,7 +1198,7 @@ def deduplicate_event(
def _create_event_from_response(
response: TransactionRequestEventResponse,
- app: App,
+ app: App | None,
transaction_id: int,
currency: str,
related_granted_refund_id: int | None = None,
@@ -1415,7 +1418,7 @@ def process_order_or_checkout_with_transaction(
def create_transaction_event_for_transaction_session(
request_event: TransactionEvent,
- app: App,
+ app: App | None,
manager: "PluginsManager",
transaction_webhook_response: dict[str, Any] | None = None,
):
@@ -1549,7 +1552,7 @@ def update_order_granted_status_if_needed(request_event: TransactionEvent):
def create_transaction_event_from_request_and_webhook_response(
request_event: TransactionEvent,
- app: App,
+ app: App | None,
transaction_webhook_response: dict[str, Any] | None = None,
):
transaction_request_response, error_msg = (
@@ -1645,7 +1648,7 @@ def create_transaction_event_from_request_and_webhook_response(
transaction_item, manager, app=app, user=None
)
source_object = transaction_item.checkout or transaction_item.order
- if event and source_object:
+ if event and source_object and app:
invalidate_cache_for_stored_payment_methods_if_needed(
event, source_object, app.identifier
)
@@ -1827,7 +1830,7 @@ def handle_transaction_initialize_session(
amount: Decimal,
action: str,
customer_ip_address: str | None,
- app: App,
+ app: App | None,
manager: PluginsManager,
idempotency_key: str,
):
@@ -1880,7 +1883,17 @@ def handle_transaction_initialize_session(
idempotency_key=idempotency_key,
)
- result = manager.transaction_initialize_session(session_data)
+ if payment_gateway_data.app_identifier == GIFT_CARD_PAYMENT_GATEWAY_ID:
+ from ..giftcard.gateway import (
+ transaction_initialize_session_with_gift_card_payment_method,
+ )
+
+ with transaction.atomic():
+ result = transaction_initialize_session_with_gift_card_payment_method(
+ session_data, source_object
+ )
+ else:
+ result = manager.transaction_initialize_session(session_data)
response_data = result.response if result else None
@@ -1890,9 +1903,13 @@ def handle_transaction_initialize_session(
transaction_webhook_response=response_data,
manager=manager,
)
- invalidate_cache_for_stored_payment_methods_if_needed(
- created_event, source_object, app.identifier
- )
+
+ if payment_gateway_data.app_identifier != GIFT_CARD_PAYMENT_GATEWAY_ID:
+ invalidate_cache_for_stored_payment_methods_if_needed(
+ created_event,
+ source_object,
+ app.identifier, # type: ignore[union-attr]
+ )
data_to_return = response_data.get("data") if response_data else None
return created_event.transaction, created_event, data_to_return
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 75fb50698d..69b29241c5 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -13,8 +13,15 @@ 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 ...giftcard.const import (
+ GIFT_CARD_PAYMENT_GATEWAY_ID,
+ GIFT_CARD_PAYMENT_GATEWAY_NAME,
+)
from ...graphql.discount.utils import convert_migrated_sale_predicate_to_catalogue_info
from ...payment import TokenizedPaymentFlow
+from ...payment.gateway import (
+ get_payment_gateways,
+)
from ...payment.interface import (
ListStoredPaymentMethodsRequestData,
PaymentGateway,
@@ -682,7 +689,7 @@ def test_manager_serve_list_of_payment_gateways(channel_USD):
"saleor.plugins.tests.sample_plugins.InactivePaymentGateway",
]
manager = PluginsManager(plugins=plugins)
- assert manager.list_payment_gateways() == [expected_gateway]
+ assert get_payment_gateways(manager=manager) == [expected_gateway]
def test_manager_serve_list_all_payment_gateways(channel_USD):
@@ -706,7 +713,7 @@ def test_manager_serve_list_all_payment_gateways(channel_USD):
"saleor.plugins.tests.sample_plugins.InactivePaymentGateway",
]
manager = PluginsManager(plugins=plugins)
- assert manager.list_payment_gateways(active_only=False) == expected_gateways
+ assert get_payment_gateways(manager=manager, active_only=False) == expected_gateways
def test_manager_serve_list_all_payment_gateways_specified_currency(channel_USD):
@@ -716,7 +723,13 @@ def test_manager_serve_list_all_payment_gateways_specified_currency(channel_USD)
name=ActiveDummyPaymentGateway.PLUGIN_NAME,
config=ActiveDummyPaymentGateway.CLIENT_CONFIG,
currencies=ActiveDummyPaymentGateway.SUPPORTED_CURRENCIES,
- )
+ ),
+ PaymentGateway(
+ id=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ name=GIFT_CARD_PAYMENT_GATEWAY_NAME,
+ currencies=["EUR"],
+ config=[],
+ ),
]
plugins = [
@@ -726,7 +739,7 @@ def test_manager_serve_list_all_payment_gateways_specified_currency(channel_USD)
]
manager = PluginsManager(plugins=plugins)
assert (
- manager.list_payment_gateways(currency="EUR", active_only=False)
+ get_payment_gateways(manager=manager, currency="EUR", active_only=False)
== expected_gateways
)
@@ -747,6 +760,12 @@ def test_manager_serve_list_all_payment_gateways_specified_currency_two_gateways
config=ActiveDummyPaymentGateway.CLIENT_CONFIG,
currencies=ActiveDummyPaymentGateway.SUPPORTED_CURRENCIES,
),
+ PaymentGateway(
+ id=GIFT_CARD_PAYMENT_GATEWAY_ID,
+ name=GIFT_CARD_PAYMENT_GATEWAY_NAME,
+ currencies=["USD"],
+ config=[],
+ ),
]
plugins = [
@@ -756,7 +775,7 @@ def test_manager_serve_list_all_payment_gateways_specified_currency_two_gateways
]
manager = PluginsManager(plugins=plugins)
assert (
- manager.list_payment_gateways(currency="USD", active_only=False)
+ get_payment_gateways(manager=manager, currency="USD", active_only=False)
== expected_gateways
)
diff --git a/saleor/tests/e2e/checkout/utils/checkout_complete.py b/saleor/tests/e2e/checkout/utils/checkout_complete.py
index b80ba5732f..08035ba53a 100644
--- a/saleor/tests/e2e/checkout/utils/checkout_complete.py
+++ b/saleor/tests/e2e/checkout/utils/checkout_complete.py
@@ -15,6 +15,8 @@ mutation CheckoutComplete($checkoutId: ID!) {
userEmail
status
paymentStatus
+ authorizeStatus
+ chargeStatus
isPaid
isShippingRequired
total {
diff --git a/saleor/tests/e2e/gift_cards/test_gift_cards.py b/saleor/tests/e2e/gift_cards/test_gift_cards.py
new file mode 100644
index 0000000000..c64e2ba8eb
--- /dev/null
+++ b/saleor/tests/e2e/gift_cards/test_gift_cards.py
@@ -0,0 +1,407 @@
+import pytest
+
+from ....graphql.order.enums import OrderChargeStatusEnum
+from ....tests import race_condition
+from ...e2e.utils import assign_permissions
+from ..checkout.utils.checkout_add_promo_code import checkout_add_promo_code
+from ..checkout.utils.checkout_complete import checkout_complete
+from ..checkout.utils.checkout_create import checkout_create
+from ..orders.utils.order_query import order_query
+from ..product.utils.preparing_product import prepare_product
+from ..shop.utils import prepare_shop
+from ..transactions.utils.transaction_initialize import (
+ transaction_initialize_for_gift_card_payment_gateway,
+)
+from .utils.gift_card_create import create_gift_card
+from .utils.gift_card_query import get_gift_card
+
+
+def _prepare_shop(staff_api_client):
+ shop_data, _ = prepare_shop(
+ staff_api_client,
+ channels=[
+ {
+ "shipping_zones": [
+ {
+ "shipping_methods": [{}],
+ },
+ ],
+ "order_settings": {
+ "allowUnpaidOrders": False,
+ "automaticallyConfirmAllNewOrders": True,
+ },
+ "checkout_settings": {
+ "automaticallyCompleteFullyPaidCheckouts": False,
+ },
+ }
+ ],
+ )
+
+ return shop_data
+
+
+def _prepare_product(staff_api_client, shop_data):
+ channel_id = shop_data[0]["id"]
+ warehouse_id = shop_data[0]["warehouse_id"]
+
+ variant_price = 10
+
+ (
+ _,
+ product_variant_id,
+ _,
+ ) = prepare_product(
+ staff_api_client,
+ warehouse_id,
+ channel_id,
+ variant_price,
+ is_shipping_required=False,
+ )
+
+ return product_variant_id, variant_price
+
+
+def _prepare_checkout(api_client, lines, channel_slug):
+ return checkout_create(
+ api_client,
+ lines,
+ channel_slug,
+ )
+
+
+def test_gift_card_added_via_add_promo_code_and_transaction_does_not_use_the_same_funds_twice(
+ api_client,
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_gift_card,
+ permission_manage_orders,
+ shop_permissions,
+):
+ permissions = [
+ permission_manage_product_types_and_attributes,
+ permission_manage_gift_card,
+ permission_manage_orders,
+ *shop_permissions,
+ ]
+
+ assign_permissions(staff_api_client, permissions)
+
+ # Step 1 - create gift card
+ gift_card_initial_balance = 100
+ gift_card_data = create_gift_card(staff_api_client, gift_card_initial_balance)
+
+ # Step 2 - prepare channel and product
+ shop_data = _prepare_shop(staff_api_client)
+ channel_slug = shop_data[0]["slug"]
+ product_variant_id, variant_price = _prepare_product(staff_api_client, shop_data)
+
+ # Step 3 - create checkout
+ checkout_data = _prepare_checkout(
+ api_client,
+ [
+ {
+ "variantId": product_variant_id,
+ "quantity": 1,
+ },
+ ],
+ channel_slug,
+ )
+
+ # Step 4 - add gift card to checkout with addPromoCode
+ checkout_add_promo_code(api_client, checkout_data["id"], gift_card_data["code"])
+
+ # Step 5 - add gift card to checkout via transaction
+ transaction_initialize_for_gift_card_payment_gateway(
+ api_client,
+ checkout_data["id"],
+ gift_card_data["code"],
+ variant_price,
+ )
+
+ # Step 6 - complete checkout
+ order_data = checkout_complete(api_client, checkout_data["id"])
+
+ # Step 7 - check gift card funds
+ gift_card_data = get_gift_card(staff_api_client, gift_card_data["id"])
+
+ # Two times variant price because:
+ # - gift card attached to checkout with checkoutAddPromoCode
+ # - gift card attached to checkout with transaction
+ assert gift_card_data["currentBalance"]["amount"] == gift_card_initial_balance - (
+ 2 * variant_price
+ )
+
+ # Step 8 - check order payment status and gift card transaction
+ order_data = order_query(staff_api_client, order_data["id"])
+ assert order_data["chargeStatus"] == OrderChargeStatusEnum.OVERCHARGED.name
+ assert len(order_data["transactions"]) == 1
+ assert order_data["transactions"][0]["authorizedAmount"]["amount"] == 0
+ assert order_data["transactions"][0]["chargedAmount"]["amount"] == 10
+
+
+def test_gift_card_detach_gift_card_from_checkout_as_gift_card_transactions_are_about_to_get_charged(
+ api_client,
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_gift_card,
+ permission_manage_orders,
+ shop_permissions,
+):
+ permissions = [
+ permission_manage_product_types_and_attributes,
+ permission_manage_gift_card,
+ permission_manage_orders,
+ *shop_permissions,
+ ]
+
+ assign_permissions(staff_api_client, permissions)
+
+ # Step 1 - create gift card
+ gift_card_initial_balance = 100
+ gift_card_data = create_gift_card(staff_api_client, gift_card_initial_balance)
+
+ # Step 2 - prepare channel and product
+ shop_data = _prepare_shop(staff_api_client)
+ channel_slug = shop_data[0]["slug"]
+ product_variant_id, variant_price = _prepare_product(staff_api_client, shop_data)
+
+ # Step 3 - create checkout
+ checkout_data = _prepare_checkout(
+ api_client,
+ [
+ {
+ "variantId": product_variant_id,
+ "quantity": 1,
+ },
+ ],
+ channel_slug,
+ )
+
+ # Step 4 - add gift card to checkout via transaction
+ transaction_initialize_for_gift_card_payment_gateway(
+ api_client,
+ checkout_data["id"],
+ gift_card_data["code"],
+ variant_price,
+ )
+
+ # Step 5 - complete checkout
+ def attach_gift_card_to_another_checkout(*args, **kwargs):
+ another_checkout_data = _prepare_checkout(
+ api_client,
+ [],
+ channel_slug,
+ )
+ transaction_initialize_for_gift_card_payment_gateway(
+ api_client,
+ another_checkout_data["id"],
+ gift_card_data["code"],
+ 1,
+ )
+
+ with race_condition.RunBefore(
+ # At this point gift card will not get detached because when
+ # charge_gift_card_transactions is executed the transaction is no longer
+ # attached to a checkout (but to an order)
+ "saleor.giftcard.gateway.charge_gift_card_transactions",
+ attach_gift_card_to_another_checkout,
+ ):
+ order_data = checkout_complete(api_client, checkout_data["id"])
+
+ # Step 6 - check gift card funds
+ gift_card_data = get_gift_card(staff_api_client, gift_card_data["id"])
+
+ assert (
+ gift_card_data["currentBalance"]["amount"]
+ == gift_card_initial_balance - variant_price
+ )
+
+ # Step 7 - check order payment status and gift card transaction
+ order_data = order_query(staff_api_client, order_data["id"])
+ assert order_data["chargeStatus"] == OrderChargeStatusEnum.FULL.name
+ assert len(order_data["transactions"]) == 1
+ assert order_data["transactions"][0]["authorizedAmount"]["amount"] == 0
+ assert order_data["transactions"][0]["chargedAmount"]["amount"] == variant_price
+
+
+def test_gift_card_detach_gift_card_from_checkout_as_checkout_gets_completed(
+ api_client,
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_gift_card,
+ permission_manage_orders,
+ shop_permissions,
+):
+ permissions = [
+ permission_manage_product_types_and_attributes,
+ permission_manage_gift_card,
+ permission_manage_orders,
+ *shop_permissions,
+ ]
+
+ assign_permissions(staff_api_client, permissions)
+
+ # Step 1 - create gift card
+ gift_card_initial_balance = 100
+ gift_card_data = create_gift_card(staff_api_client, gift_card_initial_balance)
+
+ # Step 2 - prepare channel and product
+ shop_data = _prepare_shop(staff_api_client)
+ channel_slug = shop_data[0]["slug"]
+ product_variant_id, variant_price = _prepare_product(staff_api_client, shop_data)
+
+ # Step 3 - create checkout
+ checkout_data = _prepare_checkout(
+ api_client,
+ [
+ {
+ "variantId": product_variant_id,
+ "quantity": 1,
+ },
+ ],
+ channel_slug,
+ )
+
+ # Step 4 - add gift card to checkout via transaction
+ transaction_initialize_for_gift_card_payment_gateway(
+ api_client,
+ checkout_data["id"],
+ gift_card_data["code"],
+ variant_price,
+ )
+
+ # Step 5 - complete checkout
+ def attach_gift_card_to_another_checkout(*args, **kwargs):
+ another_checkout_data = _prepare_checkout(
+ api_client,
+ [],
+ channel_slug,
+ )
+ transaction_initialize_for_gift_card_payment_gateway(
+ api_client,
+ another_checkout_data["id"],
+ gift_card_data["code"],
+ 1,
+ )
+
+ with race_condition.RunBefore(
+ # Complete checkout logic can get started because checkout's authorization
+ # status is set to full at that time. Just before order gets created and transactions are charged the
+ # gift card is detached from the checkout.
+ "saleor.checkout.complete_checkout.create_order_from_checkout",
+ attach_gift_card_to_another_checkout,
+ ):
+ order_data = checkout_complete(api_client, checkout_data["id"])
+
+ # Step 6 - check gift card funds
+ gift_card_data = get_gift_card(staff_api_client, gift_card_data["id"])
+
+ assert gift_card_data["currentBalance"]["amount"] == gift_card_initial_balance
+
+ # Step 7 - check order payment status and gift card transaction
+ order_data = order_query(staff_api_client, order_data["id"])
+ assert order_data["chargeStatus"] == OrderChargeStatusEnum.NONE.name
+ assert len(order_data["transactions"]) == 1
+ assert order_data["transactions"][0]["authorizedAmount"]["amount"] == 0
+ assert order_data["transactions"][0]["chargedAmount"]["amount"] == 0
+
+
+def test_gift_card_simultaneous_complete_checkout_of_two_checkouts_using_gift_card_differently(
+ api_client,
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_gift_card,
+ permission_manage_orders,
+ shop_permissions,
+):
+ permissions = [
+ permission_manage_product_types_and_attributes,
+ permission_manage_gift_card,
+ permission_manage_orders,
+ *shop_permissions,
+ ]
+
+ assign_permissions(staff_api_client, permissions)
+
+ # Step 1 - create gift card
+ gift_card_initial_balance = 100
+ gift_card_data = create_gift_card(staff_api_client, gift_card_initial_balance)
+
+ # Step 2 - prepare channel and product
+ shop_data = _prepare_shop(staff_api_client)
+ channel_slug = shop_data[0]["slug"]
+ product_variant_id, variant_price = _prepare_product(staff_api_client, shop_data)
+
+ # Step 3 - create checkout
+ checkout_data = _prepare_checkout(
+ api_client,
+ [
+ {
+ "variantId": product_variant_id,
+ "quantity": 1,
+ },
+ ],
+ channel_slug,
+ )
+
+ # Step 4 - add gift card to checkout with addPromoCode
+ checkout_add_promo_code(api_client, checkout_data["id"], gift_card_data["code"])
+
+ # Step 5 - create another checkout
+ another_checkout_data = _prepare_checkout(
+ api_client,
+ [
+ {
+ "variantId": product_variant_id,
+ "quantity": 1,
+ },
+ ],
+ channel_slug,
+ )
+
+ # Step 6 - add gift card to another checkout via transaction
+ transaction_initialize_for_gift_card_payment_gateway(
+ api_client,
+ another_checkout_data["id"],
+ gift_card_data["code"],
+ variant_price,
+ )
+
+ # Step 6 - complete checkout
+ order_data = None
+
+ def do_complete_checkout(*args, **kwargs):
+ nonlocal order_data
+ order_data = checkout_complete(api_client, checkout_data["id"])
+
+ with race_condition.RunBefore(
+ "saleor.giftcard.gateway.charge_gift_card_transactions",
+ do_complete_checkout,
+ ):
+ another_order_data = checkout_complete(api_client, another_checkout_data["id"])
+
+ # Step 6 - check gift card funds
+ gift_card_data = get_gift_card(staff_api_client, gift_card_data["id"])
+
+ assert gift_card_data["currentBalance"]["amount"] == gift_card_initial_balance - (
+ 2 * variant_price
+ )
+
+ # Step 7 - check order payment status and gift card transaction
+ order_data = order_query(staff_api_client, order_data["id"])
+ assert order_data["chargeStatus"] == OrderChargeStatusEnum.FULL.name
+ assert len(order_data["transactions"]) == 0
+
+ another_order_data = order_query(staff_api_client, another_order_data["id"])
+ assert another_order_data["chargeStatus"] == OrderChargeStatusEnum.FULL.name
+ assert len(another_order_data["transactions"]) == 1
+ assert another_order_data["transactions"][0]["authorizedAmount"]["amount"] == 0
+ assert (
+ another_order_data["transactions"][0]["chargedAmount"]["amount"]
+ == variant_price
+ )
diff --git a/saleor/tests/e2e/gift_cards/utils/gift_card_query.py b/saleor/tests/e2e/gift_cards/utils/gift_card_query.py
new file mode 100644
index 0000000000..434af9edbd
--- /dev/null
+++ b/saleor/tests/e2e/gift_cards/utils/gift_card_query.py
@@ -0,0 +1,34 @@
+from ...utils import get_graphql_content
+
+GIFT_CARD_QUERY = """
+query GiftCard($id: ID!) {
+ giftCard(id: $id) {
+ id
+ code
+ initialBalance {
+ amount
+ currency
+ }
+ currentBalance {
+ amount
+ currency
+ }
+ }
+}
+"""
+
+
+def get_gift_card(
+ staff_api_client,
+ gift_card_id,
+):
+ variables = {
+ "id": gift_card_id,
+ }
+
+ response = staff_api_client.post_graphql(
+ GIFT_CARD_QUERY,
+ variables,
+ )
+ content = get_graphql_content(response)
+ return content["data"]["giftCard"]
diff --git a/saleor/tests/e2e/orders/utils/order_query.py b/saleor/tests/e2e/orders/utils/order_query.py
index c9a290d304..e7ed2cf2af 100644
--- a/saleor/tests/e2e/orders/utils/order_query.py
+++ b/saleor/tests/e2e/orders/utils/order_query.py
@@ -11,6 +11,8 @@ query OrderDetails($id: ID!) {
active
}
paymentStatus
+ authorizeStatus
+ chargeStatus
isPaid
payments {
id
@@ -51,6 +53,12 @@ query OrderDetails($id: ID!) {
status
transactions {
id
+ chargedAmount {
+ amount
+ }
+ authorizedAmount {
+ amount
+ }
}
metadata {
key
diff --git a/saleor/tests/e2e/transactions/utils/transaction_initialize.py b/saleor/tests/e2e/transactions/utils/transaction_initialize.py
index 7981734d0f..a0ae7c85a5 100644
--- a/saleor/tests/e2e/transactions/utils/transaction_initialize.py
+++ b/saleor/tests/e2e/transactions/utils/transaction_initialize.py
@@ -1,5 +1,6 @@
from unittest import mock
+from .....giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from .....payment.interface import TransactionSessionResult
from ...utils import get_graphql_content
@@ -110,3 +111,29 @@ def transaction_initialize(
data = content["data"]["transactionInitialize"]
return data
+
+
+def transaction_initialize_for_gift_card_payment_gateway(
+ api_client,
+ id,
+ code,
+ amount,
+ action=None,
+):
+ variables = {
+ "action": action,
+ "amount": amount,
+ "id": id,
+ "paymentGateway": {
+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,
+ "data": {"code": code},
+ },
+ }
+
+ response = api_client.post_graphql(TRANSACTION_INITIALIZE_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ assert not content["data"]["transactionInitialize"]["errors"]
+ data = content["data"]["transactionInitialize"]
+
+ return data
diff --git a/saleor/webhook/response_schemas/transaction.py b/saleor/webhook/response_schemas/transaction.py
index b6e2f255b0..6ef3d29dfe 100644
--- a/saleor/webhook/response_schemas/transaction.py
+++ b/saleor/webhook/response_schemas/transaction.py
@@ -379,6 +379,21 @@ class TransactionSessionFailureSchema(TransactionSessionBaseSchema):
]
+class TransactionSessionCancelSuccessSchema(TransactionSessionBaseSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[TransactionEventTypeEnum.CANCEL_SUCCESS.name,],
+ Field(description="Result of the action"),
+ ]
+ psp_reference: Annotated[
+ DefaultIfNone[str],
+ Field(
+ validation_alias="pspReference",
+ default=None,
+ description="PSP reference received from payment provider.",
+ ),
+ ]
+
+
class TransactionSessionActionRequiredSchema(TransactionSessionBaseSchema):
result: Annotated[ # type: ignore[name-defined]
Literal[