Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Adjust dashboard to new Payment method
Pacu2a68052d5843a
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex ebaf662964..ee3c7c5ea3 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -13,7 +13,6 @@ from django_countries.fields import Countryfrom faker import Factoryfrom faker.providers import BaseProviderfrom measurement.measures import Weight-from payments import PaymentStatusfrom prices import Moneyfrom ...account.models import Address, User@@ -25,9 +24,11 @@ from ...dashboard.menu.utils import update_menufrom ...discount import DiscountValueType, VoucherTypefrom ...discount.models import Sale, Voucherfrom ...menu.models import Menu-from ...order.models import Fulfillment, Order, Payment+from ...order.models import Fulfillment, Orderfrom ...order.utils import update_order_statusfrom ...page.models import Page+from ...payment import PaymentMethodChargeStatus, TransactionType+from ...payment.models import PaymentMethodfrom ...product.models import (Attribute, AttributeValue, Category, Collection, Product, ProductImage,ProductType, ProductVariant)@@ -376,13 +377,35 @@ def create_fake_user():return user+def create_transactions(payment):+ payment.transactions.create(+ transaction_type=TransactionType.AUTH,+ is_success=True, amount=payment.total, currency=payment.currency)+ if payment.status == PaymentMethodChargeStatus.NOT_CHARGED:+ if random.randint(0, 1):+ payment.transactions.create(+ transaction_type=TransactionType.RELEASE,+ is_success=True, amount=payment.total,+ currency=payment.currency)+ return+ payment.transactions.create(+ transaction_type=TransactionType.CAPTURE,+ is_success=True, amount=payment.total, currency=payment.currency)+ if payment.status == PaymentMethodChargeStatus.FULLY_REFUNDED:+ payment.transactions.create(+ transaction_type=TransactionType.REFUND,+ is_success=True, amount=payment.total,+ currency=payment.currency)+ return payment++def create_payment(order):status = random.choice([- PaymentStatus.WAITING,- PaymentStatus.PREAUTH,- PaymentStatus.CONFIRMED])- payment = Payment.objects.create(+ PaymentMethodChargeStatus.FULLY_REFUNDED,+ PaymentMethodChargeStatus.CHARGED,+ PaymentMethodChargeStatus.NOT_CHARGED])+ payment = PaymentMethod.objects.create(order=order,status=status,variant='default',@@ -390,17 +413,19 @@ def create_payment(order):currency=settings.DEFAULT_CURRENCY,total=order.total.gross.amount,tax=order.total.tax.amount,- delivery=order.shipping_price.net.amount,customer_ip_address=fake.ipv4(),billing_first_name=order.billing_address.first_name,billing_last_name=order.billing_address.last_name,billing_address_1=order.billing_address.street_address_1,+ billing_address_2=order.billing_address.street_address_2,billing_city=order.billing_address.city,billing_postcode=order.billing_address.postal_code,- billing_country_code=order.billing_address.country)- if status == PaymentStatus.CONFIRMED:+ billing_country_code=order.billing_address.country,+ billing_country_area=order.billing_address.country_area)+ if status == PaymentMethodChargeStatus.CONFIRMED:payment.captured_amount = payment.totalpayment.save()+ create_transactions(payment)return paymentdiff --git a/saleor/dashboard/order/filters.py b/saleor/dashboard/order/filters.pyindex 2094a15405..3797db8168 100644--- a/saleor/dashboard/order/filters.py+++ b/saleor/dashboard/order/filters.py@@ -4,11 +4,11 @@ from django.utils.translation import npgettext, pgettext_lazyfrom django_filters import (CharFilter, ChoiceFilter, DateFromToRangeFilter, NumberFilter,OrderingFilter, RangeFilter)-from payments import PaymentStatusfrom ...core.filters import SortedFilterSetfrom ...order import OrderStatusfrom ...order.models import Order+from ...payment import PaymentMethodChargeStatusfrom ..widgets import DateRangeWidget, MoneyRangeWidgetSORT_BY_FIELDS = [@@ -45,7 +45,7 @@ class OrderFilter(SortedFilterSet):payment_status = ChoiceFilter(label=pgettext_lazy('Order list filter label', 'Payment status'),field_name='payments__status',- choices=PaymentStatus.CHOICES,+ choices=PaymentMethodChargeStatus.CHOICES,empty_label=pgettext_lazy('Filter empty choice label', 'All'),widget=forms.Select)total_net = RangeFilter(diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 6ebdc5a1a0..35c43e0c78 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -122,7 +122,7 @@ def order_details(request, order_pk):'payments', 'events__user', 'lines__variant__product','fulfillments__lines__order_line')order = get_object_or_404(qs, pk=order_pk)- all_payments = order.payments.exclude(status=PaymentStatus.INPUT)+ all_payments = order.payments.all()payment = order.get_last_payment()preauthorized = ZERO_TAXED_MONEYcaptured = ZERO_MONEYdiff --git a/saleor/dashboard/views.py b/saleor/dashboard/views.pyindex 977a49bec1..ebe66dc5c7 100644--- a/saleor/dashboard/views.py+++ b/saleor/dashboard/views.py@@ -4,9 +4,9 @@ from django.contrib.admin.views.decorators import (from django.contrib.auth import REDIRECT_FIELD_NAMEfrom django.db.models import Q, Sumfrom django.template.response import TemplateResponse-from payments import PaymentStatus--from ..order.models import Order, Payment+from ..payment.models import PaymentMethod+from ..payment import PaymentMethodChargeStatus+from ..order.models import Orderfrom ..product.models import Product@@ -35,8 +35,9 @@ def index(request):paginate_by = 10orders_to_ship = Order.objects.ready_to_fulfill().select_related('user').prefetch_related('lines', 'payments')- payments = Payment.objects.filter(- status=PaymentStatus.PREAUTH).order_by('-created')+ payments = PaymentMethod.objects.filter(+ is_active=True, charge_status=PaymentMethodChargeStatus.NOT_CHARGED+ ).order_by('-created')payments = payments.select_related('order', 'order__user')low_stock = get_low_stock_products()ctx = {'preauthorized_payments': payments[:paginate_by],diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 2b5cd973a8..0635dca025 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -74,7 +74,7 @@ def clean_order_capture(payment, amount, errors):field='payment',message='There\'s no payment associated with the order.'))return errors- if payment.status != PaymentStatus.PREAUTH:+ if not payment.is_active:errors.append(Error(field='payment',@@ -84,7 +84,7 @@ def clean_order_capture(payment, amount, errors):def clean_release_payment(payment, errors):"""Check for payment errors."""- if payment.status != PaymentStatus.PREAUTH:+ if not payment.is_active:errors.append(Error(field='payment',message='Only pre-authorized payments can be released'))diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 57d97e6dbd..c2ca56d4d3 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -213,8 +213,9 @@ class Order(CountableDjangoObjectType):@gql_optimizer.resolver_hints(prefetch_related='payments')def resolve_total_captured(obj, info):payment = obj.get_last_payment()+ #FIXME adjust to multiple paymentsif payment:- return payment.get_captured_price()+ return payment.get_captured_money()@staticmethoddef resolve_fulfillments(obj, info):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex b7397550aa..b524cc82d6 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1189,7 +1189,7 @@ type PaymentMethod implements Node {isActive: Boolean!created: DateTime!modified: DateTime!- chargeStatus: PaymentMethodCaptureStatus!+ chargeStatus: PaymentMethodChargeStatus!billingFirstName: String!billingLastName: String!billingAddress1: String!@@ -1216,7 +1216,7 @@ type PaymentMethodCapture {paymentMethod: PaymentMethod}-enum PaymentMethodCaptureStatus {+enum PaymentMethodChargeStatus {CHARGEDNOT_CHARGEDFULLY_REFUNDEDdiff --git a/saleor/order/models.py b/saleor/order/models.pyindex fa8c7311b4..fe12c30da1 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -15,7 +15,6 @@ from django_prices.models import MoneyField, TaxedMoneyFieldfrom measurement.measures import Weightfrom payments import PurchasedItemfrom payments.models import BasePayment-from payment import PaymentMethodChargeStatusfrom prices import Money, TaxedMoneyfrom . import FulfillmentStatus, OrderEvents, OrderStatus, display_order_event@@ -25,6 +24,7 @@ from ..core.utils.json_serializer import CustomJsonEncoderfrom ..core.utils.taxes import ZERO_TAXED_MONEYfrom ..core.weight import WeightUnits, zero_weightfrom ..discount.models import Voucher+from ..payment import PaymentMethodChargeStatusfrom ..shipping.models import ShippingMethod@@ -132,8 +132,8 @@ class Order(models.Model):def is_fully_paid(self):payments = self.payment_methods.filter(charge_status=PaymentMethodChargeStatus.CHARGED)- total_paid = sum([- payment.get_total() for payment in payments], ZERO_TAXED_MONEY)+ total_captured = [payment.get_captured_money() for payment in payments]+ total_paid = sum(total_captured, ZERO_TAXED_MONEY)return total_paid.gross >= self.total.grossdef get_user_current_email(self):diff --git a/saleor/order/views.py b/saleor/order/views.pyindex a84589071a..1d886fc015 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -84,10 +84,6 @@ def payment(request, token):@check_order_statusdef start_payment(request, order, variant):- waiting_payments = order.payments.filter(- status=PaymentStatus.WAITING).exists()- if waiting_payments:- return redirect('order:payment', token=order.token)billing = order.billing_addresstotal = order.totaldefaults = {diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex fd7004a518..d77a024455 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -37,7 +37,7 @@ class TransactionType:(VOID, pgettext_lazy('transaction type', 'Void'))]-class PaymentMethodCaptureStatus:+class PaymentMethodChargeStatus:"""- Charged: Funds were taken off the customer founding source, partly orcompletly covering the payment amount.diff --git a/saleor/payment/forms.py b/saleor/payment/forms.pyindex adf8eb6321..78da79ffb1 100644--- a/saleor/payment/forms.py+++ b/saleor/payment/forms.py@@ -1,6 +1,6 @@from django import forms-from ..payment import TransactionType+from . import TransactionTypefrom .models import PaymentMethoddiff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex fbfa6add1e..0b58172d7f 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 PaymentMethodCaptureStatus, TransactionType+from . import PaymentMethodChargeStatus, 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=PaymentMethodCaptureStatus.CHOICES,- default=PaymentMethodCaptureStatus.NOT_CHARGED)+ choices=PaymentMethodChargeStatus.CHOICES,+ default=PaymentMethodChargeStatus.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)diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 63be3ac9dc..d6df5760bb 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, PaymentMethodCaptureStatus, get_provider+from . import PaymentError, PaymentMethodChargeStatus, 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 == PaymentMethodCaptureStatus.NOT_CHARGED:+ if not payment_method.charge_status == PaymentMethodChargeStatus.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 = PaymentMethodCaptureStatus.NOT_CHARGED+ payment_method.charge_status = PaymentMethodChargeStatus.NOT_CHARGEDpayment_method.save(update_fields=['charge_status'])if not txn.is_success:# TODO: Handle gateway response here somehow@@ -65,8 +65,8 @@ def gateway_authorize(payment_method, transaction_token) -> Transaction:@validate_payment_methoddef gateway_capture(payment_method, amount) -> Transaction:if payment_method.charge_status not in {- PaymentMethodCaptureStatus.CHARGED,- PaymentMethodCaptureStatus.NOT_CHARGED}:+ PaymentMethodChargeStatus.CHARGED,+ PaymentMethodChargeStatus.NOT_CHARGED}:raise PaymentError('This payment method cannot be captured.')if amount > payment_method.total or amount > (payment_method.total - payment_method.captured_amount):@@ -79,7 +79,7 @@ def gateway_capture(payment_method, amount) -> Transaction:txn, error = provider.capture(payment_method, amount=amount, **provider_params)if txn.is_success:- payment_method.charge_status = PaymentMethodCaptureStatus.CHARGED+ payment_method.charge_status = PaymentMethodChargeStatus.CHARGEDpayment_method.captured_amount += txn.amountpayment_method.save(update_fields=['charge_status', 'captured_amount'])@@ -92,7 +92,7 @@ def gateway_capture(payment_method, amount) -> Transaction:@validate_payment_methoddef gateway_void(payment_method) -> Transaction:- if not payment_method.charge_status == PaymentMethodCaptureStatus.NOT_CHARGED:+ if not payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED:raise PaymentError('Only pre-authorized transactions can be void.')provider, provider_params = get_provider(payment_method.variant)with transaction.atomic():@@ -111,7 +111,7 @@ 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 == PaymentMethodCaptureStatus.CHARGED:+ if not payment_method.charge_status == PaymentMethodChargeStatus.CHARGED:raise PaymentError('Refund is possible only when transaction is captured.')@@ -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 = PaymentMethodCaptureStatus.FULLY_REFUNDED+ payment_method.charge_status = PaymentMethodChargeStatus.FULLY_REFUNDEDpayment_method.is_active = Falsechanged_fields += ['charge_status', 'is_active']payment_method.captured_amount -= amountdiff --git a/tests/conftest.py b/tests/conftest.pyindex 762bf93a91..d4c92e2eda 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -466,14 +466,6 @@ def draft_order(order_with_lines):return order_with_lines-def payment_waiting(order_with_lines):- return order_with_lines.payments.create(- variant='default', status=PaymentStatus.WAITING,- fraud_status=FraudStatus.ACCEPT, currency='USD',- total=order_with_lines.total_gross.amount)--@pytest.fixture()def payment_preauth(order_with_lines):return order_with_lines.payments.create(