Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Rename PaymentMethod to Payment
Pacu27e117aa9a163
diff --git a/docs/architecture/payments.rst b/docs/architecture/payments.rstindex bf298029ed..da268f3c1c 100644--- a/docs/architecture/payments.rst+++ b/docs/architecture/payments.rst@@ -13,9 +13,9 @@ All payment process related pieces of information are stored at the gateway levewe are operating on the reusable token which is a unique identifierof the customer for given gateway.-Payment methods belong to a customer, one can use several payments method within a single order.+Several payment methods can be used within a single order.-Payment method has 3 possible charge statuses:+Payment has 3 possible charge statuses:+----------------+-------------------+------------------------------------------------------------------------------------------------------+| Code | GraphQL API value | Description |diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 4a15f0001e..cec62b95c0 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -846,7 +846,7 @@ def _fill_order_with_cart_data(order, cart, discounts, taxes):add_variant_to_order(order, line.variant, line.quantity, discounts, taxes)- cart.payment_methods.update(order=order)+ cart.payments.update(order=order)if cart.note:order.customer_note = cart.note@@ -886,9 +886,9 @@ def create_order(cart, tracking_code, discounts, taxes):def is_fully_paid(cart: Cart):- payment_methods = cart.payment_methods.filter(is_active=True)+ payments = cart.payments.filter(is_active=True)total_paid = sum(- [p.captured_amount.amount for p in payment_methods])+ [p.captured_amount.amount for p in payments])return total_paid >= cart.get_total().gross.amountdiff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 03a1dc95e6..30c20ce5d1 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -28,7 +28,12 @@ from ...order.models import Fulfillment, Orderfrom ...order.utils import update_order_statusfrom ...page.models import Pagefrom ...payment import ChargeStatus, TransactionType+<<<<<<< HEADfrom ...payment.models import PaymentMethod+=======+from ...payment.utils import get_billing_data+from ...payment.models import Payment+>>>>>>> Rename PaymentMethod to Paymentfrom ...product.models import (Attribute, AttributeValue, Category, Collection, Product, ProductImage,ProductType, ProductVariant)@@ -407,11 +412,11 @@ def create_payment(order):ChargeStatus.FULLY_REFUNDED,ChargeStatus.CHARGED,ChargeStatus.NOT_CHARGED])- payment = PaymentMethod.objects.create(- order=order,+ payment = Payment.objects.create(charge_status=status,variant='default',customer_ip_address=fake.ipv4(),+ is_active=True,order=order,total=order.total.gross,**get_billing_data(order))diff --git a/saleor/dashboard/order/filters.py b/saleor/dashboard/order/filters.pyindex ce216c7551..1d394b477f 100644--- a/saleor/dashboard/order/filters.py+++ b/saleor/dashboard/order/filters.py@@ -13,14 +13,14 @@ from ..widgets import DateRangeWidget, MoneyRangeWidgetSORT_BY_FIELDS = [('pk', 'pk'),- ('payment_methods__charge_status', 'payment_status'),+ ('payments__charge_status', 'payment_status'),('user__email', 'email'),('created', 'created'),('total_net', 'total')]SORT_BY_FIELDS_LABELS = {'pk': pgettext_lazy('Order list sorting option', '#'),- 'payment_methods__charge_status': pgettext_lazy(+ 'payments__charge_status': pgettext_lazy('Order list sorting option', 'payment'),'user__email': pgettext_lazy('Order list sorting option', 'email'),'created': pgettext_lazy('Order list sorting option', 'created'),diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 14aa9c04f8..ff30cee10e 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -19,7 +19,8 @@ from ...order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order,change_order_line_quantity, recalculate_order)from ...payment import ChargeStatus, PaymentError-from ...payment.models import PaymentMethod+from ...payment.models import Payment+from ...payment.utils import get_billing_datafrom ...product.models import Product, ProductVariantfrom ...product.utils import allocate_stock, deallocate_stockfrom ...shipping.models import ShippingMethod@@ -345,7 +346,7 @@ class OrderMarkAsPaidForm(forms.Form):def clean(self):super().clean()- if self.order.payment_methods.exists():+ if self.order.payments.exists():raise forms.ValidationError(pgettext_lazy('Mark order as paid form error',@@ -357,7 +358,7 @@ class OrderMarkAsPaidForm(forms.Form):'total': self.order.total.gross,'captured_amount': self.order.total.gross,**get_billing_data(self.order)}- PaymentMethod.objects.get_or_create(+ Payment.objects.get_or_create(variant=CustomPaymentChoices.MANUAL,charge_status=ChargeStatus.CHARGED, order=self.order,defaults=defaults)diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex a26e86a34e..69b00e26fe 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -44,7 +44,7 @@ from .utils import (@staff_member_required@permission_required('order.manage_orders')def order_list(request):- orders = Order.objects.prefetch_related('payment_methods', 'lines', 'user')+ orders = Order.objects.prefetch_related('payments', 'lines', 'user')order_filter = OrderFilter(request.GET, queryset=orders)orders = get_paginator_items(order_filter.qs, settings.DASHBOARD_PAGINATE_BY,@@ -119,10 +119,10 @@ def remove_draft_order(request, order_pk):def order_details(request, order_pk):qs = Order.objects.select_related('user', 'shipping_address', 'billing_address').prefetch_related(- 'payment_methods', 'events__user', 'lines__variant__product',+ 'payments', 'events__user', 'lines__variant__product','fulfillments__lines__order_line')order = get_object_or_404(qs, pk=order_pk)- all_payments = order.payment_methods.all()+ all_payments = order.payments.all()payment = order.get_last_payment()preauthorized = ZERO_TAXED_MONEYcaptured = ZERO_MONEY@@ -145,7 +145,7 @@ def order_details(request, order_pk):balance = captured - order.total.grosselse:can_capture = can_release = can_refund = False- can_mark_as_paid = not order.payment_methods.exists()+ can_mark_as_paid = not order.payments.exists()ctx = {'order': order, 'all_payments': all_payments, 'payment': payment,'notes': order.events.filter(type=OrderEvents.NOTE_ADDED.value),@@ -184,9 +184,9 @@ def order_add_note(request, order_pk):@staff_member_required@permission_required('order.manage_orders')def capture_payment(request, order_pk, payment_pk):- orders = Order.objects.confirmed().prefetch_related('payment_methods')+ orders = Order.objects.confirmed().prefetch_related('payments')order = get_object_or_404(orders, pk=order_pk)- payment = get_object_or_404(order.payment_methods, pk=payment_pk)+ payment = get_object_or_404(order.payments, pk=payment_pk)amount = order.total.quantize('0.01').grossform = CapturePaymentForm(request.POST or None, payment=payment, initial={'amount': amount})@@ -214,9 +214,9 @@ def capture_payment(request, order_pk, payment_pk):@staff_member_required@permission_required('order.manage_orders')def refund_payment(request, order_pk, payment_pk):- orders = Order.objects.confirmed().prefetch_related('payment_methods')+ orders = Order.objects.confirmed().prefetch_related('payments')order = get_object_or_404(orders, pk=order_pk)- payment = get_object_or_404(order.payment_methods, pk=payment_pk)+ payment = get_object_or_404(order.payments, pk=payment_pk)amount = payment.captured_amountform = RefundPaymentForm(request.POST or None, payment=payment, initial={'amount': amount})@@ -244,9 +244,9 @@ def refund_payment(request, order_pk, payment_pk):@staff_member_required@permission_required('order.manage_orders')def release_payment(request, order_pk, payment_pk):- orders = Order.objects.confirmed().prefetch_related('payment_methods')+ orders = Order.objects.confirmed().prefetch_related('payments')order = get_object_or_404(orders, pk=order_pk)- payment = get_object_or_404(order.payment_methods, pk=payment_pk)+ payment = get_object_or_404(order.payments, pk=payment_pk)form = ReleasePaymentForm(request.POST or None, payment=payment)if form.is_valid() and form.release():msg = pgettext_lazy('Dashboard message', 'Released payment')diff --git a/saleor/dashboard/views.py b/saleor/dashboard/views.pyindex affb23e68a..8d8e5565ea 100644--- a/saleor/dashboard/views.py+++ b/saleor/dashboard/views.py@@ -7,7 +7,7 @@ from django.template.response import TemplateResponsefrom ..order.models import Orderfrom ..payment import ChargeStatus-from ..payment.models import PaymentMethod+from ..payment.models import Paymentfrom ..product.models import Product@@ -36,7 +36,7 @@ def index(request):paginate_by = 10orders_to_ship = Order.objects.ready_to_fulfill().select_related('user').prefetch_related('lines', 'payments')- payments = PaymentMethod.objects.filter(+ payments = Payment.objects.filter(is_active=True, charge_status=ChargeStatus.NOT_CHARGED).order_by('-created')payments = payments.select_related('order', 'order__user')diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 8db1d19706..26ebccd77c 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -46,8 +46,8 @@ from .product.schema import ProductMutations, ProductQueriesfrom .payment.types import Payment, PaymentGatewayEnumfrom .payment.resolvers import resolve_payments, resolve_payment_client_tokenfrom .payment.mutations import (- CheckoutPaymentMethodCreate, PaymentMethodCapture, PaymentMethodRefund,- PaymentMethodVoid)+ CheckoutPaymentCreate, PaymentCapture, PaymentRefund,+ PaymentVoid)from .shipping.resolvers import resolve_shipping_zonesfrom .shipping.types import ShippingZonefrom .shipping.mutations import (@@ -122,7 +122,7 @@ class Query(ProductQueries):Page, query=graphene.String(description=DESCRIPTIONS['page']),description='List of the shop\'s pages.')- payment = graphene.Field(PaymentMethod, id=graphene.Argument(graphene.ID))+ payment = graphene.Field(Payment, id=graphene.Argument(graphene.ID))payment_client_token = graphene.Field(graphene.String, args={'gateway': PaymentGatewayEnum()})payments = DjangoFilterConnectionField(@@ -214,15 +214,15 @@ class Query(ProductQueries):def resolve_orders(self, info, query=None, **kwargs):return resolve_orders(info, query)- def resolve_payment_method(self, info, id):- return graphene.Node.get_node_from_global_id(info, id, PaymentMethod)+ def resolve_payment(self, info, id):+ return graphene.Node.get_node_from_global_id(info, id, Payment)def resolve_payment_client_token(self, info, gateway=None):return resolve_payment_client_token(gateway)@permission_required('order.manage_orders')def resolve_payments(self, info, query=None, **kwargs):- return resolve_payment_methods(info, query)+ return resolve_payments(info, query)@login_requireddef resolve_orders(@@ -301,7 +301,7 @@ class Mutations(ProductMutations):checkout_shipping_address_update = CheckoutShippingAddressUpdate.Field()checkout_shipping_method_update = CheckoutShippingMethodUpdate.Field()checkout_email_update = CheckoutEmailUpdate.Field()- checkout_payment_method_create = CheckoutPaymentMethodCreate.Field()+ checkout_payment_create = CheckoutPaymentCreate.Field()checkout_complete = CheckoutComplete.Field()menu_create = MenuCreate.Field()diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 81c88b9da7..405c954488 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -6,7 +6,8 @@ from ....core.utils.taxes import ZERO_TAXED_MONEYfrom ....order import CustomPaymentChoices, OrderEvents, modelsfrom ....order.utils import cancel_orderfrom ....payment import ChargeStatus, PaymentError-from ....payment.models import PaymentMethod+from ....payment.models import Payment+from ....payment.utils import get_billing_datafrom ....shipping.models import ShippingMethod as ShippingMethodModelfrom ...account.types import AddressInputfrom ...core.mutations import BaseMutation@@ -58,7 +59,7 @@ def clean_order_cancel(order, errors):def clean_order_mark_as_paid(order, errors):- if order and order.payment_methods.exists():+ if order and order.payments.exists():errors.append(Error(field='payment',@@ -292,7 +293,7 @@ class OrderMarkAsPaid(BaseMutation):defaults = {'total': order.total.gross, 'captured_amount': order.total.gross,**get_billing_data(order)}- PaymentMethod.objects.get_or_create(+ Payment.objects.get_or_create(variant=CustomPaymentChoices.MANUAL,charge_status=ChargeStatus.CHARGED, order=order,defaults=defaults)diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 287f14e7ab..d78da9a4a3 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -5,17 +5,17 @@ from prices import Money, TaxedMoneyfrom ...payment import PaymentErrorfrom ...payment.utils import (- create_payment_method, gateway_authorize, gateway_capture, gateway_refund,+ create_payment, gateway_authorize, gateway_capture, gateway_refund,gateway_void)from ..account.i18n import I18nMixinfrom ..account.types import AddressInputfrom ..checkout.types import Checkoutfrom ..core.mutations import BaseMutationfrom ..core.types.common import Decimal-from .types import PaymentGatewayEnum, PaymentMethod+from .types import Payment, PaymentGatewayEnum-class PaymentMethodInput(graphene.InputObjectType):+class PaymentInput(graphene.InputObjectType):gateway = PaymentGatewayEnum()checkout_id = graphene.ID(description='Checkout ID.')transaction_token = graphene.String(@@ -28,13 +28,11 @@ class PaymentMethodInput(graphene.InputObjectType):billing_address = AddressInput(description='Billing address')-class CheckoutPaymentMethodCreate(BaseMutation, I18nMixin):- payment_method = graphene.Field(- PaymentMethod, description='Updated payment method')+class CheckoutPaymentCreate(BaseMutation, I18nMixin):+ payment = graphene.Field(Payment, description='Updated payment')class Arguments:- input = PaymentMethodInput(- required=True, description='Payment method details')+ input = PaymentInput(required=True, description='Payment details')class Meta:description = 'Creates credit card transaction.'@@ -44,35 +42,39 @@ class CheckoutPaymentMethodCreate(BaseMutation, I18nMixin):# FIXME: improve error handlingerrors = []checkout = cls.get_node_or_error(- info, input['checkout_id'], errors, 'checkout_id',+ info,+ input['checkout_id'],+ errors,+ 'checkout_id',only_type=Checkout)if not checkout:- return CheckoutPaymentMethodCreate(errors=errors)+ return CheckoutPaymentCreate(errors=errors)billing_data = {}if input['billing_address']:billing_address, errors = cls.validate_address(input['billing_address'], errors, 'billing_address')if not billing_address:- return CheckoutPaymentMethodCreate(errors=errors)+ return CheckoutPaymentCreate(errors=errors)billing_data = cls.clean_billing_address(billing_address)extra_data = cls.get_extra_info(info)gross = Money(input['amount'], currency=settings.DEFAULT_CURRENCY)- payment_method = create_payment_method(+ payment = create_payment(total=gross,- variant=input['gateway'], billing_email=checkout.email,- extra_data=extra_data, checkout=checkout,+ variant=input['gateway'],+ billing_email=checkout.email,+ extra_data=extra_data,+ checkout=checkout,**billing_data)# authorize paymenttry:- gateway_authorize(payment_method, input['transaction_token'])+ gateway_authorize(payment, input['transaction_token'])except PaymentError as exc:msg = str(exc)cls.add_error(field=None, message=msg, errors=errors)- return CheckoutPaymentMethodCreate(- payment_method=payment_method, errors=errors)+ return CheckoutPaymentCreate(payment=payment, errors=errors)@classmethoddef clean_billing_address(cls, billing_address):@@ -99,13 +101,11 @@ class CheckoutPaymentMethodCreate(BaseMutation, I18nMixin):'customer_user_agent': user_agent}-class PaymentMethodCapture(BaseMutation):- payment_method = graphene.Field(- PaymentMethod, description='Updated payment method')+class PaymentCapture(BaseMutation):+ payment = graphene.Field(Payment, description='Updated payment')class Arguments:- payment_method_id = graphene.ID(- required=True, description='Payment method ID')+ payment_id = graphene.ID(required=True, description='Payment ID')amount = Decimal(description='Transaction amount')class Meta:@@ -113,73 +113,66 @@ class PaymentMethodCapture(BaseMutation):@classmethod@permission_required('order.manage_orders')- def mutate(cls, root, info, payment_method_id, amount=None):+ def mutate(cls, root, info, payment_id, amount=None):errors = []- payment_method = cls.get_node_or_error(- info, payment_method_id, errors, 'payment_method_id',- only_type=PaymentMethod)+ payment = cls.get_node_or_error(+ info, payment_id, errors, 'payment_id', only_type=Payment)- if not payment_method:- return PaymentMethodCapture(errors=errors)+ if not payment:+ return PaymentCapture(errors=errors)try:- gateway_capture(payment_method, amount)+ gateway_capture(payment, amount)except PaymentError as exc:msg = str(exc)cls.add_error(field=None, message=msg, errors=errors)- return PaymentMethodCapture(- payment_method=payment_method, errors=errors)+ return PaymentCapture(payment=payment, errors=errors)-class PaymentMethodRefund(PaymentMethodCapture):+class PaymentRefund(PaymentCapture):@classmethod@permission_required('order.manage_orders')- def mutate(cls, root, info, payment_method_id, amount=None):+ def mutate(cls, root, info, payment_id, amount=None):errors = []- payment_method = cls.get_node_or_error(- info, payment_method_id, errors, 'payment_method_id',- only_type=PaymentMethod)+ payment = cls.get_node_or_error(+ info, payment_id, errors, 'payment_id', only_type=Payment)- if not payment_method:- return PaymentMethodRefund(errors=errors)+ if not payment:+ return PaymentRefund(errors=errors)try:- gateway_refund(payment_method, amount=amount)+ gateway_refund(payment, amount=amount)except PaymentError as exc:msg = str(exc)cls.add_error(field=None, message=msg, errors=errors)- return PaymentMethodRefund(- payment_method=payment_method, errors=errors)+ return PaymentRefund(payment=payment, errors=errors)class Meta:description = 'Refunds the captured payment amount'-class PaymentMethodVoid(BaseMutation):- payment_method = graphene.Field(- PaymentMethod, description='Updated payment method')+class PaymentVoid(BaseMutation):+ payment = graphene.Field(Payment, description='Updated payment')class Arguments:- payment_method_id = graphene.ID(- required=True, description='Payment method ID')+ payment_id = graphene.ID(required=True, description='Payment ID')class Meta:description = 'Voids the authorized payment'@classmethod@permission_required('order.manage_orders')- def mutate(cls, root, info, payment_method_id, amount=None):+ def mutate(cls, root, info, payment_id, amount=None):errors = []- payment_method = cls.get_node_or_error(- info, payment_method_id, errors, 'payment_method_id',- only_type=PaymentMethod)+ payment = cls.get_node_or_error(+ info, payment_id, errors, 'payment_id', only_type=Payment)- if not payment_method:- return PaymentMethodVoid(errors=errors)+ if not payment:+ return PaymentVoid(errors=errors)try:- gateway_void(payment_method)+ gateway_void(payment)except PaymentError as exc:msg = str(exc)cls.add_error(field=None, message=msg, errors=errors)- return PaymentMethodVoid(payment_method=payment_method, errors=errors)+ return PaymentVoid(payment=payment, errors=errors)diff --git a/saleor/graphql/payment/resolvers.py b/saleor/graphql/payment/resolvers.pyindex 0bbf69240b..9b233eca9a 100644--- a/saleor/graphql/payment/resolvers.py+++ b/saleor/graphql/payment/resolvers.py@@ -5,9 +5,9 @@ from ..utils import filter_by_query_paramPAYMENT_SEARCH_FIELDS = ['id']-def resolve_payment_methods(info, query):+def resolve_payments(info, query):# FIXME Add tests- queryset = models.PaymentMethod.objects.all().distinct()+ queryset = models.Payment.objects.all().distinct()queryset = filter_by_query_param(queryset, query, PAYMENT_SEARCH_FIELDS)return querysetdiff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.pyindex 7b5d988366..eab80cda42 100644--- a/saleor/graphql/payment/types.py+++ b/saleor/graphql/payment/types.py@@ -11,15 +11,17 @@ PaymentChargeStatusEnum = graphene.Enum([(str_to_enum(code.upper()), code) for code, name in ChargeStatus.CHOICES])-class PaymentMethod(CountableDjangoObjectType):+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)class Meta:- description = 'Represents a payment method of a given type.'+ description = 'Represents a payment of a given type.'interfaces = [relay.Node]- model = models.PaymentMethod+ model = models.Paymentfilter_fields = ['id']diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 0bfb7fbab1..d8861cba78 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -295,7 +295,7 @@ type Checkout implements Node {translatedDiscountName: StringvoucherCode: Stringlines: [CheckoutLine]- paymentMethods(before: String, after: String, first: Int, last: Int, id: ID): PaymentMethodCountableConnection+ payments(before: String, after: String, first: Int, last: Int, id: ID): PaymentCountableConnectionid: ID!totalPrice: TaxedMoneysubtotalPrice: TaxedMoney@@ -389,9 +389,9 @@ type CheckoutLinesUpdate {checkout: Checkout}-type CheckoutPaymentMethodCreate {+type CheckoutPaymentCreate {errors: [Error]- paymentMethod: PaymentMethod+ payment: Payment}type CheckoutShippingAddressUpdate {@@ -872,7 +872,7 @@ type Mutations {checkoutShippingAddressUpdate(checkoutId: ID, shippingAddress: AddressInput): CheckoutShippingAddressUpdatecheckoutShippingMethodUpdate(checkoutId: ID, shippingMethodId: ID!): CheckoutShippingMethodUpdatecheckoutEmailUpdate(checkoutId: ID, email: String!): CheckoutEmailUpdate- checkoutPaymentMethodCreate(input: PaymentMethodInput!): CheckoutPaymentMethodCreate+ checkoutPaymentCreate(input: PaymentInput!): CheckoutPaymentCreatecheckoutComplete(checkoutId: ID): CheckoutCompletemenuCreate(input: MenuCreateInput!): MenuCreatemenuDelete(id: ID!): MenuDelete@@ -904,9 +904,10 @@ type Mutations {attributeCreate(id: ID!, input: AttributeCreateInput!, type: AttributeTypeEnum!): AttributeCreateattributeDelete(id: ID!): AttributeDeleteattributeUpdate(id: ID!, input: AttributeUpdateInput!): AttributeUpdate- paymentMethodCapture(amount: Decimal, paymentMethodId: ID!): PaymentMethodCapture- paymentMethodRefund(amount: Decimal, paymentMethodId: ID!): PaymentMethodRefund- paymentMethodVoid(paymentMethodId: ID!): PaymentMethodVoid+ paymentCapture(amount: Decimal, paymentId: ID!): PaymentCapture+ paymentRefund(amount: Decitmal, paymentId: ID!): PaymentRefund+ paymentVoid(paymentId: ID!): PaymentVoid+>>>>>>> Rename PaymentMethod to PaymentsaleCreate(input: SaleInput!): SaleCreatesaleDelete(id: ID!): SaleDeletesaleUpdate(id: ID!, input: SaleInput!): SaleUpdate@@ -915,7 +916,6 @@ type Mutations {homepageCollectionUpdate(collection: ID): HomepageCollectionUpdatevoucherCreate(input: VoucherInput!): VoucherCreatevoucherDelete(id: ID!): VoucherDelete- voucherUpdate(id: ID!, input: VoucherInput!): VoucherUpdateshippingZoneCreate(input: ShippingZoneInput!): ShippingZoneCreateshippingZoneDelete(id: ID!): ShippingZoneDeleteshippingZoneUpdate(id: ID!, input: ShippingZoneInput!): ShippingZoneUpdate@@ -963,7 +963,7 @@ type Order implements Node {lines: [OrderLine]!fulfillments: [Fulfillment]!events: [OrderEvent]- paymentMethods(before: String, after: String, first: Int, last: Int, id: ID): PaymentMethodCountableConnection+ payments(before: String, after: String, first: Int, last: Int, id: ID): PaymentCountableConnectionisPaid: Booleannumber: StringpaymentStatus: PaymentChargeStatusEnum@@ -1204,7 +1204,7 @@ enum PaymentChargeStatusEnum {FULLY_REFUNDED}-type PaymentMethod implements Node {+type Payment implements Node {id: ID!variant: String!isActive: Boolean!@@ -1232,23 +1232,23 @@ type PaymentMethod implements Node {transactions(before: String, after: String, first: Int, last: Int, id: ID): TransactionCountableConnection}-type PaymentMethodCapture {+type PaymentCapture {errors: [Error]- paymentMethod: PaymentMethod+ payment: Payment}-type PaymentMethodCountableConnection {+type PaymentCountableConnection {pageInfo: PageInfo!- edges: [PaymentMethodCountableEdge!]!+ edges: [PaymentCountableEdge!]!totalCount: Int}-type PaymentMethodCountableEdge {- node: PaymentMethod!+type PaymentCountableEdge {+ node: Payment!cursor: String!}-input PaymentMethodInput {+input PaymentInput {gateway: ProvidersEnumcheckoutId: IDtransactionToken: String!@@ -1257,14 +1257,14 @@ input PaymentMethodInput {billingAddress: AddressInput}-type PaymentMethodRefund {+type PaymentRefund {errors: [Error]- paymentMethod: PaymentMethod+ payment: Payment}-type PaymentMethodVoid {+type PaymentVoid {errors: [Error]- paymentMethod: PaymentMethod+ payment: Payment}type PermissionDisplay {@@ -1886,7 +1886,7 @@ type TaxedMoneyRange {type Transaction implements Node {id: ID!created: DateTime!- paymentMethod: PaymentMethod!+ payment: Payment!token: String!transactionType: TransactionTransactionType!isSuccess: Boolean!diff --git a/saleor/order/forms.py b/saleor/order/forms.pyindex eaf148e9ee..993fe9ee32 100644--- a/saleor/order/forms.py+++ b/saleor/order/forms.py@@ -4,13 +4,13 @@ from django.utils.translation import pgettext_lazyfrom ..account.forms import SignupFormfrom ..payment import can_be_voided-from ..payment.models import PaymentMethod+from ..payment.models import Paymentfrom .models import Order-class PaymentMethodsForm(forms.Form):+class PaymentsForm(forms.Form):method = forms.ChoiceField(- label=pgettext_lazy('Payment methods form label', 'Method'),+ label=pgettext_lazy('Payments form label', 'Method'),choices=settings.CHECKOUT_PAYMENT_CHOICES, widget=forms.RadioSelect,initial=settings.CHECKOUT_PAYMENT_CHOICES[0][0])@@ -25,7 +25,7 @@ class PaymentDeleteForm(forms.Form):def clean(self):cleaned_data = super().clean()payment_id = cleaned_data.get('payment_id')- payment = PaymentMethod.objects.filter(is_active=True).first(+ payment = Payment.objects.filter(is_active=True).first(id=payment_id)if not payment:self._errors['number'] = self.error_class([diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 5a79d93f80..c2835a87c5 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -43,8 +43,8 @@ class OrderQueryset(models.QuerySet):fulfilled)."""statuses = {OrderStatus.UNFULFILLED, OrderStatus.PARTIALLY_FULFILLED}- qs = self.filter(status__in=statuses, payment_methods__is_active=True)- qs = qs.annotate(amount_paid=Sum('payment_methods__captured_amount'))+ qs = self.filter(status__in=statuses, payments__is_active=True)+ qs = qs.annotate(amount_paid=Sum('payments__captured_amount'))return qs.filter(total_gross__lte=F('amount_paid'))def ready_to_capture(self):@@ -132,7 +132,7 @@ class Order(models.Model):return super().save(*args, **kwargs)def is_fully_paid(self):- payments = self.payment_methods.filter(+ payments = self.payments.filter(charge_status=ChargeStatus.CHARGED)total_captured = [payment.captured_amount for payment in payments]total_paid = sum(total_captured, ZERO_TAXED_MONEY)@@ -160,7 +160,7 @@ class Order(models.Model):return reverse('order:details', kwargs={'token': self.token})def get_last_payment(self):- return max(self.payment_methods.all(), default=None, key=attrgetter('pk'))+ return max(self.payments.all(), default=None, key=attrgetter('pk'))def get_last_payment_status(self):last_payment = self.get_last_payment()@@ -170,7 +170,7 @@ class Order(models.Model):def get_last_payment_status_display(self):last_payment = max(- self.payment_methods.all(), default=None, key=attrgetter('pk'))+ self.payments.all(), default=None, key=attrgetter('pk'))if last_payment:return last_payment.get_charge_status_display()return None@@ -179,7 +179,7 @@ class Order(models.Model):# 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 self.payment_methods.filter(is_active=True).exists()+ return self.payments.filter(is_active=True).exists()@propertydef quantity_fulfilled(self):diff --git a/saleor/order/views.py b/saleor/order/views.pyindex 66f32ce83e..6cebed543e 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -16,11 +16,11 @@ from ..account.forms import LoginFormfrom ..account.models import Userfrom ..core.utils import get_client_ipfrom ..payment import ChargeStatus-from ..payment.forms import PaymentMethodForm-from ..payment.models import PaymentMethod+from ..payment.forms import PaymentForm+from ..payment.models import Paymentfrom ..payment.utils import get_billing_datafrom .forms import (- CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentMethodsForm)+ CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentsForm)from .models import Orderfrom .utils import attach_order_to_user, check_order_status@@ -55,13 +55,13 @@ def payment(request, token):orders = orders.select_related('billing_address', 'shipping_address', 'user')order = get_object_or_404(orders, token=token)- payments = order.payment_methods.all()+ payments = order.payments.all()form_data = request.POST or Nonetry:waiting_payment = payments.filter(is_active=True,charge_status=ChargeStatus.NOT_CHARGED).get()- except PaymentMethod.DoesNotExist:+ except Payment.DoesNotExist:waiting_payment = Nonewaiting_payment_form = Noneelse:@@ -72,12 +72,12 @@ def payment(request, token):form_data = Nonepayment_form = Noneif not order.is_pre_authorized():- payment_form = PaymentMethodsForm(form_data)- # FIXME: redirect if there is only one payment method+ payment_form = PaymentsForm(form_data)+ # FIXME: redirect if there is only one paymentif payment_form.is_valid():- payment_method = payment_form.cleaned_data['method']+ payment = payment_form.cleaned_data['method']return redirect(- 'order:payment', token=order.token, variant=payment_method)+ 'order:payment', token=order.token, variant=payment)ctx = {'order': order, 'payment_form': payment_form, 'payments': payments,'waiting_payment': waiting_payment,@@ -96,17 +96,17 @@ def start_payment(request, order, variant):raise Http404('%r is not a valid payment variant' % (variant,))with transaction.atomic():# FIXME: temporary solution, should be adapted to new API- payment_method, _ = PaymentMethod.objects.get_or_create(+ payment, _ = Payment.objects.get_or_create(variant=variant, is_active=True, order=order, defaults=defaults)- form = PaymentMethodForm(- data=request.POST or None, instance=payment_method)+ form = PaymentForm(+ data=request.POST or None, instance=payment)form.method = "POST"if form.is_valid():form.save()form.authorize_payment()return redirect(order.get_absolute_url())template = 'order/payment/%s.html' % variant- ctx = {'form': form, 'payment': payment_method}+ ctx = {'form': form, 'payment': payment}return TemplateResponse(request, [template, 'order/payment/default.html'], ctx)diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex fd6c20726e..af79e0c062 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -51,11 +51,9 @@ class ChargeStatus:# partially refundedCHOICES = [- (CHARGED, pgettext_lazy('payment method status', 'Charged')),- (NOT_CHARGED, pgettext_lazy('payment method status', 'Not charged')),- (- FULLY_REFUNDED,- pgettext_lazy('payment method status', 'Fully refunded'))]+ (CHARGED, pgettext_lazy('payment status', 'Charged')),+ (NOT_CHARGED, pgettext_lazy('payment status', 'Not charged')),+ (FULLY_REFUNDED, pgettext_lazy('payment status', 'Fully refunded'))]PROVIDERS_ENUM = Enum(diff --git a/saleor/payment/forms.py b/saleor/payment/forms.pyindex f569b96a42..0d598b50cf 100644--- a/saleor/payment/forms.py+++ b/saleor/payment/forms.py@@ -1,16 +1,17 @@from django import formsfrom . import TransactionType-from .models import PaymentMethod+from .models import Payment-class PaymentMethodForm(forms.ModelForm):+class PaymentForm(forms.ModelForm):class Meta:- model = PaymentMethod+ model = Paymentfields = ['variant', 'is_active', 'charge_status']def authorize_payment(self):self.instance.transactions.create(amount=self.instance.total,transaction_type=TransactionType.AUTH,- gateway_response={}, is_success=True)+ gateway_response={},+ is_success=True)diff --git a/saleor/payment/migrations/0003_rename_payment_method_to_payment.py b/saleor/payment/migrations/0003_rename_payment_method_to_payment.pynew file mode 100644index 0000000000..a8e6c7f444--- /dev/null+++ b/saleor/payment/migrations/0003_rename_payment_method_to_payment.py@@ -0,0 +1,37 @@+# Generated by Django 2.1.2 on 2018-10-20 16:41++from django.db import migrations, models+import django.db.models.deletion+import django_prices.models+import saleor.core+++class Migration(migrations.Migration):++ dependencies = [+ ('order', '0065_auto_20181017_1633'),+ ('checkout', '0015_auto_20181017_1346'),+ ('payment', '0002_transfer_payment_to_payment_method'),+ ]++ operations = [+ migrations.RenameModel(+ old_name='PaymentMethod',+ new_name='Payment',+ ),+ migrations.RenameField(+ model_name='transaction',+ old_name='payment_method',+ new_name='payment',+ ),+ migrations.AlterField(+ model_name='payment',+ name='checkout',+ field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='payments', to='checkout.Cart'),+ ),+ migrations.AlterField(+ model_name='payment',+ name='order',+ field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='payments', to='order.Order'),+ ),+ ]diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex 13358cbcc5..ec8e55d660 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -9,7 +9,7 @@ from ..core import zero_moneyfrom ..order.models import Order-class PaymentMethod(models.Model):+class Payment(models.Model):"""Represents transactable payment informationsuch as credit card details, gift card information or a customer'sauthorization to charge their PayPal account.@@ -18,8 +18,7 @@ class PaymentMethod(models.Model):at the gateway level, we are operating on the reusable tokenwhich is a unique identifier of the customer for given gateway.- Payment methods belong to a customer, one can use several payments method- within a single order.+ Several payment methods can be used within a single order."""#FIXME we should provide an option to store the card for later usagevariant = models.CharField(max_length=255)@@ -51,20 +50,20 @@ class PaymentMethod(models.Model):token = models.CharField(max_length=36, blank=True, default='')total = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES,default=zero_money)captured_amount = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES,default=zero_money)checkout = models.ForeignKey(- Cart, null=True, related_name='payment_methods',- on_delete=models.SET_NULL)+ Cart, null=True, related_name='payments', on_delete=models.SET_NULL)order = models.ForeignKey(- Order, null=True, related_name='payment_methods',- on_delete=models.PROTECT)+ Order, null=True, related_name='payments', on_delete=models.PROTECT)def get_auth_transaction(self):txn = self.transactions.get(@@ -76,25 +75,25 @@ class PaymentMethod(models.Model):# dashboard 2.0from . import utilsreturn utils.gateway_authorize(- payment_method=self, transaction_token=client_token)+ payment=self, transaction_token=client_token)def void(self):# FIXME Used for backwards compatibility, remove after moving to# dashboard 2.0from . import utils- return utils.gateway_void(payment_method=self)+ return utils.gateway_void(payment=self)def capture(self, amount=None):# FIXME Used for backwards compatibility, remove after moving to# dashboard 2.0from . import utils- return utils.gateway_capture(payment_method=self, amount=amount)+ return utils.gateway_capture(payment=self, amount=amount)def refund(self, amount=None):# FIXME Used for backwards compatibility, remove after moving to# dashboard 2.0from . import utils- return utils.gateway_refund(payment_method=self, amount=amount)+ return utils.gateway_refund(payment=self, amount=amount)class Transaction(models.Model):@@ -102,8 +101,8 @@ class Transaction(models.Model):and your customers, with a chosen payment method."""created = models.DateTimeField(auto_now_add=True, editable=False)- payment_method = models.ForeignKey(- PaymentMethod, related_name='transactions', on_delete=models.PROTECT)+ payment = models.ForeignKey(+ Payment, related_name='transactions', on_delete=models.PROTECT)token = models.CharField(max_length=64, blank=True, default='')transaction_type = models.CharField(max_length=10, choices=TransactionType.CHOICES)@@ -111,7 +110,8 @@ class Transaction(models.Model):# a bool, eg for payments with 3d secureis_success = models.BooleanField(default=False)amount = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES,default=zero_money)diff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.pyindex af45f1d0ee..ad4e02e881 100644--- a/saleor/payment/providers/braintree/__init__.py+++ b/saleor/payment/providers/braintree/__init__.py@@ -16,6 +16,7 @@ THREE_D_SECURE_REQUIRED = Falsedef get_customer_data(payment):+ # FIXME: TESTMEreturn {'billing': {'first_name': payment.billing_first_name,@@ -28,8 +29,7 @@ def get_customer_data(payment):'region': payment.billing_country_area,'country_code_alpha2': payment.billing_country_code},'risk_data': {- 'customer_ip': payment.customer_ip_address or ''- },+ 'customer_ip': payment.customer_ip_address or ''},'customer': {'email': payment.billing_email}}@@ -38,6 +38,7 @@ def get_error_for_client(errors):"""Filters all error messages and decides which one is visible for theclient side."""+ # FIXME: TESTMEif not errors:return ''@@ -55,12 +56,14 @@ def get_error_for_client(errors):def extract_gateway_response(braintree_result) -> Dict:+ # FIXME: TESTME"""Extract data from Braintree response that will be stored locally."""errors = []if not braintree_result.is_success:- errors = [- {'code': error.code, 'message': error.message}- for error in braintree_result.errors.deep_errors]+ errors = [{+ 'code': error.code,+ 'message': error.message}+ for error in braintree_result.errors.deep_errors]bt_transaction = braintree_result.transactionif not bt_transaction:return {'errors': errors}@@ -79,6 +82,7 @@ def extract_gateway_response(braintree_result) -> Dict:def get_gateway(sandbox_mode, merchant_id, public_key, private_key):+ # FIXME: TESTMEif not all([merchant_id, private_key, public_key]):raise ImproperlyConfigured('Incorrectly configured Braintree gateway.')environment = braintree_sdk.Environment.Sandbox@@ -95,47 +99,51 @@ def get_gateway(sandbox_mode, merchant_id, public_key, private_key):def get_client_token(**client_kwargs):+ # FIXME: TESTMEgateway = get_gateway(**client_kwargs)client_token = gateway.client_token.generate()return client_token-def authorize(payment_method, transaction_token, **client_kwargs):+def authorize(payment, transaction_token, **client_kwargs):+ # FIXME: TESTMEgateway = get_gateway(**client_kwargs)result = gateway.transaction.sale({- 'amount': str(payment_method.total.amount),+ 'amount': str(payment.total.amount),'payment_method_nonce': transaction_token,'options': {'submit_for_settlement': CONFIRM_MANUALLY,- 'three_d_secure': {'required': THREE_D_SECURE_REQUIRED}},- **get_customer_data(payment_method)})+ 'three_d_secure': {+ 'required': THREE_D_SECURE_REQUIRED}},+ **get_customer_data(payment)})gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])txn = create_transaction(- payment_method=payment_method,+ payment=payment,transaction_type=TransactionType.AUTH,- amount=payment_method.total.amount,+ amount=payment.total.amount,gateway_response=gateway_response,token=getattr(result.transaction, 'id', ''),is_success=result.is_success)return txn, error-def capture(payment_method, amount=None, **client_kwargs):+def capture(payment, amount=None, **client_kwargs):gateway = get_gateway(**client_kwargs)# FIXME we are assuming that appropriate transaction exists without# forcing the flow- auth_transaction = payment_method.transactions.filter(+ # FIXME: TESTME+ auth_transaction = payment.transactions.filter(transaction_type=TransactionType.AUTH).first()if not amount:- amount = payment_method.total.amount+ amount = payment.total.amountresult = gateway.transaction.submit_for_settlement(transaction_id=auth_transaction.token, amount=amount)gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])txn = create_transaction(- payment_method=payment_method,+ payment=payment,transaction_type=TransactionType.CAPTURE,amount=amount,token=result.transaction.id,@@ -144,37 +152,39 @@ def capture(payment_method, amount=None, **client_kwargs):return txn, error-def void(payment_method, **client_kwargs):+def void(payment, **client_kwargs):gateway = get_gateway(**client_kwargs)# FIXME we are assuming that appropriate transaction exists without# forcing the flow- auth_transaction = payment_method.transactions.filter(+ # FIXME: TESTME+ auth_transaction = payment.transactions.filter(transaction_type=TransactionType.AUTH).first()result = gateway.transaction.void(transaction_id=auth_transaction.token)gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])txn = create_transaction(- payment_method=payment_method,+ payment=payment,transaction_type=TransactionType.VOID,- amount=payment_method.total.amount,+ amount=payment.total.amount,gateway_response=gateway_response,token=result.transaction.id,is_success=result.is_success)return txn, error-def refund(payment_method, amount=None, **client_kwargs):+def refund(payment, amount=None, **client_kwargs):gateway = get_gateway(**client_kwargs)# FIXME we are assuming that appropriate transaction exists without# forcing the flow- auth_transaction = payment_method.transactions.filter(+ # FIXME: TESTME+ auth_transaction = payment.transactions.filter(transaction_type=TransactionType.CAPTURE).first()result = gateway.transaction.refund(transaction_id=auth_transaction.token, amount=amount)gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])txn = create_transaction(- payment_method=payment_method,+ payment=payment,transaction_type=TransactionType.REFUND,amount=amount,token=result.transaction.id,diff --git a/saleor/payment/providers/dummy/__init__.py b/saleor/payment/providers/dummy/__init__.pyindex b2776f58e0..3e9102fead 100644--- a/saleor/payment/providers/dummy/__init__.py+++ b/saleor/payment/providers/dummy/__init__.py@@ -12,43 +12,43 @@ def get_client_token(**client_kwargs):return str(uuid.uuid4())-def authorize(payment_method, transaction_token, **client_kwargs):+def authorize(payment, transaction_token, **client_kwargs):success = dummy_success()error = Noneif not success:error = 'Unable to authorize transaction'txn = create_transaction(- payment_method=payment_method,+ payment=payment,transaction_type=TransactionType.AUTH,- amount=payment_method.total,+ amount=payment.total,gateway_response={},token=str(uuid.uuid4()),is_success=success)return txn, error-def void(payment_method, **client_kwargs):+def void(payment, **client_kwargs):error = Nonesuccess = dummy_success()if not success:error = 'Unable to void transaction'txn = create_transaction(- payment_method=payment_method,+ payment=payment,transaction_type=TransactionType.VOID,- amount=payment_method.total,+ amount=payment.total,gateway_response={},token=str(uuid.uuid4()),is_success=success)return txn, error-def capture(payment_method, amount=None):+def capture(payment, amount=None):error = Nonesuccess = dummy_success()if not success:error = 'Unable to process capture'txn = create_transaction(- payment_method=payment_method,+ payment=payment,transaction_type=TransactionType.CAPTURE,amount=amount,token=str(uuid.uuid4()),@@ -56,13 +56,13 @@ def capture(payment_method, amount=None):return txn, error-def refund(payment_method, amount=None):+def refund(payment, amount=None):error = Nonesuccess = dummy_success()if not success:error = 'Unable to process refund'txn = create_transaction(- payment_method=payment_method,+ payment=payment,transaction_type=TransactionType.REFUND,amount=amount,token=str(uuid.uuid4()),diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex b9f8cb4ebe..b441d5d350 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -11,7 +11,7 @@ from . import ChargeStatus, PaymentError, can_be_voided, get_providerfrom ..core import analyticsfrom ..order import OrderEvents, OrderEventsEmailsfrom ..order.emails import send_payment_confirmation-from .models import PaymentMethod, Transaction+from .models import Payment, Transactionlogger = logging.getLogger(__name__)@@ -49,34 +49,42 @@ def handle_fully_paid_order(order):logger.exception('Recording order in analytics failed')-def validate_payment_method(view):- """Decorate a view to check if payment method is active, so any actions+def validate_payment(view):+ """Decorate a view to check if payment is authorized, so any actionscan be performed on it."""+@wraps(view)- def func(payment_method, *args, **kwargs):- if not payment_method.is_active:- raise PaymentError('This payment method is no longer active.')- return view(payment_method, *args, **kwargs)+ def func(payment, *args, **kwargs):+ if not payment.is_active:+ raise PaymentError('This payment is no longer authorized.')+ return view(payment, *args, **kwargs)+return func-def create_payment_method(**payment_data):- payment_method, _ = PaymentMethod.objects.get_or_create(**payment_data)- return payment_method+def create_payment(**payment_data):+ payment, _ = Payment.objects.get_or_create(**payment_data)+ return paymentdef create_transaction(- payment_method: PaymentMethod, token: str, transaction_type: str,- is_success: bool, amount: Decimal,+ payment: Payment,+ token: str,+ transaction_type: str,+ is_success: bool,+ amount: Decimal,gateway_response: Optional[Dict] = None) -> Transaction:if not gateway_response:gateway_response = {}txn, _ = Transaction.objects.get_or_create(- payment_method=payment_method, token=token,- transaction_type=transaction_type, is_success=is_success,- amount=amount, gateway_response=gateway_response)+ payment=payment,+ token=token,+ transaction_type=transaction_type,+ is_success=is_success,+ amount=amount,+ gateway_response=gateway_response)return txn@@ -87,52 +95,45 @@ def gateway_get_client_token(provider_name: str):return provider.get_client_token(**provider_params)-@validate_payment_method-def gateway_authorize(- payment_method: PaymentMethod,- transaction_token: str) -> Transaction:- if not payment_method.charge_status == ChargeStatus.NOT_CHARGED:+@validate_payment+def gateway_authorize(payment: Payment, transaction_token: str) -> Transaction:+ if not payment.charge_status == ChargeStatus.NOT_CHARGED:raise PaymentError('Charged transactions cannot be authorized again.')- provider, provider_params = get_provider(payment_method.variant)+ provider, provider_params = get_provider(payment.variant)with transaction.atomic():txn, error = provider.authorize(- payment_method, transaction_token, **provider_params)+ payment, transaction_token, **provider_params)if txn.is_success:- payment_method.charge_status = ChargeStatus.NOT_CHARGED- payment_method.save(update_fields=['charge_status'])+ payment.charge_status = ChargeStatus.NOT_CHARGED+ payment.save(update_fields=['charge_status'])if not txn.is_success:# TODO: Handle gateway response here somehowraise PaymentError(error)return txn-@validate_payment_method-def gateway_capture(- payment_method: PaymentMethod,- amount: Decimal) -> Transaction:+@validate_payment+def gateway_capture(payment: Payment, amount: Decimal) -> Transaction:if amount <= 0:raise PaymentError('Amount should be a positive number.')- if payment_method.charge_status not in {- ChargeStatus.CHARGED,- ChargeStatus.NOT_CHARGED}:- raise PaymentError('This payment method cannot be captured.')- if amount > payment_method.total.amount or amount > (- payment_method.total.amount -- payment_method.captured_amount.amount):+ if payment.charge_status not in {ChargeStatus.CHARGED,+ ChargeStatus.NOT_CHARGED}:+ raise PaymentError('This payment cannot be captured.')+ if amount > payment.total.amount or amount > (+ payment.total.amount - payment.captured_amount.amount):raise PaymentError('Unable to capture more than authorized amount.')- provider, provider_params = get_provider(payment_method.variant)+ provider, provider_params = get_provider(payment.variant)with transaction.atomic():txn, error = provider.capture(- payment_method, amount=amount, **provider_params)+ payment, amount=amount, **provider_params)if txn.is_success:- payment_method.charge_status = ChargeStatus.CHARGED- payment_method.captured_amount += Money(+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount += Money(txn.amount, settings.DEFAULT_CURRENCY)- payment_method.save(- update_fields=['charge_status', 'captured_amount'])- order = payment_method.order+ payment.save(update_fields=['charge_status', 'captured_amount'])+ order = payment.orderif order and order.is_fully_paid():handle_fully_paid_order(order)if not txn.is_success:@@ -141,45 +142,43 @@ def gateway_capture(return txn-@validate_payment_method-def gateway_void(payment_method) -> Transaction:- if not can_be_voided(payment_method):+@validate_payment+def gateway_void(payment) -> Transaction:+ if not can_be_voided(payment):raise PaymentError('Only pre-authorized transactions can be void.')- provider, provider_params = get_provider(payment_method.variant)+ provider, provider_params = get_provider(payment.variant)with transaction.atomic():- txn, error = provider.void(payment_method, **provider_params)+ txn, error = provider.void(payment, **provider_params)if txn.is_success:- payment_method.is_active = False- payment_method.save(update_fields=['is_active'])+ payment.is_active = False+ payment.save(update_fields=['is_active'])if not txn.is_success:raise PaymentError(error)return txn-@validate_payment_method-def gateway_refund(- payment_method,- amount: Decimal) -> Transaction:+@validate_payment+def gateway_refund(payment, amount: Decimal) -> Transaction:if amount <= 0:raise PaymentError('Amount should be a positive number.')- if amount > payment_method.captured_amount.amount:+ if amount > payment.captured_amount.amount:raise PaymentError('Cannot refund more than captured')- if not payment_method.charge_status == ChargeStatus.CHARGED:+ if not payment.charge_status == ChargeStatus.CHARGED:raise PaymentError('Refund is possible only when transaction is captured.')- provider, provider_params = get_provider(payment_method.variant)+ provider, provider_params = get_provider(payment.variant)with transaction.atomic():- txn, error = provider.refund(payment_method, amount, **provider_params)+ txn, error = provider.refund(payment, amount, **provider_params)if txn.is_success:changed_fields = ['captured_amount']- if txn.amount == payment_method.total.amount:- payment_method.charge_status = ChargeStatus.FULLY_REFUNDED- payment_method.is_active = False+ if txn.amount == payment.total.amount:+ payment.charge_status = ChargeStatus.FULLY_REFUNDED+ payment.is_active = Falsechanged_fields += ['charge_status', 'is_active']- payment_method.captured_amount -= Money(+ payment.captured_amount -= Money(txn.amount, settings.DEFAULT_CURRENCY)- payment_method.save(update_fields=changed_fields)+ payment.save(update_fields=changed_fields)if not txn.is_success:raise PaymentError(error)return txndiff --git a/templates/order/payment.html b/templates/order/payment.htmlindex d1c55bc5a3..fce78828e7 100644--- a/templates/order/payment.html+++ b/templates/order/payment.html@@ -73,7 +73,7 @@Pay for order {{ order }}{% endblocktrans %}</h1>- <form method="post" action="{% url "order:payment" token=order.token %}" class="payment-method-form radio">+ <form method="post" action="{% url "order:payment" token=order.token %}" class="payment-form radio">{% csrf_token %}{{ payment_form }}{% block form_submit %}diff --git a/templates/order/payment/default.html b/templates/order/payment/default.htmlindex e7440ca6d8..c81adc6e34 100644--- a/templates/order/payment/default.html+++ b/templates/order/payment/default.html@@ -9,7 +9,7 @@{% bootstrap_form form layout="horizontal" %}{% if form.errors %}<a class="btn" href="{% url "order:details" token=payment.order.token %}">- {% trans "Change payment method" context "Payment form (Stripe) secondary action" %}+ {% trans "Change payment" context "Payment form (Stripe) secondary action" %}</a>{% endif %}{% if not form.autosubmit %}diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 3bb6e87f54..03cd4e2116 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -359,21 +359,21 @@ def test_checkout_email_update(user_api_client, cart_with_item):@pytest.mark.integrationdef test_checkout_complete(- user_api_client, cart_with_item, payment_method_dummy, address,+ user_api_client, cart_with_item, payment_dummy, address,shipping_method):checkout = cart_with_itemcheckout.shipping_address = addresscheckout.shipping_method = shipping_methodcheckout.save()total = checkout.get_total()- payment_method = payment_method_dummy- payment_method.is_active = True- payment_method.order = None- payment_method.total = total.gross- payment_method.captured_amount = total.gross- payment_method.checkout = checkout- payment_method.save()- payment_method.transactions.create(+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross+ payment.captured_amount = total.gross+ payment.checkout = checkout+ payment.save()+ payment.transactions.create(transaction_type=TransactionType.AUTH,is_success=True,gateway_response={},@@ -411,9 +411,9 @@ def test_checkout_complete(assert checkout_line.variant == order_line.variantassert order.shipping_address == addressassert order.shipping_method == checkout.shipping_method- assert order.payment_methods.exists()- order_payment_method = order.payment_methods.first()- assert order_payment_method == payment_method+ assert order.payments.exists()+ order_payment = order.payments.first()+ assert order_payment == paymentdef test_fetch_checkout_by_token(user_api_client, cart_with_item):diff --git a/tests/api/test_order.py b/tests/api/test_order.pyindex 640868c2a3..a2d7fecb77 100644--- a/tests/api/test_order.py+++ b/tests/api/test_order.py@@ -17,7 +17,7 @@ from saleor.graphql.payment.types import PaymentChargeStatusEnumfrom saleor.order import (CustomPaymentChoices, OrderEvents, OrderEventsEmails, OrderStatus)from saleor.order.models import Order, OrderEvent-from saleor.payment.models import PaymentMethod+from saleor.payment.models import Paymentfrom saleor.shipping.models import ShippingMethodfrom .utils import assert_no_permission@@ -895,8 +895,8 @@ def test_order_cancel(def test_order_capture(staff_api_client, permission_manage_orders,- payment_method_txn_preauth, staff_user):- order = payment_method_txn_preauth.order+ payment_txn_preauth, staff_user):+ order = payment_txn_preauth.orderquery = """mutation captureOrder($id: ID!, $amount: Decimal!) {orderCapture(id: $id, amount: $amount) {@@ -911,7 +911,7 @@ def test_order_capture(}"""order_id = graphene.Node.to_global_id('Order', order.id)- amount = float(payment_method_txn_preauth.total.amount)+ amount = float(payment_txn_preauth.total.amount)variables = {'id': order_id, 'amount': amount}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])@@ -938,8 +938,8 @@ def test_order_capture(def test_paid_order_mark_as_paid(staff_api_client, permission_manage_orders,- payment_method_txn_preauth):- order = payment_method_txn_preauth.order+ payment_txn_preauth):+ order = payment_txn_preauth.orderquery = """mutation markPaid($id: ID!) {orderMarkAsPaid(id: $id) {@@ -997,9 +997,9 @@ def test_order_mark_as_paid(def test_order_release(- staff_api_client, permission_manage_orders, payment_method_txn_preauth,+ staff_api_client, permission_manage_orders, payment_txn_preauth,staff_user):- order = payment_method_txn_preauth.order+ order = payment_txn_preauth.orderquery = """mutation releaseOrder($id: ID!) {orderRelease(id: $id) {@@ -1023,8 +1023,8 @@ def test_order_release(def test_order_refund(staff_api_client, permission_manage_orders,- payment_method_txn_captured):- order = order = payment_method_txn_captured.order+ payment_txn_captured):+ order = order = payment_txn_captured.orderquery = """mutation refundOrder($id: ID!, $amount: Decimal!) {orderRefund(id: $id, amount: $amount) {@@ -1037,7 +1037,7 @@ def test_order_refund(}"""order_id = graphene.Node.to_global_id('Order', order.id)- amount = float(payment_method_txn_captured.total.amount)+ amount = float(payment_txn_captured.total.amount)variables = {'id': order_id, 'amount': amount}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])@@ -1054,7 +1054,7 @@ def test_order_refund(def test_clean_order_release_payment():- payment = MagicMock(spec=PaymentMethod)+ payment = MagicMock(spec=Payment)payment.is_active = Falseerrors = clean_release_payment(payment, [])assert errors[0].field == 'payment'@@ -1069,7 +1069,7 @@ def test_clean_order_release_payment():def test_clean_order_refund_payment():- payment = MagicMock(spec=PaymentMethod)+ payment = MagicMock(spec=Payment)payment.variant = CustomPaymentChoices.MANUALamount = Mock(spec='string')errors = clean_refund_payment(payment, amount, [])@@ -1085,8 +1085,8 @@ def test_clean_order_capture():'There\'s no payment associated with the order.')-def test_clean_order_mark_as_paid(payment_method_txn_preauth):- order = payment_method_txn_preauth.order+def test_clean_order_mark_as_paid(payment_txn_preauth):+ order = payment_txn_preauth.ordererrors = clean_order_mark_as_paid(order, [])assert errors[0].field == 'payment'assert errors[0].message == (diff --git a/tests/api/test_payment.py b/tests/api/test_payment.pyindex b8a4547f99..9651af8e50 100644--- a/tests/api/test_payment.py+++ b/tests/api/test_payment.py@@ -5,9 +5,9 @@ from tests.api.utils import get_graphql_contentVOID_QUERY = """- mutation PaymentMethodVoid($paymentMethodId: ID!) {- paymentMethodVoid(paymentMethodId: $paymentMethodId) {- paymentMethod {+ mutation PaymentVoid($paymentId: ID!) {+ paymentVoid(paymentId: $paymentId) {+ payment {id,chargeStatus}@@ -20,53 +20,53 @@ VOID_QUERY = """"""-def test_payment_method_void_success(- staff_api_client, permission_manage_orders, payment_method_dummy):- assert payment_method_dummy.charge_status == ChargeStatus.NOT_CHARGED- payment_method_id = graphene.Node.to_global_id(- 'PaymentMethod', payment_method_dummy.pk)- variables = {'paymentMethodId': payment_method_id}+def test_payment_void_success(+ staff_api_client, permission_manage_orders, payment_dummy):+ assert payment_dummy.charge_status == ChargeStatus.NOT_CHARGED+ payment_id = graphene.Node.to_global_id(+ 'Payment', payment_dummy.pk)+ variables = {'paymentId': payment_id}response = staff_api_client.post_graphql(VOID_QUERY, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content['data']['paymentMethodVoid']+ data = content['data']['paymentVoid']assert not data['errors']- payment_method_dummy.refresh_from_db()- assert payment_method_dummy.is_active == False- assert payment_method_dummy.transactions.count() == 1- txn = payment_method_dummy.transactions.first()+ payment_dummy.refresh_from_db()+ assert payment_dummy.is_active == False+ assert payment_dummy.transactions.count() == 1+ txn = payment_dummy.transactions.first()assert txn.transaction_type == TransactionType.VOID-def test_payment_method_charge_gateway_error(- staff_api_client, permission_manage_orders, payment_method_dummy,+def test_payment_charge_gateway_error(+ staff_api_client, permission_manage_orders, payment_dummy,monkeypatch):- assert payment_method.charge_status == ChargeStatus.NOT_CHARGED- payment_method_id = graphene.Node.to_global_id(- 'PaymentMethod', payment_method_dummy.pk)- variables = {'paymentMethodId': payment_method_id}+ assert payment.charge_status == ChargeStatus.NOT_CHARGED+ payment_id = graphene.Node.to_global_id(+ 'Payment', payment_dummy.pk)+ variables = {'paymentId': payment_id}monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)response = staff_api_client.post_graphql(VOID_QUERY, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content['data']['paymentMethodCapture']+ data = content['data']['paymentCapture']assert data['errors']assert data['errors'][0]['field'] is Noneassert data['errors'][0]['message'] == ('Only pre-authorized transactions can be void.')- payment_method_dummy.refresh_from_db()- assert payment_method_dummy.charge_status == ChargeStatus.NOT_CHARGED- assert payment_method_dummy.is_active == True- assert payment_method_dummy.transactions.count() == 1- txn = payment_method_dummy.transactions.first()+ payment_dummy.refresh_from_db()+ assert payment_dummy.charge_status == ChargeStatus.NOT_CHARGED+ assert payment_dummy.is_active == True+ assert payment_dummy.transactions.count() == 1+ txn = payment_dummy.transactions.first()assert txn.transaction_type == TransactionType.VOIDassert not txn.is_successCREATE_QUERY = """- mutation CheckoutPaymentMethodCreate($input: PaymentMethodInput!) {- checkoutPaymentMethodCreate(input: $input) {- paymentMethod {+ mutation CheckoutPaymentCreate($input: PaymentInput!) {+ checkoutPaymentCreate(input: $input) {+ payment {transactions(first: 1) {edges {node {@@ -86,7 +86,7 @@ CREATE_QUERY = """"""-def test_checkout_add_payment_method(+def test_checkout_add_payment(user_api_client, cart_with_item, graphql_address_data):cart = cart_with_itemassert cart.user is None@@ -102,14 +102,14 @@ def test_checkout_add_payment_method('billingAddress': graphql_address_data}}response = user_api_client.post_graphql(CREATE_QUERY, variables)content = get_graphql_content(response)- data = content['data']['checkoutPaymentMethodCreate']+ data = content['data']['checkoutPaymentCreate']assert not data['errors']- transaction_id = data['paymentMethod']['transactions']['edges'][0]['node'][+ transaction_id = data['payment']['transactions']['edges'][0]['node']['token']txn = Transaction.objects.filter(token=transaction_id).first()assert txn.transaction_type == TransactionType.AUTHassert txn is not None- payment = txn.payment_method+ payment = txn.paymentassert payment.checkout == cartassert payment.is_activeassert payment.total == cart.get_total().gross@@ -117,9 +117,9 @@ def test_checkout_add_payment_method(CHARGE_QUERY = """- mutation PaymentMethodCharge($paymentMethodId: ID!, $amount: Decimal!) {- paymentMethodCapture(paymentMethodId: $paymentMethodId, amount: $amount) {- paymentMethod {+ mutation PaymentCharge($paymentId: ID!, $amount: Decimal!) {+ paymentCapture(paymentId: $paymentId, amount: $amount) {+ payment {id,chargeStatus}@@ -132,60 +132,60 @@ CHARGE_QUERY = """"""-def test_payment_method_charge_success(- staff_api_client, permission_manage_orders, payment_method_dummy):- payment_method = payment_method_dummy- assert payment_method.charge_status == ChargeStatus.NOT_CHARGED- payment_method_id = graphene.Node.to_global_id(- 'PaymentMethod', payment_method_dummy.pk)+def test_payment_charge_success(+ staff_api_client, permission_manage_orders, payment_dummy):+ payment = payment_dummy+ assert payment.charge_status == ChargeStatus.NOT_CHARGED+ payment_id = graphene.Node.to_global_id(+ 'Payment', payment_dummy.pk)variables = {- 'paymentMethodId': payment_method_id,- 'amount': str(payment_method_dummy.total.amount)}+ 'paymentId': payment_id,+ 'amount': str(payment_dummy.total.amount)}response = staff_api_client.post_graphql(CHARGE_QUERY, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content['data']['paymentMethodCapture']+ data = content['data']['paymentCapture']assert not data['errors']- payment_method_dummy.refresh_from_db()- assert payment_method.charge_status == ChargeStatus.CHARGED- assert payment_method.transactions.count() == 1- txn = payment_method.transactions.first()+ payment_dummy.refresh_from_db()+ assert payment.charge_status == ChargeStatus.CHARGED+ assert payment.transactions.count() == 1+ txn = payment.transactions.first()assert txn.transaction_type == TransactionType.CHARGE-def test_payment_method_charge_gateway_error(- staff_api_client, permission_manage_orders, payment_method_dummy,+def test_payment_charge_gateway_error(+ staff_api_client, permission_manage_orders, payment_dummy,monkeypatch):- payment_method = payment_method_dummy- assert payment_method.charge_status == ChargeStatus.NOT_CHARGED- payment_method_id = graphene.Node.to_global_id(- 'PaymentMethod', payment_method_dummy.pk)+ payment = payment_dummy+ assert payment.charge_status == ChargeStatus.NOT_CHARGED+ payment_id = graphene.Node.to_global_id(+ 'Payment', payment_dummy.pk)variables = {- 'paymentMethodId': payment_method_id,- 'amount': str(payment_method_dummy.total.amount)}+ 'paymentId': payment_id,+ 'amount': str(payment_dummy.total.amount)}monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)response = staff_api_client.post_graphql(CHARGE_QUERY, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content['data']['paymentMethodCapture']+ data = content['data']['paymentCapture']assert data['errors']assert data['errors'][0]['field'] is Noneassert data['errors'][0]['message']- payment_method_dummy.refresh_from_db()- assert payment_method.charge_status == ChargeStatus.NOT_CHARGED- assert payment_method.transactions.count() == 1- txn = payment_method.transactions.first()+ payment_dummy.refresh_from_db()+ assert payment.charge_status == ChargeStatus.NOT_CHARGED+ assert payment.transactions.count() == 1+ txn = payment.transactions.first()assert txn.transaction_type == TransactionType.CHARGEassert not txn.is_successREFUND_QUERY = """- mutation PaymentMethodRefund($paymentMethodId: ID!, $amount: Decimal!) {- paymentMethodRefund(paymentMethodId: $paymentMethodId, amount: $amount) {- paymentMethod {+ mutation PaymentRefund($paymentId: ID!, $amount: Decimal!) {+ paymentRefund(paymentId: $paymentId, amount: $amount) {+ payment {id,chargeStatus}@@ -198,62 +198,62 @@ REFUND_QUERY = """"""-def test_payment_method_refund_success(- staff_api_client, permission_manage_orders, payment_method_dummy):- payment_method = payment_method_dummy- payment_method.charge_status = ChargeStatus.CHARGED- payment_method.captured_amount = payment_method.total- payment_method.save()- payment_method_id = graphene.Node.to_global_id(- 'PaymentMethod', payment_method.pk)+def test_payment_refund_success(+ staff_api_client, permission_manage_orders, payment_dummy):+ payment = payment_dummy+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount = payment.total+ payment.save()+ payment_id = graphene.Node.to_global_id(+ 'Payment', payment.pk)variables = {- 'paymentMethodId': payment_method_id,- 'amount': str(payment_method_dummy.total.amount)}+ 'paymentId': payment_id,+ 'amount': str(payment_dummy.total.amount)}response = staff_api_client.post_graphql(REFUND_QUERY, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content['data']['paymentMethodRefund']+ data = content['data']['paymentRefund']assert not data['errors']- payment_method_dummy.refresh_from_db()- assert payment_method.charge_status == ChargeStatus.FULLY_REFUNDED- assert payment_method.transactions.count() == 1- txn = payment_method.transactions.first()+ payment_dummy.refresh_from_db()+ assert payment.charge_status == ChargeStatus.FULLY_REFUNDED+ assert payment.transactions.count() == 1+ txn = payment.transactions.first()assert txn.transaction_type == TransactionType.REFUND-def test_payment_method_refund_error(- staff_api_client, permission_manage_orders, payment_method_dummy,+def test_payment_refund_error(+ staff_api_client, permission_manage_orders, payment_dummy,monkeypatch):- payment_method = payment_method_dummy- payment_method.charge_status = ChargeStatus.CHARGED- payment_method.captured_amount = payment_method.total- payment_method.save()- payment_method_id = graphene.Node.to_global_id(- 'PaymentMethod', payment_method_dummy.pk)+ payment = payment_dummy+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount = payment.total+ payment.save()+ payment_id = graphene.Node.to_global_id(+ 'Payment', payment_dummy.pk)variables = {- 'paymentMethodId': payment_method_id,- 'amount': str(payment_method.total.amount)}+ 'paymentId': payment_id,+ 'amount': str(payment.total.amount)}monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)response = staff_api_client.post_graphql(REFUND_QUERY, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content['data']['paymentMethodRefund']+ data = content['data']['paymentRefund']assert data['errors']assert data['errors'][0]['field'] is Noneassert data['errors'][0]['message']- payment_method_dummy.refresh_from_db()- assert payment_method.charge_status == ChargeStatus.CHARGED- assert payment_method.transactions.count() == 1- txn = payment_method.transactions.first()+ payment_dummy.refresh_from_db()+ assert payment.charge_status == ChargeStatus.CHARGED+ assert payment.transactions.count() == 1+ txn = payment.transactions.first()assert txn.transaction_type == TransactionType.REFUNDassert not txn.is_successdef test_payments_query(- payment_method_dummy, permission_manage_orders, staff_api_client):+ payment_dummy, permission_manage_orders, staff_api_client):query = """ {payments {edges {@@ -269,4 +269,4 @@ def test_payments_query(query, permissions=[permission_manage_orders])content = get_graphql_content(response)data = content['data']['payments']- assert data['edges'][0]['node']['variant'] == payment_method_dummy.variant+ assert data['edges'][0]['node']['variant'] == payment_dummy.variantdiff --git a/tests/conftest.py b/tests/conftest.pyindex 681cc311df..9746381c1d 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -29,7 +29,7 @@ from saleor.order.models import Order, OrderEventfrom saleor.order.utils import recalculate_orderfrom saleor.page.models import Pagefrom saleor.payment import ChargeStatus, TransactionType-from saleor.payment.models import PaymentMethod+from saleor.payment.models import Paymentfrom saleor.product.models import (Attribute, AttributeTranslation, AttributeValue, Category, Collection,Product, ProductImage, ProductTranslation, ProductType, ProductVariant)@@ -468,9 +468,9 @@ def draft_order(order_with_lines):@pytest.fixture()-def payment_method_txn_preauth(order_with_lines, payment_method_dummy):+def payment_txn_preauth(order_with_lines, payment_dummy):order = order_with_lines- payment = payment_method_dummy+ payment = payment_dummypayment.order = orderpayment.save()@@ -483,9 +483,9 @@ def payment_method_txn_preauth(order_with_lines, payment_method_dummy):@pytest.fixture()-def payment_method_txn_captured(order_with_lines, payment_method_dummy):+def payment_txn_captured(order_with_lines, payment_dummy):order = order_with_lines- payment = payment_method_dummy+ payment = payment_dummypayment.order = orderpayment.charge_status = ChargeStatus.CHARGEDpayment.captured_amount = payment.total@@ -500,9 +500,9 @@ def payment_method_txn_captured(order_with_lines, payment_method_dummy):@pytest.fixture()-def payment_method_txn_refunded(order_with_lines, payment_method_dummy):+def payment_txn_refunded(order_with_lines, payment_dummy):order = order_with_lines- payment = payment_method_dummy+ payment = payment_dummypayment.order = orderpayment.charge_status = ChargeStatus.FULLY_REFUNDEDpayment.is_active = False@@ -517,10 +517,10 @@ def payment_method_txn_refunded(order_with_lines, payment_method_dummy):@pytest.fixture()-def payment_method_not_authorized(payment_method_dummy):- payment_method_dummy.is_active = False- payment_method_dummy.save()- return payment_method_dummy+def payment_not_authorized(payment_dummy):+ payment_dummy.is_active = False+ payment_dummy.save()+ return payment_dummy@pytest.fixture()@@ -728,8 +728,8 @@ def product_translation_fr(product):@pytest.fixture-def payment_method_dummy(db, order_with_lines):- return PaymentMethod.objects.create(+def payment_dummy(db, order_with_lines):+ return Payment.objects.create(variant='dummy',order=order_with_lines,is_active=True,diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.pyindex 6671692da0..b3aa1efafc 100644--- a/tests/dashboard/test_order.py+++ b/tests/dashboard/test_order.py@@ -63,9 +63,9 @@ def test_ajax_order_shipping_methods_list_different_country(@pytest.mark.integrationdef test_view_capture_order_payment_preauth(- admin_client, order_with_lines, payment_method_txn_preauth):+ admin_client, order_with_lines, payment_txn_preauth):order = order_with_lines- payment = payment_method_txn_preauth+ payment = payment_txn_preauthurl = reverse('dashboard:capture-payment', kwargs={'order_pk': order.pk, 'payment_pk': payment.pk})@@ -77,68 +77,68 @@ def test_view_capture_order_payment_preauth('csrfmiddlewaretoken': 'hello','amount': str(order.total.gross.amount)})assert response.status_code == 302- payment = order.payment_methods.last()+ payment = order.payments.last()assert payment.charge_status == ChargeStatus.CHARGEDassert payment.captured_amount == order.total.gross@pytest.mark.integrationdef test_view_capture_order_invalid_payment_confirmed_status(- admin_client, order_with_lines, payment_method_txn_captured):+ admin_client, order_with_lines, payment_txn_captured):order = order_with_linesurl = reverse('dashboard:capture-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_method_txn_captured.pk})+ 'order_pk': order.pk, 'payment_pk': payment_txn_captured.pk})response = admin_client.get(url)assert response.status_code == 200response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})assert response.status_code == 400- payment = order.payment_methods.last()+ payment = order.payments.last()assert payment.charge_status == ChargeStatus.CHARGED@pytest.mark.integrationdef test_view_capture_order_invalid_payment_rejected_status(- admin_client, payment_method_not_authorized):- order = payment_method_not_authorized.order+ admin_client, payment_not_authorized):+ order = payment_not_authorized.orderurl = reverse('dashboard:capture-payment', kwargs={'order_pk': order.pk,- 'payment_pk': payment_method_not_authorized.pk})+ 'payment_pk': payment_not_authorized.pk})response = admin_client.get(url)assert response.status_code == 200response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})assert response.status_code == 400- payment = order.payment_methods.last()+ payment = order.payments.last()assert payment.charge_status == ChargeStatus.NOT_CHARGED@pytest.mark.integrationdef test_view_capture_order_invalid_payment_refunded_status(- admin_client, order_with_lines, payment_method_txn_refunded):+ admin_client, order_with_lines, payment_txn_refunded):order = order_with_linesurl = reverse('dashboard:capture-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_method_txn_refunded.pk})+ 'order_pk': order.pk, 'payment_pk': payment_txn_refunded.pk})response = admin_client.get(url)assert response.status_code == 200response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})assert response.status_code == 400- payment = order.payment_methods.last()+ payment = order.payments.last()assert payment.charge_status == ChargeStatus.FULLY_REFUNDED@pytest.mark.integrationdef test_view_refund_order_payment_confirmed(- admin_client, order_with_lines, payment_method_txn_captured):+ admin_client, order_with_lines, payment_txn_captured):order = order_with_lines- payment_confirmed = payment_method_txn_captured+ payment_confirmed = payment_txn_capturedurl = reverse('dashboard:refund-payment', kwargs={'order_pk': order.pk, 'payment_pk': payment_confirmed.pk})@@ -150,62 +150,62 @@ def test_view_refund_order_payment_confirmed('csrfmiddlewaretoken': 'hello','amount': str(payment_confirmed.captured_amount.amount)})assert response.status_code == 302- payment = order.payment_methods.last()+ payment = order.payments.last()assert payment.charge_status == ChargeStatus.FULLY_REFUNDEDassert payment.captured_amount == Money(0, 'USD')@pytest.mark.integrationdef test_view_refund_order_invalid_payment_preauth_status(- admin_client, order_with_lines, payment_method_txn_preauth):+ admin_client, order_with_lines, payment_txn_preauth):order = order_with_linesurl = reverse('dashboard:refund-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_method_txn_preauth.pk})+ 'order_pk': order.pk, 'payment_pk': payment_txn_preauth.pk})response = admin_client.get(url)assert response.status_code == 200response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})assert response.status_code == 400- payment = order.payment_methods.last()+ payment = order.payments.last()assert payment.charge_status == ChargeStatus.NOT_CHARGED@pytest.mark.integrationdef test_view_refund_order_invalid_payment_refunded_status(- admin_client, order_with_lines, payment_method_txn_refunded):+ admin_client, order_with_lines, payment_txn_refunded):order = order_with_linesurl = reverse('dashboard:refund-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_method_txn_refunded.pk})+ 'order_pk': order.pk, 'payment_pk': payment_txn_refunded.pk})response = admin_client.get(url)assert response.status_code == 200response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})assert response.status_code == 400- payment = order.payment_methods.last()+ payment = order.payments.last()assert payment.charge_status == ChargeStatus.FULLY_REFUNDED@pytest.mark.integrationdef test_view_release_order_payment_preauth(- admin_client, order_with_lines, payment_method_txn_preauth):+ admin_client, order_with_lines, payment_txn_preauth):order = order_with_linesurl = reverse('dashboard:release-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_method_txn_preauth.pk})+ 'order_pk': order.pk, 'payment_pk': payment_txn_preauth.pk})response = admin_client.get(url)assert response.status_code == 200response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello'})assert response.status_code == 302- order_payment = order.payment_methods.last()+ order_payment = order.payments.last()assert order_payment.charge_status == ChargeStatus.NOT_CHARGEDlast_transaction = order_payment.transactions.latest('pk')@@ -216,38 +216,38 @@ def test_view_release_order_payment_preauth(@pytest.mark.integrationdef test_view_release_order_invalid_payment_confirmed_status(- admin_client, order_with_lines, payment_method_txn_captured):+ admin_client, order_with_lines, payment_txn_captured):order = order_with_linesurl = reverse('dashboard:release-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_method_txn_captured.pk})+ 'order_pk': order.pk, 'payment_pk': payment_txn_captured.pk})response = admin_client.get(url)assert response.status_code == 200response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello'})assert response.status_code == 400- order_payment = order.payment_methods.last()+ order_payment = order.payments.last()assert order_payment.charge_status == ChargeStatus.CHARGEDassert order_payment.captured_amount == order.total.gross@pytest.mark.integrationdef test_view_release_order_invalid_payment_refunded_status(- admin_client, order_with_lines, payment_method_txn_refunded):+ admin_client, order_with_lines, payment_txn_refunded):order = order_with_linesurl = reverse('dashboard:release-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_method_txn_refunded.pk})+ 'order_pk': order.pk, 'payment_pk': payment_txn_refunded.pk})response = admin_client.get(url)assert response.status_code == 200response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello'})assert response.status_code == 400- payment = order.payment_methods.last()+ payment = order.payments.last()assert payment.charge_status == ChargeStatus.FULLY_REFUNDEDassert payment.captured_amount == Money(0, 'USD')diff --git a/tests/test_order.py b/tests/test_order.pyindex 8525b98dba..a261e424cc 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -366,7 +366,7 @@ def test_order_queryset_to_ship():status=OrderStatus.PARTIALLY_FULFILLED, total=total)]for order in orders_to_ship:- order.payment_methods.create(+ order.payments.create(variant='default', charge_status=ChargeStatus.CHARGED,total=order.total.gross, captured_amount=order.total_gross)@@ -441,7 +441,7 @@ def test_order_payment_flow(order = create_order(request_cart_with_item, 'tracking_code', discounts=None, taxes=None)- # Select payment method+ # Select paymenturl = reverse('order:payment', kwargs={'token': order.token})data = {'method': 'default'}response = client.post(url, data, follow=True)@@ -466,7 +466,7 @@ def test_order_payment_flow(assert get_redirect_location(response) == redirect_url# Assert that payment object was created and contains correct data- payment = order.payment_methods.all()[0]+ payment = order.payments.all()[0]assert payment.total == order.total_grossassert payment.transactions.count() == 1assert payment.transactions.first().transaction_type == 'auth'diff --git a/tests/test_payments.py b/tests/test_payments.pyindex 2331d603ae..30d7801c77 100644--- a/tests/test_payments.py+++ b/tests/test_payments.py@@ -5,35 +5,35 @@ from saleor.payment import ChargeStatus, PaymentError, TransactionTypefrom .utils import money-def test_authorize(payment_method_dummy):- txn = payment_method_dummy.authorize(client_token='Fake')+def test_authorize(payment_dummy):+ txn = payment_dummy.authorize(client_token='Fake')assert txn.is_successassert txn.transaction_type == TransactionType.AUTH- assert txn.payment_method == payment_method_dummy- payment_method_dummy.refresh_from_db()- assert payment_method_dummy.is_active+ assert txn.payment == payment_dummy+ payment_dummy.refresh_from_db()+ assert payment_dummy.is_active-def test_authorize_gateway_error(payment_method_dummy, monkeypatch):+def test_authorize_gateway_error(payment_dummy, monkeypatch):monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)with pytest.raises(PaymentError):- txn = payment_method_dummy.authorize(client_token='Fake')+ txn = payment_dummy.authorize(client_token='Fake')assert txn.transaction_type == TransactionType.AUTHassert not txn.is_success- assert txn.payment_method == payment_method_dummy+ assert txn.payment == payment_dummy-def test_void_success(payment_method_dummy):- assert payment_method_dummy.is_active- assert payment_method_dummy.charge_status == ChargeStatus.NOT_CHARGED- txn = payment_method_dummy.void()+def test_void_success(payment_dummy):+ assert payment_dummy.is_active+ assert payment_dummy.charge_status == ChargeStatus.NOT_CHARGED+ txn = payment_dummy.void()assert txn.is_successassert txn.transaction_type == TransactionType.VOID- assert txn.payment_method == payment_method_dummy- payment_method_dummy.refresh_from_db()- assert not payment_method_dummy.is_active- assert payment_method_dummy.charge_status == ChargeStatus.NOT_CHARGED+ assert txn.payment == payment_dummy+ payment_dummy.refresh_from_db()+ assert not payment_dummy.is_active+ assert payment_dummy.charge_status == ChargeStatus.NOT_CHARGED@pytest.mark.parametrize(@@ -42,34 +42,34 @@ def test_void_success(payment_method_dummy):(False, ChargeStatus.CHARGED),(True, ChargeStatus.CHARGED),(True, ChargeStatus.FULLY_REFUNDED), ])-def test_void_failed(is_active, charge_status, payment_method_dummy):- payment_method = payment_method_dummy- payment_method.is_active = is_active- payment_method.charge_status = charge_status- payment_method.save()+def test_void_failed(is_active, charge_status, payment_dummy):+ payment = payment_dummy+ payment.is_active = is_active+ payment.charge_status = charge_status+ payment.save()with pytest.raises(PaymentError):- txn = payment_method.void()+ txn = payment.void()assert txn is None-def test_void_gateway_error(payment_method_dummy, monkeypatch):+def test_void_gateway_error(payment_dummy, monkeypatch):monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)with pytest.raises(PaymentError):- txn = payment_method_dummy.void()+ txn = payment_dummy.void()assert txn.transaction_type == TransactionType.VOIDassert not txn.is_success- assert txn.payment_method == payment_method_dummy+ assert txn.payment == payment_dummy@pytest.mark.parametrize('amount', [80, 70])-def test_charge_success(amount, payment_method_dummy):- txn = payment_method_dummy.capture(amount=amount)+def test_charge_success(amount, payment_dummy):+ txn = payment_dummy.capture(amount=amount)assert txn.is_success- assert txn.payment_method == payment_method_dummy- payment_method_dummy.refresh_from_db()- assert payment_method_dummy.charge_status == ChargeStatus.CHARGED- assert payment_method_dummy.is_active+ assert txn.payment == payment_dummy+ payment_dummy.refresh_from_db()+ assert payment_dummy.charge_status == ChargeStatus.CHARGED+ assert payment_dummy.is_active@pytest.mark.parametrize(@@ -80,25 +80,25 @@ def test_charge_success(amount, payment_method_dummy):(120, money(0), ChargeStatus.NOT_CHARGED, True), ])def test_charge_failed(amount, captured_amount, charge_status, is_active,- payment_method_dummy):- payment_method = payment_method_dummy- payment_method.is_active = is_active- payment_method.captured_amount = captured_amount- payment_method.charge_status = charge_status- payment_method.save()+ payment_dummy):+ payment = payment_dummy+ payment.is_active = is_active+ payment.captured_amount = captured_amount+ payment.charge_status = charge_status+ payment.save()with pytest.raises(PaymentError):- txn = payment_method.capture(amount=amount)+ txn = payment.capture(amount=amount)assert txn is None-def test_charge_gateway_error(payment_method_dummy, monkeypatch):+def test_charge_gateway_error(payment_dummy, monkeypatch):monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)with pytest.raises(PaymentError):- txn = payment_method_dummy.capture(80)+ txn = payment_dummy.capture(80)assert txn.transaction_type == TransactionType.CHARGEassert not txn.is_success- assert txn.payment_method == payment_method_dummy+ assert txn.payment == payment_dummy@pytest.mark.parametrize(@@ -108,18 +108,18 @@ def test_charge_gateway_error(payment_method_dummy, monkeypatch):(money(80), 10, money(70), ChargeStatus.CHARGED, True), ])def test_refund_success(initial_captured_amount, refund_amount, final_captured_amount,- final_charge_status, active_after, payment_method_dummy):- payment_method = payment_method_dummy- payment_method.charge_status = ChargeStatus.CHARGED- payment_method.captured_amount = initial_captured_amount- payment_method.save()- txn = payment_method.refund(refund_amount)+ final_charge_status, active_after, payment_dummy):+ payment = payment_dummy+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount = initial_captured_amount+ payment.save()+ txn = payment.refund(refund_amount)assert txn.transaction_type == TransactionType.REFUNDassert txn.is_success- assert txn.payment_method == payment_method- assert payment_method.charge_status == final_charge_status- assert payment_method.captured_amount == final_captured_amount- assert payment_method.is_active == active_after+ assert txn.payment == payment+ assert payment.charge_status == final_charge_status+ assert payment.captured_amount == final_captured_amount+ assert payment.is_active == active_after@pytest.mark.parametrize(@@ -129,28 +129,28 @@ def test_refund_success((money(10), 20, ChargeStatus.CHARGED), ])def test_refund_failed(initial_captured_amount, refund_amount, initial_charge_status,- payment_method_dummy):- payment_method = payment_method_dummy- payment_method.charge_status = initial_charge_status- payment_method.captured_amount = initial_captured_amount- payment_method.save()+ payment_dummy):+ payment = payment_dummy+ payment.charge_status = initial_charge_status+ payment.captured_amount = initial_captured_amount+ payment.save()with pytest.raises(PaymentError):- txn = payment_method.refund(refund_amount)+ txn = payment.refund(refund_amount)assert txn is None-def test_refund_gateway_error(payment_method_dummy, monkeypatch):+def test_refund_gateway_error(payment_dummy, monkeypatch):monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)- payment_method = payment_method_dummy- payment_method.charge_status = ChargeStatus.CHARGED- payment_method.captured_amount = money(80)- payment_method.save()+ payment = payment_dummy+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount = money(80)+ payment.save()with pytest.raises(PaymentError):- txn = payment_method.refund(80)- payment_method.refresh_from_db()+ txn = payment.refund(80)+ payment.refresh_from_db()assert txn.transaction_type == TransactionType.REFUNDassert not txn.is_success- assert txn.payment_method == payment_method- assert payment_method.charge_status == ChargeStatus.CHARGED- assert payment_method.captured_amount == money(80)+ assert txn.payment == payment+ assert payment.charge_status == ChargeStatus.CHARGED+ assert payment.captured_amount == money(80)