Skip to content

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

add Payment and Transaction GraphQL types

Pacu240f9cc82986e
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index e65d97c21f..4e24dbca15 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -4,6 +4,7 @@ import random
import unicodedata
from datetime import date
from decimal import Decimal
+from unittest.mock import patch
from django.conf import settings
from django.contrib.sites.models import Site
@@ -377,37 +378,10 @@ def create_fake_user():
user.save()
return user
-
-def create_transactions(payment):
- # FIXME Add tests for this function
- payment.transactions.create(
- transaction_type=TransactionType.AUTH,
- is_success=True, amount=payment.total, gateway_response={})
- if payment.charge_status == ChargeStatus.NOT_CHARGED:
- if random.randint(0, 1):
- payment.transactions.create(
- transaction_type=TransactionType.VOID,
- is_success=True, amount=payment.total,
- gateway_response={})
- return
- payment.transactions.create(
- transaction_type=TransactionType.CAPTURE,
- is_success=True, amount=payment.total, gateway_response={})
- if payment.charge_status == ChargeStatus.FULLY_REFUNDED:
- payment.transactions.create(
- transaction_type=TransactionType.REFUND,
- is_success=True, amount=payment.total,
- gateway_response={})
- return payment
-
-
-def create_payment(order):
- # FIXME Add tests for this function
- status = random.choice(
- [
- ChargeStatus.FULLY_REFUNDED,
- ChargeStatus.CHARGED,
- ChargeStatus.NOT_CHARGED])
+# We don't want to spam the console with payment confirmations sent to
+# non-existing fake customers.
+@patch('saleor.order.emails.send_payment_confirmation.delay')
+def create_payment(mock_email_confirmation, order):
payment = Payment.objects.create(
gateway=settings.DUMMY,
customer_ip_address=fake.ipv4(),
@@ -506,9 +480,8 @@ def create_fake_order(discounts, taxes):
order.weight = weight
order.save()
+ create_payment(order=order)
create_fulfillments(order)
-
- create_payment(order)
return order
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 754d45c60c..2771437fc0 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -4,7 +4,7 @@ import graphene
from graphene.types import InputObjectType
from graphql_jwt.decorators import permission_required
-from ....account.models import Address, User
+from ....account.models import User
from ....core.exceptions import InsufficientStock
from ....core.utils.taxes import ZERO_TAXED_MONEY
from ....order import OrderEvents, OrderStatus, models
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index bf8788acb9..ea2450d21b 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -1,8 +1,11 @@
import graphene
+from django_countries.fields import Country
from graphene import relay
from ...payment import GATEWAYS_ENUM, ChargeStatus, models
-from ..core.types.common import CountableDjangoObjectType
+from ..account.types import Address
+from ..core.types.common import CountableDjangoObjectType, CountryDisplay
+from ..core.types.money import Money
from ..core.utils import str_to_enum
PaymentGatewayEnum = graphene.Enum.from_enum(GATEWAYS_ENUM)
@@ -12,6 +15,7 @@ PaymentChargeStatusEnum = graphene.Enum(
class OrderAction(graphene.Enum):
+ # FIXME could use a better name
CAPTURE = 'CAPTURE'
MARK_AS_PAID = 'MARK_AS_PAID'
REFUND = 'REFUND'
@@ -29,6 +33,22 @@ class OrderAction(graphene.Enum):
return 'Represents a void action.'
+class Transaction(CountableDjangoObjectType):
+ amount = graphene.Field(
+ Money, description='Total amount of the transaction.')
+
+ class Meta:
+ description = 'An object representing a single payment.'
+ interfaces = [relay.Node]
+ model = models.Transaction
+ filter_fields = ['id', 'charge_status', 'is_success']
+ exclude_fields = ['currency']
+
+ @staticmethod
+ def resolve_amount(self, info):
+ return self.get_amount()
+
+
class Payment(CountableDjangoObjectType):
# FIXME gateway_response field should be resolved into query-readable format
# if we want to use it on the frontend
@@ -38,12 +58,26 @@ class Payment(CountableDjangoObjectType):
actions = graphene.List(
OrderAction, description='''List of actions that can be performed in
the current state of a payment.''', required=True)
+ total = graphene.Field(
+ Money, description='Total amount of the payment.')
+ captured_amount = graphene.Field(
+ Money, description='Total amount captured for this payment.')
+ billing_address = graphene.Field(
+ Address, description='Customer billing address.')
+ transactions = graphene.List(
+ Transaction,
+ description='List of all transactions within this payment.')
class Meta:
description = 'Represents a payment of a given type.'
interfaces = [relay.Node]
model = models.Payment
filter_fields = ['id']
+ exclude_fields = [
+ 'billing_first_name', 'billing_last_name', 'billing_company_name',
+ 'billing_address_1', 'billing_address_2', 'billing_city',
+ 'billing_postal_code', 'billing_country_code',
+ 'billing_country_area', 'currency', 'billing_city_area']
def resolve_actions(self, info):
actions = []
@@ -55,10 +89,24 @@ class Payment(CountableDjangoObjectType):
actions.append(OrderAction.VOID)
return actions
+ def resolve_total(self, info):
+ return self.get_total()
-class Transaction(CountableDjangoObjectType):
- class Meta:
- description = 'An object representing a single payment.'
- interfaces = [relay.Node]
- model = models.Transaction
- filter_fields = ['id']
+ def resolve_captured_amount(self, info):
+ return self.get_captured_amount()
+
+ def resolve_billing_address(self, info):
+ return Address(
+ first_name=self.billing_first_name,
+ last_name=self.billing_last_name,
+ company_name=self.billing_company_name,
+ street_address_1=self.billing_address_1,
+ street_address_2=self.billing_address_2,
+ city=self.billing_city,
+ city_area=self.billing_city_area,
+ postal_code=self.billing_postal_code,
+ country=Country(self.billing_country_code),
+ country_area=self.billing_country_area)
+
+ def resolve_transactions(self, info):
+ return self.transactions.all()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a6140115a0..80a474ca6b 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1218,26 +1218,17 @@ type Payment implements Node {
created: DateTime!
modified: DateTime!
chargeStatus: PaymentChargeStatusEnum!
- billingFirstName: String!
- billingLastName: String!
- billingCompanyName: String!
- billingAddress1: String!
- billingAddress2: String!
- billingCity: String!
- billingPostalCode: String!
- billingCountryCode: String!
- billingCountryArea: String!
billingEmail: String!
customerIpAddress: String
extraData: String!
token: String!
- currency: String!
- total: Float!
- capturedAmount: Float!
+ total: Money
+ capturedAmount: Money
checkout: Checkout
order: Order
- transactions(before: String, after: String, first: Int, last: Int, id: ID): TransactionCountableConnection
+ transactions: [Transaction]
actions: [OrderAction]!
+ billingAddress: Address
}
type PaymentCapture {
@@ -1901,22 +1892,10 @@ type Transaction implements Node {
token: String!
kind: TransactionKind!
isSuccess: Boolean!
- currency: String!
- amount: Float!
+ amount: Money
gatewayResponse: JSONString!
}
-type TransactionCountableConnection {
- pageInfo: PageInfo!
- edges: [TransactionCountableEdge!]!
- totalCount: Int
-}
-
-type TransactionCountableEdge {
- node: Transaction!
- cursor: String!
-}
-
enum TransactionKind {
AUTH
CAPTURE
diff --git a/saleor/payment/migrations/0001_initial.py b/saleor/payment/migrations/0001_initial.py
index cfd7507572..7e56bf1cd9 100644
--- a/saleor/payment/migrations/0001_initial.py
+++ b/saleor/payment/migrations/0001_initial.py
@@ -33,6 +33,7 @@ class Migration(migrations.Migration):
('billing_address_1', models.CharField(blank=True, max_length=256)),
('billing_address_2', models.CharField(blank=True, max_length=256)),
('billing_city', models.CharField(blank=True, max_length=256)),
+ ('billing_city_area', models.CharField(blank=True, max_length=128)),
('billing_postal_code', models.CharField(blank=True, max_length=256)),
('billing_country_code', models.CharField(blank=True, max_length=2)),
('billing_country_area', models.CharField(blank=True, max_length=256)),
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index a068274019..a38f1211c6 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -44,6 +44,7 @@ class Payment(models.Model):
billing_address_1 = models.CharField(max_length=256, blank=True)
billing_address_2 = models.CharField(max_length=256, blank=True)
billing_city = models.CharField(max_length=256, blank=True)
+ billing_city_area = models.CharField(max_length=128, blank=True)
billing_postal_code = models.CharField(max_length=256, blank=True)
billing_country_code = models.CharField(max_length=2, blank=True)
billing_country_area = models.CharField(max_length=256, blank=True)
@@ -74,9 +75,6 @@ class Payment(models.Model):
return 'Payment(gateway=%s, is_active=%s, created=%s, charge_status=%s)' % (
self.gateway, self.is_active, self.created, self.charge_status)
- def __iter__(self):
- return iter(self.transactions.all())
-
def get_total(self):
return Money(self.total, self.currency or settings.DEFAULT_CURRENCY)
@@ -155,5 +153,8 @@ class Transaction(models.Model):
gateway_response = JSONField()
def __repr__(self):
- return 'Transaction(created=%s, type=%s, is_success=%s)' % (
- self.created, self.kind, self.is_success)
+ return 'Transaction(type=%s, is_success=%s, created=%s)' % (
+ self.kind, self.is_success, self.created)
+
+ def get_amount(self):
+ return Money(self.amount, self.currency or settings.DEFAULT_CURRENCY)
diff --git a/tests/api/test_payment.py b/tests/api/test_payment.py
index 4513f010c2..a87a3955ac 100644
--- a/tests/api/test_payment.py
+++ b/tests/api/test_payment.py
@@ -3,6 +3,9 @@ from tests.api.utils import get_graphql_content
from saleor.payment.models import (
ChargeStatus, Payment, Transaction, Transactions)
+from saleor.graphql.payment.types import (
+ PaymentChargeStatusEnum, PaymentGatewayEnum, OrderAction)
+from saleor.core.utils import get_country_name_by_code
VOID_QUERY = """
mutation PaymentVoid($paymentId: ID!) {
@@ -68,13 +71,9 @@ CREATE_QUERY = """
mutation CheckoutPaymentCreate($input: PaymentInput!) {
checkoutPaymentCreate(input: $input) {
payment {
- transactions(first: 1) {
- edges {
- node {
- kind,
- token
- }
- }
+ transactions {
+ kind,
+ token
}
chargeStatus
}
@@ -105,7 +104,7 @@ def test_checkout_add_payment(
content = get_graphql_content(response)
data = content['data']['checkoutPaymentCreate']
assert not data['errors']
- transactions = data['payment']['transactions']['edges']
+ transactions = data['payment']['transactions']
assert not transactions
payment = Payment.objects.get()
assert payment.checkout == cart
@@ -254,13 +253,44 @@ def test_payment_refund_error(
def test_payments_query(
- payment_dummy, permission_manage_orders, staff_api_client):
+ payment_txn_captured, permission_manage_orders, staff_api_client):
query = """ {
payments {
edges {
node {
id
gateway
+ capturedAmount {
+ amount
+ currency
+ }
+ total {
+ amount
+ currency
+ }
+ actions
+ chargeStatus
+ billingAddress {
+ country {
+ code
+ country
+ }
+ firstName
+ lastName
+ cityArea
+ countryArea
+ city
+ companyName
+ streetAddress1
+ streetAddress2
+ postalCode
+ }
+ transactions {
+ amount {
+ currency
+ amount
+ }
+ }
}
}
}
@@ -269,5 +299,31 @@ def test_payments_query(
response = staff_api_client.post_graphql(
query, permissions=[permission_manage_orders])
content = get_graphql_content(response)
- data = content['data']['payments']
- assert data['edges'][0]['node']['gateway'] == payment_dummy.gateway
+ data = content['data']['payments']['edges'][0]['node']
+ pay = payment_txn_captured
+ assert data['gateway'] == pay.gateway
+ assert data['capturedAmount'] == {
+ 'amount': pay.captured_amount, 'currency': pay.currency}
+ assert data['total'] == {'amount': pay.total, 'currency': pay.currency}
+ assert data['chargeStatus'] == PaymentChargeStatusEnum.CHARGED.name
+ assert data['billingAddress'] == {
+ 'firstName': pay.billing_first_name,
+ 'lastName': pay.billing_last_name,
+ 'city': pay.billing_city,
+ 'cityArea': pay.billing_city_area,
+ 'countryArea': pay.billing_country_area,
+ 'companyName': pay.billing_company_name,
+ 'streetAddress1': pay.billing_address_1,
+ 'streetAddress2': pay.billing_address_2,
+ 'postalCode': pay.billing_postal_code,
+ 'country': {
+ 'code': pay.billing_country_code,
+ 'country': get_country_name_by_code(pay.billing_country_code)
+ }
+ }
+ assert data['actions'] == [OrderAction.REFUND.name]
+ txn = pay.transactions.get()
+ assert data['transactions'] == [{
+ 'amount': {
+ 'currency': pay.currency,
+ 'amount': float(str(txn.amount))}}]