Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Rename charge to capture, add additional statuses
Pacu26250d95a913d
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 06a43bef27..6ebdc5a1a0 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -11,7 +11,6 @@ from django.template.response import TemplateResponsefrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django.views.decorators.http import require_POSTfrom django_prices.templatetags import prices_i18n-from payments import PaymentStatusfrom ...core.exceptions import InsufficientStockfrom ...core.utils import get_paginator_itemsdiff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 3234222f9d..23d93c7813 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -46,7 +46,7 @@ from .product.schema import ProductMutations, ProductQueriesfrom .payment.types import Payment, PaymentGatewayEnumfrom .payment.resolvers import resolve_payments, resolve_payment_client_tokenfrom .payment.mutations import (- CheckoutPaymentMethodCreate, PaymentMethodCharge, PaymentMethodRefund,+ CheckoutPaymentMethodCreate, PaymentMethodCapture, PaymentMethodRefund,PaymentMethodVoid)from .shipping.resolvers import resolve_shipping_zonesfrom .shipping.types import ShippingZonediff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 50c6e0f371..6345fee60d 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -8,6 +8,7 @@ from ...checkout.utils import (get_taxes_for_cart, ready_to_place_order)from ...core import analyticsfrom ...core.exceptions import InsufficientStock+from ...core.utils.taxes import get_taxes_for_addressfrom ...shipping.models import ShippingMethod as ShippingMethodModelfrom ..account.types import AddressInput, Userfrom ..core.mutations import BaseMutation, ModelMutation@@ -279,9 +280,18 @@ class CheckoutShippingAddressUpdate(BaseMutation):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)+shipping_address = Address(**shipping_address)- # FIXME validate if shipping method is still valid after changing- # shipping address+ cls.clean_instance(shipping_address, errors)+ if errors:+ CheckoutShippingAddressUpdate(errors=errors)++ clean_shipping_method(+ checkout, checkout.shipping_method, errors,+ info.context.discounts, get_taxes_for_address(shipping_address))+ if errors:+ CheckoutShippingAddressUpdate(errors=errors)+if checkout and shipping_address:with transaction.atomic():shipping_address.save()diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex e0e44e35f2..e4d0c6bff7 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -3,7 +3,7 @@ from graphql_jwt.decorators import permission_requiredfrom ...payment import PaymentErrorfrom ...payment.utils import (- create_payment_method, gateway_authorize, gateway_charge, gateway_refund,+ create_payment_method, gateway_authorize, gateway_capture, gateway_refund,gateway_void)from ..account.types import AddressInputfrom ..checkout.types import Checkout@@ -94,7 +94,7 @@ class CheckoutPaymentMethodCreate(BaseMutation):'customer_user_agent': user_agent}-class PaymentMethodCharge(BaseMutation):+class PaymentMethodCapture(BaseMutation):payment_method = graphene.Field(PaymentMethod, description='Updated payment method')@@ -112,18 +112,18 @@ class PaymentMethodCharge(BaseMutation):only_type=PaymentMethod)if not payment_method:- return PaymentMethodCharge(errors=errors)+ return PaymentMethodCapture(errors=errors)try:- gateway_charge(payment_method, amount=amount)+ gateway_capture(payment_method, amount=amount)except PaymentError as exc:msg = str(exc)cls.add_error(field=None, message=msg, errors=errors)- return PaymentMethodCharge(+ return PaymentMethodCapture(payment_method=payment_method, errors=errors)-class PaymentMethodRefund(PaymentMethodCharge):+class PaymentMethodRefund(PaymentMethodCapture):@classmethod@permission_required('order.manage_orders')def mutate(cls, root, info, payment_method_id, amount=None):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex f39a7e2eba..b7397550aa 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -294,12 +294,13 @@ type Checkout implements Node {discountName: StringtranslatedDiscountName: StringvoucherCode: String- lines(before: String, after: String, first: Int, last: Int, id: ID): CheckoutLineCountableConnection+ lines: [CheckoutLine]paymentMethods(before: String, after: String, first: Int, last: Int, id: ID): PaymentMethodCountableConnectionid: ID!totalPrice: TaxedMoneysubtotalPrice: TaxedMoneyshippingPrice: TaxedMoney+ availableShippingMethods: [ShippingMethod]}type CheckoutComplete {@@ -888,7 +889,7 @@ type Mutations {pageCreate(input: PageInput!): PageCreatepageDelete(id: ID!): PageDeletepageUpdate(id: ID!, input: PageInput!): PageUpdate- paymentMethodCharge(amount: Decimal, paymentMethodId: ID!): PaymentMethodCharge+ paymentMethodCharge(amount: Decimal, paymentMethodId: ID!): PaymentMethodCapturepaymentMethodRefund(amount: Decimal, paymentMethodId: ID!): PaymentMethodRefundpaymentMethodVoid(paymentMethodId: ID!): PaymentMethodVoidsaleCreate(input: SaleInput!): SaleCreate@@ -1188,7 +1189,7 @@ type PaymentMethod implements Node {isActive: Boolean!created: DateTime!modified: DateTime!- chargeStatus: PaymentMethodChargeStatus!+ chargeStatus: PaymentMethodCaptureStatus!billingFirstName: String!billingLastName: String!billingAddress1: String!@@ -1210,12 +1211,12 @@ type PaymentMethod implements Node {transactions(before: String, after: String, first: Int, last: Int, id: ID): TransactionCountableConnection}-type PaymentMethodCharge {+type PaymentMethodCapture {errors: [Error]paymentMethod: PaymentMethod}-enum PaymentMethodChargeStatus {+enum PaymentMethodCaptureStatus {CHARGEDNOT_CHARGEDFULLY_REFUNDED@@ -1879,11 +1880,13 @@ type TaxedMoneyRange {type Transaction implements Node {id: ID!+ created: DateTime!paymentMethod: PaymentMethod!token: String!transactionType: TransactionTransactionType!isSuccess: Boolean!amount: Float!+ currency: String!gatewayResponse: JSONString!}diff --git a/saleor/order/models.py b/saleor/order/models.pyindex f478eb64c3..fa8c7311b4 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -13,8 +13,9 @@ from django.utils.translation import pgettext_lazyfrom django_measurement.models import MeasurementFieldfrom django_prices.models import MoneyField, TaxedMoneyFieldfrom measurement.measures import Weight-from payments import PaymentStatus, PurchasedItem+from payments import PurchasedItemfrom payments.models import BasePayment+from payment import PaymentMethodChargeStatusfrom prices import Money, TaxedMoneyfrom . import FulfillmentStatus, OrderEvents, OrderStatus, display_order_event@@ -129,12 +130,10 @@ class Order(models.Model):return super().save(*args, **kwargs)def is_fully_paid(self):- confirmed_payments = [- payment for payment in self.payments.all()- if payment.status == PaymentStatus.CONFIRMED]- total_paid = sum(- [payment.get_total()- for payment in confirmed_payments], ZERO_TAXED_MONEY)+ payments = self.payment_methods.filter(+ charge_status=PaymentMethodChargeStatus.CHARGED)+ total_paid = sum([+ payment.get_total() for payment in payments], ZERO_TAXED_MONEY)return total_paid.gross >= self.total.grossdef get_user_current_email(self):@@ -175,9 +174,10 @@ class Order(models.Model):return Nonedef is_pre_authorized(self):- # FIXME Adapt to new API- # FIXME: Check for really pre-authorized transactions- return self.payment_methods.filter(is_active=True).exists()+ # FIXME for Braintree, payment is preauthorized if it was added+ # properly and set to active. This might need to be adjusted for other+ # payment gateways in the future.+ return not self.payment_methods.filter(is_active=True).exists()@propertydef quantity_fulfilled(self):diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex b28a7ee95e..fd7004a518 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -10,25 +10,48 @@ class PaymentError(Exception):class TransactionType:+ """+ - Authorization: An amount reserved against the customer's funding+ source. Money does not change hands until the+ authorization is captured.+ - Charge: Authorization and capture in a single step.+ - Void: A cancellation of a pending authorization.+ - Capture: A transfer of the money that was reserved during the+ authorization stage.+ - Refund: Full or partial return of captured funds to the customer.+ - Release: Release of the funds that were reserved during the authorization+ stage to the customer's funding source.+ """AUTH = 'auth'- CHARGE = 'charge'+ CHARGE = 'capture'+ CAPTURE = 'capture'VOID = 'void'REFUND = 'refund'+ RELEASE = 'release'CHOICES = [(AUTH, pgettext_lazy('transaction type', 'Authorization')),(CHARGE, pgettext_lazy('transaction type', 'Charge')),(REFUND, pgettext_lazy('transaction type', 'Refund')),+ (RELEASE, pgettext_lazy('transaction type', 'Release')),+ (CAPTURE, pgettext_lazy('transaction type', 'Capture')),(VOID, pgettext_lazy('transaction type', 'Void'))]-class PaymentMethodChargeStatus:+class PaymentMethodCaptureStatus:+ """+ - Charged: Funds were taken off the customer founding source, partly or+ completly covering the payment amount.+ - Not charged: No funds were take off the customer founding source yet.+ - Fully refunded: All charged funds were returned to the customer.+ """CHARGED = 'charged'NOT_CHARGED = 'not-charged'FULLY_REFUNDED = 'fully-refunded'CHOICES = [(CHARGED, pgettext_lazy('payment method status', 'Charged')),- (NOT_CHARGED, pgettext_lazy('payment method status', 'Not charged')), (+ (NOT_CHARGED, pgettext_lazy('payment method status', 'Not charged')),+ (FULLY_REFUNDED,pgettext_lazy('payment method status', 'Fully refunded'))]diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex 4d568b12e0..fbfa6add1e 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -4,7 +4,7 @@ from django.contrib.postgres.fields import JSONFieldfrom django.db import modelsfrom prices import Money-from . import PaymentMethodChargeStatus, TransactionType+from . import PaymentMethodCaptureStatus, TransactionTypefrom ..checkout.models import Cartfrom ..order.models import Order@@ -29,8 +29,8 @@ class PaymentMethod(models.Model):modified = models.DateTimeField(auto_now=True)charge_status = models.CharField(max_length=15,- choices=PaymentMethodChargeStatus.CHOICES,- default=PaymentMethodChargeStatus.NOT_CHARGED)+ choices=PaymentMethodCaptureStatus.CHOICES,+ default=PaymentMethodCaptureStatus.NOT_CHARGED)billing_first_name = models.CharField(max_length=256, blank=True)billing_last_name = models.CharField(max_length=256, blank=True)billing_address_1 = models.CharField(max_length=256, blank=True)@@ -90,11 +90,11 @@ class PaymentMethod(models.Model):from . import utilsreturn utils.gateway_void(payment_method=self)- def charge(self, amount=None):+ def capture(self, amount=None):# FIXME Used for backwards compatibility, remove after moving to# dashboard 2.0from . import utils- return utils.gateway_charge(payment_method=self, amount=amount)+ return utils.gateway_capture(payment_method=self, amount=amount)def refund(self, amount=None):# FIXME Used for backwards compatibility, remove after moving todiff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.pyindex b39d433016..e139eda5af 100644--- a/saleor/payment/providers/braintree/__init__.py+++ b/saleor/payment/providers/braintree/__init__.py@@ -95,7 +95,7 @@ def authorize(payment_method, transaction_token, **client_kwargs):return txn, error-def charge(payment_method, amount=None, **client_kwargs):+def capture(payment_method, amount=None, **client_kwargs):gateway = get_gateway(**client_kwargs)auth_transaction = payment_method.transactions.filter(transaction_type=TransactionType.AUTH).first()@@ -108,7 +108,7 @@ def charge(payment_method, amount=None, **client_kwargs):txn = create_transaction(payment_method=payment_method,- transaction_type=TransactionType.CHARGE,+ transaction_type=TransactionType.CAPTURE,amount=amount,token=result.transaction.id,is_success=result.is_success,@@ -136,7 +136,7 @@ def void(payment_method, **client_kwargs):def refund(payment_method, amount=None, **client_kwargs):gateway = get_gateway(**client_kwargs)auth_transaction = payment_method.transactions.filter(- transaction_type=TransactionType.CHARGE).first()+ transaction_type=TransactionType.CAPTURE).first()result = gateway.transaction.refund(transaction_id=auth_transaction.token, amount=amount)gateway_response = extract_gateway_response(result)diff --git a/saleor/payment/providers/dummy/__init__.py b/saleor/payment/providers/dummy/__init__.pyindex c869555190..b2776f58e0 100644--- a/saleor/payment/providers/dummy/__init__.py+++ b/saleor/payment/providers/dummy/__init__.py@@ -42,14 +42,14 @@ def void(payment_method, **client_kwargs):return txn, error-def charge(payment_method, amount=None):+def capture(payment_method, amount=None):error = Nonesuccess = dummy_success()if not success:- error = 'Unable to process charge'+ error = 'Unable to process capture'txn = create_transaction(payment_method=payment_method,- transaction_type=TransactionType.CHARGE,+ transaction_type=TransactionType.CAPTURE,amount=amount,token=str(uuid.uuid4()),is_success=success)diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 4f580488ef..63be3ac9dc 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -4,7 +4,7 @@ from typing import Dict, Optionalfrom django.db import transaction-from . import PaymentError, PaymentMethodChargeStatus, get_provider+from . import PaymentError, PaymentMethodCaptureStatus, get_providerfrom .models import PaymentMethod, Transaction@@ -46,7 +46,7 @@ def gateway_get_client_token(provider_name):@validate_payment_methoddef gateway_authorize(payment_method, transaction_token) -> Transaction:- if not payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED:+ if not payment_method.charge_status == PaymentMethodCaptureStatus.NOT_CHARGED:raise PaymentError('Charged transactions cannot be authorized again.')provider, provider_params = get_provider(payment_method.variant)@@ -54,7 +54,7 @@ def gateway_authorize(payment_method, transaction_token) -> Transaction:txn, error = provider.authorize(payment_method, transaction_token, **provider_params)if txn.is_success:- payment_method.charge_status = PaymentMethodChargeStatus.NOT_CHARGED+ payment_method.charge_status = PaymentMethodCaptureStatus.NOT_CHARGEDpayment_method.save(update_fields=['charge_status'])if not txn.is_success:# TODO: Handle gateway response here somehow@@ -63,23 +63,23 @@ def gateway_authorize(payment_method, transaction_token) -> Transaction:@validate_payment_method-def gateway_charge(payment_method, amount) -> Transaction:+def gateway_capture(payment_method, amount) -> Transaction:if payment_method.charge_status not in {- PaymentMethodChargeStatus.CHARGED,- PaymentMethodChargeStatus.NOT_CHARGED}:- raise PaymentError('This payment method cannot be charged.')+ PaymentMethodCaptureStatus.CHARGED,+ PaymentMethodCaptureStatus.NOT_CHARGED}:+ raise PaymentError('This payment method cannot be captured.')if amount > payment_method.total or amount > (payment_method.total - payment_method.captured_amount):- raise PaymentError('Unable to charge more than authorized amount.')+ raise PaymentError('Unable to capture more than authorized amount.')if amount <= 0:raise PaymentError('Amount should be a positive number.')provider, provider_params = get_provider(payment_method.variant)with transaction.atomic():- txn, error = provider.charge(+ txn, error = provider.capture(payment_method, amount=amount, **provider_params)if txn.is_success:- payment_method.charge_status = PaymentMethodChargeStatus.CHARGED+ payment_method.charge_status = PaymentMethodCaptureStatus.CHARGEDpayment_method.captured_amount += txn.amountpayment_method.save(update_fields=['charge_status', 'captured_amount'])@@ -92,7 +92,7 @@ def gateway_charge(payment_method, amount) -> Transaction:@validate_payment_methoddef gateway_void(payment_method) -> Transaction:- if not payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED:+ if not payment_method.charge_status == PaymentMethodCaptureStatus.NOT_CHARGED:raise PaymentError('Only pre-authorized transactions can be void.')provider, provider_params = get_provider(payment_method.variant)with transaction.atomic():@@ -111,9 +111,9 @@ def gateway_refund(payment_method, amount) -> Transaction:raise PaymentError('Cannot refund more than captured')if amount <= 0:raise PaymentError('Amount should be a positive number.')- if not payment_method.charge_status == PaymentMethodChargeStatus.CHARGED:+ if not payment_method.charge_status == PaymentMethodCaptureStatus.CHARGED:raise PaymentError(- 'Refund is possible only when transaction is charged.')+ 'Refund is possible only when transaction is captured.')provider, provider_params = get_provider(payment_method.variant)with transaction.atomic():@@ -121,7 +121,7 @@ def gateway_refund(payment_method, amount) -> Transaction:if txn.is_success:changed_fields = ['captured_amount']if txn.amount == payment_method.total:- payment_method.charge_status = PaymentMethodChargeStatus.FULLY_REFUNDED+ payment_method.charge_status = PaymentMethodCaptureStatus.FULLY_REFUNDEDpayment_method.is_active = Falsechanged_fields += ['charge_status', 'is_active']payment_method.captured_amount -= amount