Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Expose possible actions on payment
Pacu2a66c90f86901
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex bdbaa52181..3a822100e8 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -13,12 +13,12 @@ from ...core.exceptions import InsufficientStockfrom ...core.utils.taxes import ZERO_TAXED_MONEYfrom ...discount.models import Voucherfrom ...discount.utils import decrease_voucher_usage, increase_voucher_usage-from ...order import CustomPaymentChoices, OrderStatus+from ...order import OrderStatusfrom ...order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ...order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order,change_order_line_quantity, recalculate_order)-from ...payment import ChargeStatus, PaymentError+from ...payment import ChargeStatus, CustomPaymentChoices, PaymentErrorfrom ...payment.models import Paymentfrom ...payment.utils import get_billing_datafrom ...product.models import Product, ProductVariantdiff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 52afc2f317..01373314c8 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -449,7 +449,8 @@ class CheckoutComplete(BaseMutation):payment = checkout.payments.filter(is_active=True).first()# FIXME there could be a situation where order was created but payment- # failed. we should cancel the order at this moment I think+ # failed. we should cancel/delete the order at this moment I think+# authorize paymenttry:gateway_authorize(payment, payment.token)diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 2f21cf4c8c..d69eee64a3 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -3,9 +3,9 @@ from graphql_jwt.decorators import permission_requiredfrom ....account.models import Userfrom ....core.utils.taxes import ZERO_TAXED_MONEY-from ....order import CustomPaymentChoices, OrderEvents, models+from ....order import OrderEvents, modelsfrom ....order.utils import cancel_order-from ....payment import ChargeStatus, PaymentError+from ....payment import ChargeStatus, CustomPaymentChoices, PaymentErrorfrom ....payment.models import Paymentfrom ....payment.utils import get_billing_datafrom ....shipping.models import ShippingMethod as ShippingMethodModeldiff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex a2161060b1..1fb04de1f4 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -8,7 +8,7 @@ from ..account.types import Userfrom ..core.fields import PrefetchingConnectionFieldfrom ..core.types.common import CountableDjangoObjectTypefrom ..core.types.money import Money, TaxedMoney-from ..payment.types import PaymentChargeStatusEnum+from ..payment.types import PaymentChargeStatusEnum, OrderActionfrom ..shipping.types import ShippingMethodOrderEventsEnum = graphene.Enum.from_enum(OrderEvents)@@ -138,24 +138,6 @@ class OrderLine(CountableDjangoObjectType):return self.unit_price-class OrderAction(graphene.Enum):- CAPTURE = 'CAPTURE'- MARK_AS_PAID = 'MARK_AS_PAID'- REFUND = 'REFUND'- VOID = 'VOID'-- @property- def description(self):- if self == OrderAction.CAPTURE:- return 'Represents the capture action.'- if self == OrderAction.MARK_AS_PAID:- return 'Represents a mark-as-paid action.'- if self == OrderAction.REFUND:- return 'Represents a refund action.'- if self == OrderAction.VOID:- return 'Represents a void action.'--class Order(CountableDjangoObjectType):fulfillments = gql_optimizer.field(graphene.List(diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.pyindex aa9a2b51ad..401c416492 100644--- a/saleor/graphql/payment/types.py+++ b/saleor/graphql/payment/types.py@@ -11,12 +11,33 @@ PaymentChargeStatusEnum = graphene.Enum([(str_to_enum(code.upper()), code) for code, name in ChargeStatus.CHOICES])+class OrderAction(graphene.Enum):+ CAPTURE = 'CAPTURE'+ MARK_AS_PAID = 'MARK_AS_PAID'+ REFUND = 'REFUND'+ VOID = 'VOID'++ @property+ def description(self):+ if self == OrderAction.CAPTURE:+ return 'Represents the capture action.'+ if self == OrderAction.MARK_AS_PAID:+ return 'Represents a mark-as-paid action.'+ if self == OrderAction.REFUND:+ return 'Represents a refund action.'+ if self == OrderAction.VOID:+ return 'Represents a void action.'++class Payment(CountableDjangoObjectType):# FIXME gateway_response field should be resolved into query-readable format# if we want to use it on the frontend# otherwise it should be removed from this typecharge_status = PaymentChargeStatusEnum(description='Internal payment status.', required=True)+ actions = graphene.List(+ OrderAction, description='''List of actions that can be performed in+ the current state of a payment.''', required=True)class Meta:description = 'Represents a payment of a given type.'@@ -24,6 +45,16 @@ class Payment(CountableDjangoObjectType):model = models.Paymentfilter_fields = ['id']+ def resolve_actions(self, info):+ actions = []+ if self.can_capture():+ actions.append(OrderAction.CAPTURE)+ if self.can_refund():+ actions.append(OrderAction.REFUND)+ if self.can_void():+ actions.append(OrderAction.VOID)+ return actions+class Transaction(CountableDjangoObjectType):class Meta:diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 691b71b004..52c2e8acf1 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1232,6 +1232,7 @@ type Payment implements Node {checkout: Checkoutorder: Ordertransactions(before: String, after: String, first: Int, last: Int, id: ID): TransactionCountableConnection+ actions: [OrderAction]!}type PaymentCapture {diff --git a/saleor/order/__init__.py b/saleor/order/__init__.pyindex f4edb87fd0..333ac217c5 100644--- a/saleor/order/__init__.py+++ b/saleor/order/__init__.py@@ -46,13 +46,6 @@ class FulfillmentStatus:'Canceled'))]-class CustomPaymentChoices:- MANUAL = 'manual'-- CHOICES = [- (MANUAL, pgettext_lazy('Custom payment choice type', 'Manual'))]--class OrderEvents(Enum):PLACED = 'placed'PLACED_FROM_DRAFT = 'draft_placed'diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 08eae4d5ac..a0a597c801 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -16,8 +16,7 @@ from measurement.measures import Weightfrom prices import Moneyfrom . import (- CustomPaymentChoices, FulfillmentStatus, OrderEvents, OrderStatus,- display_order_event)+ FulfillmentStatus, OrderEvents, OrderStatus, display_order_event)from ..account.models import Addressfrom ..core.utils.json_serializer import CustomJsonEncoderfrom ..core.utils.taxes import ZERO_TAXED_MONEY, zero_money@@ -221,29 +220,21 @@ class Order(models.Model):return Falseorder_status_ok = self.status not in {OrderStatus.DRAFT, OrderStatus.CANCELED}- return (- payment.is_active and- payment.charge_status == ChargeStatus.NOT_CHARGED and- order_status_ok)+ return payment.can_capture() and order_status_okdef can_void(self, payment=None):if not payment:payment = self.get_last_payment()if not payment:return False- return (- payment.is_active and- payment.charge_status == ChargeStatus.NOT_CHARGED)+ return payment.can_void()def can_refund(self, payment=None):if not payment:payment = self.get_last_payment()if not payment:return False- return (- payment.is_active and- payment.charge_status == ChargeStatus.CHARGED and- payment.variant != CustomPaymentChoices.MANUAL)+ return payment.can_refund()def can_mark_as_paid(self):return len(self.payments.all()) == 0diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex a53c32909c..1d183dc530 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -12,6 +12,7 @@ from ..dashboard.order.utils import get_voucher_discount_for_orderfrom ..discount.models import NotApplicablefrom ..order import FulfillmentStatus, OrderStatusfrom ..order.models import OrderLine+from ..payment import ChargeStatusfrom ..product.utils import allocate_stock, deallocate_stock, increase_stock@@ -107,6 +108,16 @@ def cancel_order(order, restock):order.status = OrderStatus.CANCELEDorder.save(update_fields=['status'])+ payments = order.payments.filter(+ is_active=True,+ charge_status__in=[ChargeStatus.NOT_CHARGED, ChargeStatus.CHARGED])++ for payment in payments:+ if payment.can_refund():+ payment.refund()+ elif payment.can_void():+ payment.void()+def update_order_status(order):"""Update order status depending on fulfillments."""diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex 2b717278cc..29136c0753 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -12,6 +12,13 @@ class PaymentError(Exception):self.message = message+class CustomPaymentChoices:+ MANUAL = 'manual'++ CHOICES = [+ (MANUAL, pgettext_lazy('Custom payment choice type', 'Manual'))]++class TransactionType:"""- Authorization: An amount reserved against the customer's fundingdiff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex a9c4158991..c683a76f48 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -7,7 +7,7 @@ from django.db import modelsfrom django_prices.models import MoneyFieldfrom prices import Money-from . import ChargeStatus, TransactionType+from . import ChargeStatus, CustomPaymentChoices, TransactionTypefrom ..checkout.models import Cartfrom ..core.utils.taxes import zero_moneyfrom ..order.models import Order@@ -24,10 +24,9 @@ class Payment(models.Model):Several payment methods can be used within a single order."""- #FIXME we should provide an option to store the card for later usage+ # FIXME we should provide an option to store the card for later usage+ # FIXME probably we should have pending statusvariant = models.CharField(max_length=255)- # FIXME probably we should have error/pending/active status instead of- # a boolis_active = models.BooleanField(default=True)#: Creation date and timecreated = models.DateTimeField(auto_now_add=True)@@ -104,15 +103,31 @@ class Payment(models.Model):def capture(self, amount=None):from . import utilsif amount is None:- amount = self.total+ # If no amount is specified, capture the maximum possible+ amount = self.total - self.captured_amountreturn utils.gateway_capture(payment=self, amount=amount)def refund(self, amount=None):from . import utilsif amount is None:- amount = self.total+ # If no amount is specified, refund the maximum possible+ amount = self.captured_amountreturn utils.gateway_refund(payment=self, amount=amount)+ def can_capture(self):+ return (+ self.is_active and self.charge_status == ChargeStatus.NOT_CHARGED)++ def can_void(self):+ return (+ self.is_active and self.charge_status == ChargeStatus.NOT_CHARGED)++ def can_refund(self):+ return (+ self.is_active and+ self.charge_status == ChargeStatus.CHARGED and+ self.variant != CustomPaymentChoices.MANUAL)+class Transaction(models.Model):"""Transactions represent attempts to transfer money between your storediff --git a/tests/api/test_order.py b/tests/api/test_order.pyindex 1f4af0d0b0..5c9fa28b3a 100644--- a/tests/api/test_order.py+++ b/tests/api/test_order.py@@ -14,9 +14,9 @@ from saleor.graphql.order.mutations.orders import (clean_refund_payment, clean_void_payment)from saleor.graphql.order.types import OrderEventsEmailsEnum, OrderStatusFilterfrom saleor.graphql.payment.types import PaymentChargeStatusEnum-from saleor.order import (- CustomPaymentChoices, OrderEvents, OrderEventsEmails, OrderStatus)+from saleor.order import OrderEvents, OrderEventsEmails, OrderStatusfrom saleor.order.models import Order, OrderEvent+from saleor.payment import CustomPaymentChoicesfrom saleor.payment.models import Paymentfrom saleor.shipping.models import ShippingMethod