Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add Order.transactionSummaries for customer-facing payment history (#19746)
Lukasz Ostrowski497e0390aea8
diff --git a/docs/adr/0010-order-payment-history-is-a-projection-not-an-opened-transaction.md b/docs/adr/0010-order-payment-history-is-a-projection-not-an-opened-transaction.mdnew file mode 100644index 0000000000..6b9ec704b3--- /dev/null+++ b/docs/adr/0010-order-payment-history-is-a-projection-not-an-opened-transaction.md@@ -0,0 +1,25 @@+# Order payment history is a projection, not an opened `TransactionItem`++**Tags:** payments, graphql, permissions, orders++Customer-facing payment history is a new `Order.transactionSummaries` field returning a+`TransactionSummary` projection of the existing `TransactionItem` rows, rather than a permission+change on `Order.transactions`.++Opening `Order.transactions` would publish the whole type — `externalUrl` (PSP back-office deep+link), `events` (internal ledger, staff identities, idempotency keys), `createdBy`, `name`,+`message` — and its `id`, which is the transaction `token`, a capability accepted by the+unauthenticated `transactionInitialize`/`transactionProcess` mutations. Allowlisting fields on the+existing type is not an option either: `PermissionsField` raises, and `[TransactionItem!]!` with+non-null fields means one denied field nulls the entire order. The projection is an allowlist, so+fields added to `TransactionItem` later cannot leak through it.++The field is meant to be queried by a storefront (account page, order summary) to show the money+that moved to and from the customer. That is why transactions with all amounts at zero are+filtered out: they are abandoned payment attempts and carry no information for the customer.++Card data is stripped for the same reason. `paymentMethodDetails` reuses the shared+`PaymentMethodDetails` types, but the resolver blanks `firstDigits`, `lastDigits`, `expMonth` and+`expYear` on a copy of the transaction, so a public caller sees the payment method and the brand+and nothing that identifies the instrument. Staff read the full card data through+`Order.transactions` as before.diff --git a/saleor/graphql/order/tests/queries/test_order_transaction_summaries.py b/saleor/graphql/order/tests/queries/test_order_transaction_summaries.pynew file mode 100644index 0000000000..46047fc4f2--- /dev/null+++ b/saleor/graphql/order/tests/queries/test_order_transaction_summaries.py@@ -0,0 +1,243 @@+from decimal import Decimal++import graphene+import pytest++from .....payment import PaymentMethodType, TransactionEventType+from .....payment.transaction_item_calculations import (+ recalculate_transaction_amounts,+)+from ....tests.utils import get_graphql_content, get_graphql_content_from_response++ORDER_TRANSACTION_SUMMARIES_QUERY = """+query Order($id: ID!) {+ order(id: $id) {+ transactionSummaries {+ createdAt+ authorizedAmount { amount currency }+ authorizePendingAmount { amount currency }+ chargedAmount { amount currency }+ chargePendingAmount { amount currency }+ refundedAmount { amount currency }+ canceledAmount { amount currency }+ paymentMethodDetails {+ name+ ... on CardPaymentMethodDetails {+ brand+ firstDigits+ lastDigits+ expMonth+ expYear+ }+ }+ }+ }+}+"""++ORDER_TRANSACTION_SUMMARIES_GIFT_CARD_QUERY = """+query Order($id: ID!) {+ order(id: $id) {+ transactionSummaries {+ paymentMethodDetails {+ name+ ... on GiftCardPaymentMethodDetails {+ brand+ lastChars+ isSaleorGiftcard+ }+ }+ }+ }+}+"""+++ ("api_client_fixture", "grant_manage_orders"),+ [+ ("api_client", False),+ ("user_api_client", False),+ ("staff_api_client", False),+ ("staff_api_client", True),+ ],+)+def test_available_to_any_requester_that_can_resolve_the_order(+ api_client_fixture,+ grant_manage_orders,+ request,+ order,+ transaction_item_generator,+ permission_manage_orders,+):+ # given+ charged_value = Decimal("13.50")+ transaction = transaction_item_generator(+ order_id=order.pk, charged_value=charged_value+ )+ api_client = request.getfixturevalue(api_client_fixture)+ if grant_manage_orders:+ api_client.user.user_permissions.add(permission_manage_orders)+ variables = {"id": graphene.Node.to_global_id("Order", order.pk)}++ # when+ response = api_client.post_graphql(ORDER_TRANSACTION_SUMMARIES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ summaries = content["data"]["order"]["transactionSummaries"]+ assert len(summaries) == 1+ assert summaries[0]["chargedAmount"] == {+ "amount": float(transaction.amount_charged.amount),+ "currency": transaction.currency,+ }+ assert summaries[0]["authorizedAmount"]["amount"] == 0.0+ assert summaries[0]["paymentMethodDetails"] is None+++def test_card_digits_and_expiration_date_are_stripped(+ api_client, order, transaction_item_generator+):+ # given+ payment_method_name = "Credit card"+ brand = "visa"+ transaction = transaction_item_generator(+ order_id=order.pk,+ charged_value=Decimal("10.00"),+ payment_method_type=PaymentMethodType.CARD,+ payment_method_name=payment_method_name,+ cc_brand=brand,+ cc_first_digits="4111",+ cc_last_digits="1111",+ cc_exp_month=12,+ cc_exp_year=2035,+ )+ variables = {"id": graphene.Node.to_global_id("Order", order.pk)}++ # when+ response = api_client.post_graphql(ORDER_TRANSACTION_SUMMARIES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ summaries = content["data"]["order"]["transactionSummaries"]+ assert len(summaries) == 1+ assert summaries[0]["paymentMethodDetails"] == {+ "name": payment_method_name,+ "brand": brand,+ "firstDigits": None,+ "lastDigits": None,+ "expMonth": None,+ "expYear": None,+ }+ # the stripping happens on a copy, the stored card data is untouched+ transaction.refresh_from_db()+ assert transaction.cc_last_digits == "1111"+++def test_gift_card_details_are_returned(api_client, order, transaction_item_generator):+ # given+ payment_method_name = "Gift card"+ brand = "Saleor"+ last_chars = "a1b2"+ transaction_item_generator(+ order_id=order.pk,+ charged_value=Decimal("10.00"),+ payment_method_type=PaymentMethodType.GIFT_CARD,+ payment_method_name=payment_method_name,+ gift_card_brand=brand,+ gift_card_last_chars=last_chars,+ )+ variables = {"id": graphene.Node.to_global_id("Order", order.pk)}++ # when+ response = api_client.post_graphql(+ ORDER_TRANSACTION_SUMMARIES_GIFT_CARD_QUERY, variables+ )++ # then+ content = get_graphql_content(response)+ summaries = content["data"]["order"]["transactionSummaries"]+ assert len(summaries) == 1+ assert summaries[0]["paymentMethodDetails"] == {+ "name": payment_method_name,+ "brand": brand,+ "lastChars": last_chars,+ "isSaleorGiftcard": False,+ }+++def test_transaction_without_any_money_movement_is_filtered_out(+ api_client, order, transaction_item_generator+):+ # given+ charged_value = Decimal("21.00")+ funded_transaction = transaction_item_generator(+ order_id=order.pk, charged_value=charged_value+ )+ abandoned_transaction = transaction_item_generator(order_id=order.pk)+ assert abandoned_transaction.has_money_movement() is False+ variables = {"id": graphene.Node.to_global_id("Order", order.pk)}++ # when+ response = api_client.post_graphql(ORDER_TRANSACTION_SUMMARIES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ summaries = content["data"]["order"]["transactionSummaries"]+ assert len(summaries) == 1+ assert summaries[0]["chargedAmount"]["amount"] == float(+ funded_transaction.amount_charged.amount+ )+++def test_fully_refunded_transaction_is_returned(+ api_client, order, transaction_item_generator, transaction_events_generator+):+ # given+ amount = Decimal("30.00")+ transaction = transaction_item_generator(order_id=order.pk, charged_value=amount)+ transaction_events_generator(+ psp_references=["refund-ref"],+ types=[TransactionEventType.REFUND_SUCCESS],+ amounts=[amount],+ transaction=transaction,+ )+ recalculate_transaction_amounts(transaction)+ assert transaction.charged_value == Decimal(0)+ variables = {"id": graphene.Node.to_global_id("Order", order.pk)}++ # when+ response = api_client.post_graphql(ORDER_TRANSACTION_SUMMARIES_QUERY, variables)++ # then+ content = get_graphql_content(response)+ summaries = content["data"]["order"]["transactionSummaries"]+ assert len(summaries) == 1+ assert summaries[0]["chargedAmount"]["amount"] == 0.0+ assert summaries[0]["refundedAmount"]["amount"] == float(amount)+++ "field", ["id", "token", "pspReference", "events { id }", "actions", "externalUrl"]+)+def test_internal_fields_are_not_exposed(field, api_client, order):+ # given+ query = f"""+ query Order($id: ID!) {{+ order(id: $id) {{+ transactionSummaries {{ {field} }}+ }}+ }}+ """+ variables = {"id": graphene.Node.to_global_id("Order", order.pk)}++ # when+ response = api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content_from_response(response)+ assert len(content["errors"]) == 1+ field_name = field.split(" ")[0]+ assert content["errors"][0]["message"] == (+ f'Cannot query field "{field_name}" on type "TransactionSummary".'+ )diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 45496e04a8..a017fba109 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -126,6 +126,7 @@ from ..payment.types import (PaymentChargeStatusEnum,TransactionEvent,TransactionItem,+ TransactionSummary,)from ..product.dataloaders import (ImagesByProductIdLoader,@@ -1723,6 +1724,17 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde),required=True,)+ transaction_summaries = NonNullList(+ TransactionSummary,+ description=(+ "Payment history of the order, with one entry per payment transaction "+ "that moved any money. Unlike `transactions`, it requires no permission "+ "and exposes only the payment method and the amounts, so it can be used "+ "to display payment details to the customer without exposing internal "+ "information." + ADDED_IN_323+ ),+ required=True,+ )payments = NonNullList(Payment,description="List of payments for the order.",@@ -2569,6 +2581,22 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Ordedef resolve_transactions(root: SyncWebhookControlContext[models.Order], info):return TransactionItemsByOrderIDLoader(info.context).load(root.node.id)+ @staticmethod+ def resolve_transaction_summaries(+ root: SyncWebhookControlContext[models.Order], info+ ):+ return (+ TransactionItemsByOrderIDLoader(info.context)+ .load(root.node.id)+ .then(+ lambda transactions: [+ transaction+ for transaction in transactions+ if transaction.has_money_movement()+ ]+ )+ )+@staticmethoddef resolve_status_display(root: SyncWebhookControlContext[models.Order], _info):return root.node.get_status_display()diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.pyindex 0ab25d30f7..93d10a66e8 100644--- a/saleor/graphql/payment/types.py+++ b/saleor/graphql/payment/types.py@@ -1,3 +1,4 @@+from copy import copyfrom typing import Anyfrom uuid import UUID@@ -587,6 +588,95 @@ class GiftCardPaymentMethodDetails(BaseObjectType):return bool(root.gift_card_id)+class TransactionSummary(BaseObjectType):+ created_at = DateTime(+ required=True,+ description="Date and time at which payment transaction was created.",+ )+ payment_method_details = graphene.Field(+ PaymentMethodDetails,+ description=(+ "The payment method used for this transaction. As this field is public, "+ "card number digits and expiration date are stripped: `firstDigits`, "+ "`lastDigits`, `expMonth` and `expYear` of "+ "`CardPaymentMethodDetails` are always `null` here. Read them through "+ "`Order.transactions` instead, which requires MANAGE_ORDERS or "+ "HANDLE_PAYMENTS."+ ),+ )+ authorized_amount = graphene.Field(+ Money, required=True, description="Total amount authorized for this payment."+ )+ authorize_pending_amount = graphene.Field(+ Money,+ required=True,+ description=(+ "Total amount of ongoing authorization requests for the transaction."+ ),+ )+ charged_amount = graphene.Field(+ Money, required=True, description="Total amount charged for this payment."+ )+ charge_pending_amount = graphene.Field(+ Money,+ required=True,+ description="Total amount of ongoing charge requests for the transaction.",+ )+ refunded_amount = graphene.Field(+ Money, required=True, description="Total amount refunded for this payment."+ )+ canceled_amount = graphene.Field(+ Money, required=True, description="Total amount canceled for this payment."+ )++ class Meta:+ description = (+ "Customer-facing summary of a single payment transaction. Exposes the "+ "payment method and the amounts, without the identifiers, events and "+ "actions available on `TransactionItem`." + ADDED_IN_323+ )+ doc_category = DOC_CATEGORY_PAYMENTS++ @staticmethod+ def resolve_payment_method_details(root: models.TransactionItem, _info):+ if not root.payment_method_type:+ return None+ # The shared `CardPaymentMethodDetails` resolvers read the card data+ # straight off the transaction, so strip it from a copy - this field is+ # public and the digits and expiration date must not leak. The copy is+ # never saved.+ public_transaction = copy(root)+ public_transaction.cc_first_digits = None+ public_transaction.cc_last_digits = None+ public_transaction.cc_exp_month = None+ public_transaction.cc_exp_year = None+ return public_transaction++ @staticmethod+ def resolve_authorized_amount(root: models.TransactionItem, _info):+ return root.amount_authorized++ @staticmethod+ def resolve_authorize_pending_amount(root: models.TransactionItem, _info):+ return root.amount_authorize_pending++ @staticmethod+ def resolve_charged_amount(root: models.TransactionItem, _info):+ return root.amount_charged++ @staticmethod+ def resolve_charge_pending_amount(root: models.TransactionItem, _info):+ return root.amount_charge_pending++ @staticmethod+ def resolve_refunded_amount(root: models.TransactionItem, _info):+ return root.amount_refunded++ @staticmethod+ def resolve_canceled_amount(root: models.TransactionItem, _info):+ return root.amount_canceled++class TransactionItem(ModelObjectType[models.TransactionItem]):token = graphene.Field(UUIDScalar, description="The transaction token.", required=Truediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 3a8eb04182..0ba73ee486 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -11896,6 +11896,13 @@ type Order implements Node & ObjectWithMetadata @doc(category: "Orders") {"""transactions: [TransactionItem!]!+ """+ Payment history of the order, with one entry per payment transaction that moved any money. Unlike `transactions`, it requires no permission and exposes only the payment method and the amounts, so it can be used to display payment details to the customer without exposing internal information.++ Added in Saleor 3.23.+ """+ transactionSummaries: [TransactionSummary!]!+"""List of payments for the order."""payments: [Payment!]! @deprecated(reason: "The legacy Payments API is deprecated and will be removed. Use the Transactions API instead.")@@ -12812,6 +12819,49 @@ enum OrderChargeStatusEnum @doc(category: "Orders") {OVERCHARGED}+"""+Customer-facing summary of a single payment transaction. Exposes the payment method and the amounts, without the identifiers, events and actions available on `TransactionItem`.++Added in Saleor 3.23.+"""+type TransactionSummary @doc(category: "Payments") {+ """Date and time at which payment transaction was created."""+ createdAt: DateTime!++ """+ The payment method used for this transaction. As this field is public, card number digits and expiration date are stripped: `firstDigits`, `lastDigits`, `expMonth` and `expYear` of `CardPaymentMethodDetails` are always `null` here. Read them through `Order.transactions` instead, which requires MANAGE_ORDERS or HANDLE_PAYMENTS.+ """+ paymentMethodDetails: PaymentMethodDetails++ """Total amount authorized for this payment."""+ authorizedAmount: Money!++ """Total amount of ongoing authorization requests for the transaction."""+ authorizePendingAmount: Money!++ """Total amount charged for this payment."""+ chargedAmount: Money!++ """Total amount of ongoing charge requests for the transaction."""+ chargePendingAmount: Money!++ """Total amount refunded for this payment."""+ refundedAmount: Money!++ """Total amount canceled for this payment."""+ canceledAmount: Money!+}++"""+Represents a payment method used for a transaction.++Added in Saleor 3.22.+"""+interface PaymentMethodDetails {+ """Name of the payment method."""+ name: String!+}+"""Represents a payment of a given type.@@ -13454,16 +13504,6 @@ enum TransactionEventTypeEnum @doc(category: "Payments") {union UserOrApp = User | App-"""-Represents a payment method used for a transaction.--Added in Saleor 3.22.-"""-interface PaymentMethodDetails {- """Name of the payment method."""- name: String!-}-"""Determine a current authorize status for checkout.diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex ac7f0a1332..bdccae6110 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -184,6 +184,24 @@ class TransactionItem(ModelWithMetadata):on_delete=models.SET_NULL,)+ def has_money_movement(self) -> bool:+ """Return True if any money was moved by this transaction.++ A transaction with all amounts at zero is an abandoned payment attempt.+ """+ return any(+ (+ self.authorized_value,+ self.authorize_pending_value,+ self.charged_value,+ self.charge_pending_value,+ self.refunded_value,+ self.refund_pending_value,+ self.canceled_value,+ self.cancel_pending_value,+ )+ )+class Meta:ordering = ("pk",)indexes = [diff --git a/saleor/payment/tests/fixtures/transaction_item.py b/saleor/payment/tests/fixtures/transaction_item.pyindex a9d0a08532..be2a0ff9fa 100644--- a/saleor/payment/tests/fixtures/transaction_item.py+++ b/saleor/payment/tests/fixtures/transaction_item.py@@ -36,6 +36,8 @@ def transaction_item_generator():metadata=None,currency="USD",gift_card=None,+ gift_card_brand=None,+ gift_card_last_chars=None,):if available_actions is None:available_actions = []@@ -64,6 +66,8 @@ def transaction_item_generator():cc_exp_year=cc_exp_year,metadata=metadata,gift_card=gift_card,+ gift_card_brand=gift_card_brand,+ gift_card_last_chars=gift_card_last_chars,)create_manual_adjustment_events(transaction=transaction,