Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix several inconsistences
Pacu2bf44946932df
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex ea921547b0..d4a6a28dc7 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -11,6 +11,7 @@ from django_prices.models import MoneyFieldfrom measurement.measures import Weightfrom ..account.models import Address+from ..core import zero_moneyfrom ..core.utils.taxes import ZERO_TAXED_MONEYfrom ..shipping.models import ShippingMethod@@ -56,7 +57,8 @@ class Cart(models.Model):note = models.TextField(blank=True, default='')discount_amount = MoneyField(currency=settings.DEFAULT_CURRENCY, max_digits=12,- decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=zero_money)discount_name = models.CharField(max_length=255, blank=True, null=True)translated_discount_name = models.CharField(max_length=255, blank=True, null=True)diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 8b6e8b26b3..dbb514ae8e 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -886,13 +886,15 @@ def create_order(cart, tracking_code, discounts, taxes):def is_fully_paid(cart: Cart):- payment_methods = cart.payment_methods.all()- total_paid = sum([p.get_captured_money() for p in payment_methods])- return total_paid == cart.get_total().gross.amount+ payment_methods = cart.payment_methods.filter(is_active=True)+ total_paid = sum(+ [p.captured_amount.amount for p in payment_methods])+ import pdb; pdb.set_trace()+ return total_paid >= cart.get_total().gross.amountdef ready_to_place_order(cart: Cart):- if cart.is_shipping_required:+ if cart.is_shipping_required():if not cart.shipping_method:return False, pgettext_lazy('order placement_error', 'Shipping method is not set')diff --git a/saleor/core/__init__.py b/saleor/core/__init__.pyindex 20d5791a47..a3999287dd 100644--- a/saleor/core/__init__.py+++ b/saleor/core/__init__.py@@ -1,6 +1,7 @@from django.conf import settingsfrom django.core.checks import Warning, registerfrom django.utils.translation import pgettext_lazy+from prices import MoneyTOKEN_PATTERN = ('(?P<token>[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}''-[0-9a-z]{12})')@@ -84,3 +85,8 @@ class TaxRateType:(SOCIAL_HOUSING, pgettext_lazy('VAT rate type', 'social housing')),(STANDARD, pgettext_lazy('VAT rate type', 'standard')),(WATER, pgettext_lazy('VAT rate type', 'water')))+++def zero_money():+ """Function used as a model's default."""+ return Money(0, currency=settings.DEFAULT_CURRENCY)diff --git a/saleor/core/templatetags/status.py b/saleor/core/templatetags/status.pyindex 8d14dcb758..24f87ad1ee 100644--- a/saleor/core/templatetags/status.py+++ b/saleor/core/templatetags/status.py@@ -1,7 +1,7 @@from django.template import Library-from payments import PaymentStatusfrom ...order import OrderStatus+from ...payment import ChargeStatusfrom ...product import ProductAvailabilityStatus, VariantAvailabilityStatusfrom ...product.utils.availability import (get_product_availability_status, get_variant_availability_status)@@ -9,8 +9,7 @@ from ...product.utils.availability import (register = Library()-ERRORS = {PaymentStatus.ERROR, PaymentStatus.REJECTED}-SUCCESSES = {PaymentStatus.CONFIRMED, PaymentStatus.REFUNDED}+SUCCESSES = {ChargeStatus.CHARGED, ChargeStatus.FULLY_REFUNDED}LABEL_DANGER = 'danger'@@ -20,9 +19,7 @@ LABEL_DEFAULT = 'default'@register.inclusion_tag('status_label.html')def render_status(status, status_display=None):- if status in ERRORS:- label_cls = LABEL_DANGER- elif status in SUCCESSES:+ if status in SUCCESSES:label_cls = LABEL_SUCCESSelse:label_cls = LABEL_DEFAULTdiff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex b76490f06f..d0edf8ef92 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -27,7 +27,7 @@ from ...menu.models import Menufrom ...order.models import Fulfillment, Orderfrom ...order.utils import update_order_statusfrom ...page.models import Page-from ...payment import PaymentMethodChargeStatus, TransactionType+from ...payment import ChargeStatus, TransactionTypefrom ...payment.models import PaymentMethodfrom ...product.models import (Attribute, AttributeValue, Category, Collection, Product, ProductImage,@@ -378,52 +378,50 @@ def create_fake_user():def create_transactions(payment):+ #FIXME Add testspayment.transactions.create(transaction_type=TransactionType.AUTH,- is_success=True, amount=payment.total, currency=payment.currency)- if payment.status == PaymentMethodChargeStatus.NOT_CHARGED:+ is_success=True, amount=payment.total)+ if payment.charge_status == ChargeStatus.NOT_CHARGED:if random.randint(0, 1):payment.transactions.create(transaction_type=TransactionType.VOID,- is_success=True, amount=payment.total,- currency=payment.currency)+ is_success=True, amount=payment.total)returnpayment.transactions.create(transaction_type=TransactionType.CAPTURE,- is_success=True, amount=payment.total, currency=payment.currency)- if payment.status == PaymentMethodChargeStatus.FULLY_REFUNDED:+ is_success=True, amount=payment.total)+ if payment.charge_status == ChargeStatus.FULLY_REFUNDED:payment.transactions.create(transaction_type=TransactionType.REFUND,- is_success=True, amount=payment.total,- currency=payment.currency)+ is_success=True, amount=payment.total)return paymentdef create_payment(order):+ #FIXME Add testsstatus = random.choice([- PaymentMethodChargeStatus.FULLY_REFUNDED,- PaymentMethodChargeStatus.CHARGED,- PaymentMethodChargeStatus.NOT_CHARGED])+ ChargeStatus.FULLY_REFUNDED,+ ChargeStatus.CHARGED,+ ChargeStatus.NOT_CHARGED])payment = PaymentMethod.objects.create(order=order,- status=status,+ charge_status=status,variant='default',transaction_id=str(fake.random_int(1, 100000)),- currency=settings.DEFAULT_CURRENCY,- total=order.total.gross.amount,- tax=order.total.tax.amount,+ total=order.total,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_postal_code=order.billing_address.postal_code,billing_country_code=order.billing_address.country,billing_country_area=order.billing_address.country_area)- if status == PaymentMethodChargeStatus.CONFIRMED:- payment.captured_amount = payment.total+ if status == ChargeStatus.CONFIRMED:+ payment.captured_amount = payment.total.grosspayment.save()create_transactions(payment)return paymentdiff --git a/saleor/dashboard/order/filters.py b/saleor/dashboard/order/filters.pyindex 3797db8168..43f5b90b83 100644--- a/saleor/dashboard/order/filters.py+++ b/saleor/dashboard/order/filters.py@@ -8,7 +8,7 @@ from django_filters import (from ...core.filters import SortedFilterSetfrom ...order import OrderStatusfrom ...order.models import Order-from ...payment import PaymentMethodChargeStatus+from ...payment import ChargeStatusfrom ..widgets import DateRangeWidget, MoneyRangeWidgetSORT_BY_FIELDS = [@@ -20,7 +20,8 @@ SORT_BY_FIELDS = [SORT_BY_FIELDS_LABELS = {'pk': pgettext_lazy('Order list sorting option', '#'),- 'payments__status': pgettext_lazy('Order list sorting option', 'payment'),+ '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'),'total_net': pgettext_lazy('Order list sorting option', 'created')}@@ -45,7 +46,7 @@ class OrderFilter(SortedFilterSet):payment_status = ChoiceFilter(label=pgettext_lazy('Order list filter label', 'Payment status'),field_name='payments__status',- choices=PaymentMethodChargeStatus.CHOICES,+ choices=ChargeStatus.CHOICES,empty_label=pgettext_lazy('Filter empty choice label', 'All'),widget=forms.Select)total_net = RangeFilter(diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex f01a2df093..ac2d126cc7 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -18,7 +18,7 @@ from ...order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ...order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order,change_order_line_quantity, recalculate_order)-from ...payment import PaymentMethodChargeStatus, PaymentError+from ...payment import ChargeStatus, PaymentErrorfrom ...payment.models import PaymentMethodfrom ...product.models import Product, ProductVariantfrom ...product.utils import allocate_stock, deallocate_stock@@ -283,17 +283,17 @@ class ManagePaymentForm(forms.Form):class CapturePaymentForm(ManagePaymentForm):- clean_status = PaymentMethodChargeStatus.NOT_CHARGED+ clean_status = ChargeStatus.NOT_CHARGEDclean_error = pgettext_lazy('Payment form error','Only pre-authorized payments can be captured')def capture(self):- return self.try_payment_action(self.payment.charge)+ return self.try_payment_action(self.payment.capture)class RefundPaymentForm(ManagePaymentForm):- clean_status = PaymentMethodChargeStatus.CHARGED+ clean_status = ChargeStatus.CHARGEDclean_error = pgettext_lazy('Payment form error','Only confirmed payments can be refunded')@@ -316,7 +316,7 @@ class ReleasePaymentForm(forms.Form):super().__init__(*args, **kwargs)def clean(self):- if self.payment.charge_status != PaymentMethodChargeStatus.NOT_CHARGED:+ if self.payment.charge_status != ChargeStatus.NOT_CHARGED:raise forms.ValidationError(pgettext_lazy('Payment form error',@@ -345,25 +345,20 @@ class OrderMarkAsPaidForm(forms.Form):def clean(self):super().clean()- if self.order.payments.exists():+ if self.order.payment_methods.exists():raise forms.ValidationError(pgettext_lazy('Mark order as paid form error','Orders with payments can not be manually marked as paid'))def save(self):+ # FIXME add more fields to the payment methoddefaults = {- 'total': self.order.total.gross.amount,- 'tax': self.order.total.tax.amount,- 'currency': self.order.total.currency,- 'delivery': self.order.shipping_price.net.amount,- 'description': pgettext_lazy(- 'Payment description', 'Order %(order)s') % {- 'order': self.order},- 'captured_amount': self.order.total.gross.amount}+ 'total': self.order.total,+ 'captured_amount': self.order.total.gross}PaymentMethod.objects.get_or_create(variant=CustomPaymentChoices.MANUAL,- status=PaymentMethodChargeStatus.CHARGED, order=self.order,+ charge_status=ChargeStatus.CHARGED, order=self.order,defaults=defaults)@@ -530,7 +525,7 @@ class OrderRemoveVoucherForm(forms.ModelForm):PAYMENT_STATUS_CHOICES = ([('', pgettext_lazy('Payment status field value', 'All'))] +- PaymentMethodChargeStatus.CHOICES)+ ChargeStatus.CHOICES)class PaymentFilterForm(forms.Form):diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 35c43e0c78..4a82049ae6 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -23,7 +23,7 @@ from ...order.emails import (send_order_confirmation)from ...order.models import Fulfillment, FulfillmentLine, Orderfrom ...order.utils import update_order_prices, update_order_status-from ...payment import PaymentMethodChargeStatus+from ...payment import ChargeStatusfrom ...shipping.models import ShippingMethodfrom ..views import staff_member_requiredfrom .filters import OrderFilter@@ -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(- 'payments', 'events__user', 'lines__variant__product',+ 'payment_methods', 'events__user', 'lines__variant__product','fulfillments__lines__order_line')order = get_object_or_404(qs, pk=order_pk)- all_payments = order.payments.all()+ all_payments = order.payment_methods.all()payment = order.get_last_payment()preauthorized = ZERO_TAXED_MONEYcaptured = ZERO_MONEY@@ -130,22 +130,22 @@ def order_details(request, order_pk):if payment:can_capture = (payment.is_active and- payment.charge_status == PaymentMethodChargeStatus.NOT_CHARGED and+ payment.charge_status == ChargeStatus.NOT_CHARGED andorder.status not in {OrderStatus.DRAFT, OrderStatus.CANCELED})can_release = (payment.is_active and- payment.charge_status == PaymentMethodChargeStatus.NOT_CHARGED)+ payment.charge_status == ChargeStatus.NOT_CHARGED)can_refund = (payment.is_active and- payment.charge_status == PaymentMethodChargeStatus.CHARGED and+ payment.charge_status == ChargeStatus.CHARGED andpayment.variant != CustomPaymentChoices.MANUAL)- preauthorized = payment.get_total()- if payment.charge_status == PaymentMethodChargeStatus.CHARGED:- captured = payment.get_captured_money()+ preauthorized = payment.total+ if payment.charge_status == ChargeStatus.CHARGED:+ captured = payment.captured_amountbalance = captured - order.total.grosselse:can_capture = can_release = can_refund = False- can_mark_as_paid = not order.payments.exists()+ can_mark_as_paid = not order.payment_methods.exists()ctx = {'order': order, 'all_payments': all_payments, 'payment': payment,'notes': order.events.filter(type=OrderEvents.NOTE_ADDED.value),@@ -188,8 +188,8 @@ def capture_payment(request, order_pk, payment_pk):order = get_object_or_404(orders, pk=order_pk)payment = get_object_or_404(order.payment_methods, pk=payment_pk)amount = order.total.quantize('0.01').gross- form = CapturePaymentForm(request.POST or None, payment=payment,- initial={'amount': amount})+ form = CapturePaymentForm(+ request.POST or None, payment=payment, initial={'amount': amount})if form.is_valid() and form.capture():amount = form.cleaned_data['amount']msg = pgettext_lazy(@@ -202,8 +202,11 @@ def capture_payment(request, order_pk, payment_pk):messages.success(request, msg)return redirect('dashboard:order-details', order_pk=order.pk)status = 400 if form.errors else 200- ctx = {'captured': payment.captured_amount, 'currency': payment.currency,- 'form': form, 'order': order, 'payment': payment}+ ctx = {+ 'captured': payment.captured_amount,+ 'form': form,+ 'order': order,+ 'payment': payment}return TemplateResponse(request, 'dashboard/order/modal/capture.html', ctx,status=status)@@ -215,8 +218,8 @@ def refund_payment(request, order_pk, payment_pk):order = get_object_or_404(orders, pk=order_pk)payment = get_object_or_404(order.payment_methods, pk=payment_pk)amount = payment.captured_amount- form = RefundPaymentForm(request.POST or None, payment=payment,- initial={'amount': amount})+ form = RefundPaymentForm(+ request.POST or None, payment=payment, initial={'amount': amount})if form.is_valid() and form.refund():amount = form.cleaned_data['amount']msg = pgettext_lazy(@@ -229,8 +232,11 @@ def refund_payment(request, order_pk, payment_pk):messages.success(request, msg)return redirect('dashboard:order-details', order_pk=order.pk)status = 400 if form.errors else 200- ctx = {'captured': payment.captured_amount, 'currency': payment.currency,- 'form': form, 'order': order, 'payment': payment}+ ctx = {+ 'captured': payment.captured_amount,+ 'form': form,+ 'order': order,+ 'payment': payment}return TemplateResponse(request, 'dashboard/order/modal/refund.html', ctx,status=status)@@ -250,8 +256,9 @@ def release_payment(request, order_pk, payment_pk):messages.success(request, msg)return redirect('dashboard:order-details', order_pk=order.pk)status = 400 if form.errors else 200- ctx = {'captured': payment.captured_amount, 'currency': payment.currency,- 'form': form, 'order': order, 'payment': payment}+ ctx = {+ 'captured': payment.captured_amount, 'form': form, 'order': order,+ 'payment': payment}return TemplateResponse(request, 'dashboard/order/modal/release.html', ctx,status=status)diff --git a/saleor/dashboard/views.py b/saleor/dashboard/views.pyindex ebe66dc5c7..affb23e68a 100644--- a/saleor/dashboard/views.py+++ b/saleor/dashboard/views.py@@ -4,9 +4,10 @@ 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 ..payment.models import PaymentMethod-from ..payment import PaymentMethodChargeStatus+from ..order.models import Order+from ..payment import ChargeStatus+from ..payment.models import PaymentMethodfrom ..product.models import Product@@ -36,7 +37,7 @@ def index(request):orders_to_ship = Order.objects.ready_to_fulfill().select_related('user').prefetch_related('lines', 'payments')payments = PaymentMethod.objects.filter(- is_active=True, charge_status=PaymentMethodChargeStatus.NOT_CHARGED+ is_active=True, charge_status=ChargeStatus.NOT_CHARGED).order_by('-created')payments = payments.select_related('order', 'order__user')low_stock = get_low_stock_products()diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 77e494bb64..8db1d19706 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -164,13 +164,15 @@ class Query(ProductQueries):def resolve_checkout_line(self, info, id):return graphene.Node.get_node_from_global_id(info, id, CheckoutLine)+ @permission_required('order.manage_orders')def resolve_checkout_lines(self, info, query=None, **kwargs):return resolve_checkout_lines(info, query)+ @permission_required('order.manage_orders')def resolve_checkouts(self, info, query=None, **kwargs):resolve_checkouts(info, query)- @permission_required(['account.manage_users'])+ @permission_required('account.manage_users')def resolve_user(self, info, id):return graphene.Node.get_node_from_global_id(info, id, User)@@ -356,4 +358,5 @@ class Mutations(ProductMutations):variant_image_assign = VariantImageAssign.Field()variant_image_unassign = VariantImageUnassign.Field()+schema = graphene.Schema(Query, Mutations)diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex abf242eb1b..652a9e3577 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -4,8 +4,8 @@ from ...checkout import modelsfrom ...core.utils.taxes import get_taxes_for_addressfrom ..core.types.common import CountableDjangoObjectTypefrom ..core.types.money import TaxedMoney-from ..shipping.types import ShippingMethodfrom ..order.resolvers import resolve_shipping_methods+from ..shipping.types import ShippingMethodclass CheckoutLine(CountableDjangoObjectType):diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex e1bbd379f7..619004235d 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -127,8 +127,8 @@ class ModelMutation(BaseMutation):@classmethoddef __init_subclass_with_meta__(- cls, arguments=None, model=None, exclude=None, return_field_name=None,- _meta=None, **options):+ cls, arguments=None, model=None, exclude=None,+ return_field_name=None, _meta=None, **options):if not model:raise ImproperlyConfigured('model is required for ModelMutation')if not _meta:diff --git a/saleor/graphql/file_upload/views.py b/saleor/graphql/file_upload/views.pyindex 4eb18d78f0..705dd310de 100644--- a/saleor/graphql/file_upload/views.py+++ b/saleor/graphql/file_upload/views.py@@ -18,20 +18,8 @@ class FileUploadGraphQLView(GraphQLView):response['Access-Control-Allow-Origin'] = ','.join(settings.ALLOWED_HOSTS)response['Access-Control-Allow-Methods'] = 'POST, OPTIONS'- response[- 'Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization'- return response-- def dispatch(self, request, *args, **kwargs):- # Handle options method the GraphQlView restricts it.- if request.method == 'OPTIONS':- response = self.options(request, *args, **kwargs)- else:- response = super().dispatch(request, *args, **kwargs)- # Add access control headers- response['Access-Control-Allow-Origin'] = ','.join(settings.ALLOWED_HOSTS)- response['Access-Control-Allow-Methods'] = 'POST, OPTIONS'- response['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization'+ response['Access-Control-Allow-Headers'] = (+ 'Origin, Content-Type, Accept, Authorization')return response@staticmethod@@ -42,8 +30,8 @@ class FileUploadGraphQLView(GraphQLView):# not checked in the original version from `graphene-file-upload`).if content_type and 'multipart/form-data' in content_type:query, variables, operation_name, id = super(- FileUploadGraphQLView, FileUploadGraphQLView).get_graphql_params(- request, data)+ FileUploadGraphQLView,+ FileUploadGraphQLView).get_graphql_params(request, data)operations = data.get('operations')files_map = data.get('map')try:@@ -54,15 +42,16 @@ class FileUploadGraphQLView(GraphQLView):# file key is which file it is in the form-datafile_instances = files_map[file_key]for file_instance in file_instances:- test = obj_set(operations, file_instance, file_key, False)+ test = obj_set(+ operations, file_instance, file_key, False)query = operations.get('query')variables = operations.get('variables')except Exception as e:raise eelse:query, variables, operation_name, id = super(- FileUploadGraphQLView, FileUploadGraphQLView).get_graphql_params(- request, data)+ FileUploadGraphQLView,+ FileUploadGraphQLView).get_graphql_params(request, data)return query, variables, operation_name, id@@ -91,7 +80,7 @@ def obj_set(obj, path, value, doNotReplace):return objif isinstance(path, str):newPath = list(map(getKey, path.split('.')))- return obj_set(obj, newPath, value, doNotReplace )+ return obj_set(obj, newPath, value, doNotReplace)currentPath = path[0]currentValue = getShallowProperty(obj, currentPath)diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 4d4e2dd79c..f8e596fa63 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -1,19 +1,18 @@import graphene-from django.utils.translation import pgettext_lazyfrom graphql_jwt.decorators import permission_requiredfrom ....account.models import Userfrom ....core.utils.taxes import ZERO_TAXED_MONEYfrom ....order import CustomPaymentChoices, OrderEvents, modelsfrom ....order.utils import cancel_order+from ....payment import ChargeStatus, PaymentError+from ....payment.models import PaymentMethodfrom ....shipping.models import ShippingMethod as ShippingMethodModelfrom ...account.types import AddressInputfrom ...core.mutations import BaseMutationfrom ...core.types.common import Decimal, Errorfrom ...order.mutations.draft_orders import DraftOrderUpdatefrom ...order.types import Order, OrderEvent-from ....payment import PaymentError, PaymentMethodChargeStatus-from ....payment.models import PaymentMethodfrom ...shipping.types import ShippingMethod@@ -59,7 +58,7 @@ def clean_order_cancel(order, errors):def clean_order_mark_as_paid(order, errors):- if order and order.payments.exists():+ if order and order.payment_methods.exists():errors.append(Error(field='payment',@@ -90,7 +89,7 @@ def clean_release_payment(payment, errors):Error(field='payment',message='Only pre-authorized payments can be released'))try:- payment.release()+ payment.void()except (PaymentError, ValueError) as e:errors.append(Error(field='payment', message=str(e)))return errors@@ -289,18 +288,12 @@ class OrderMarkAsPaid(BaseMutation):clean_order_mark_as_paid(order, errors)if errors:return OrderMarkAsPaid(errors=errors)-+ # FIXME add more fields to the payment methoddefaults = {- 'total': order.total.gross.amount,- 'tax': order.total.tax.amount,- 'currency': order.total.currency,- 'delivery': order.shipping_price.net.amount,- 'description': pgettext_lazy(- 'Payment description', 'Order %(order)s') % {'order': order},- 'captured_amount': order.total.gross.amount}- models.PaymentMethod.objects.get_or_create(+ 'total': order.total, 'captured_amount': order.total.gross}+ PaymentMethod.objects.get_or_create(variant=CustomPaymentChoices.MANUAL,- charge_status=PaymentMethodChargeStatus.CHARGED, order=order,+ charge_status=ChargeStatus.CHARGED, order=order,defaults=defaults)order.events.create(@@ -324,6 +317,7 @@ class OrderCapture(BaseMutation):@classmethod@permission_required('order.manage_orders')def mutate(cls, root, info, id, amount):+ # FIXME we should validate if amount is positive numbererrors = []order = cls.get_node_or_error(info, id, errors, 'id', Order)payment = order.get_last_payment()@@ -360,7 +354,6 @@ class OrderRelease(BaseMutation):if errors:return OrderRelease(errors=errors)-order.events.create(type=OrderEvents.PAYMENT_RELEASED.value,user=info.context.user)@@ -382,6 +375,7 @@ class OrderRefund(BaseMutation):@classmethod@permission_required('order.manage_orders')def mutate(cls, root, info, id, amount):+ # FIXME we should validate if amount is positive numbererrors = []order = cls.get_node_or_error(info, id, errors, 'id', Order)if order:diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 9efa3ff75a..e32765255d 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -1,22 +1,24 @@import grapheneimport graphene_django_optimizer as gql_optimizerfrom graphene import relay-from payments import PaymentStatusfrom ...order import OrderEvents, OrderEventsEmails, models+from ...payment import ChargeStatusfrom ...product.templatetags.product_images import get_thumbnailfrom ...shipping import models as shipping_modelsfrom ..account.types import Userfrom ..core.fields import PrefetchingConnectionFieldfrom ..core.types.common import CountableDjangoObjectType-from ..core.types.money import Money, TaxedMoney+from ..core.types.money import Money, TaxedMoney, _str_to_enumfrom ..shipping.types import ShippingMethodOrderEventsEnum = graphene.Enum.from_enum(OrderEvents)OrderEventsEmailsEnum = graphene.Enum.from_enum(OrderEventsEmails)PaymentStatusEnum = graphene.Enum('PaymentStatusEnum',- [(code.upper(), code) for code, name in PaymentStatus.CHOICES])+ [+ (_str_to_enum(code.upper()), code)+ for code, name in ChargeStatus.CHOICES])class OrderStatusFilter(graphene.Enum):@@ -205,17 +207,18 @@ class Order(CountableDjangoObjectType):@staticmethod@gql_optimizer.resolver_hints(prefetch_related='payments')def resolve_total_authorized(obj, info):+ # FIXME adjust to multiple paymentspayment = obj.get_last_payment()if payment:- return payment.get_total().gross+ return payment.total.gross@staticmethod@gql_optimizer.resolver_hints(prefetch_related='payments')def resolve_total_captured(obj, info):- payment = obj.get_last_payment()# FIXME adjust to multiple payments+ payment = obj.get_last_payment()if payment:- return payment.get_captured_money()+ return payment.captured_amount@staticmethoddef resolve_fulfillments(obj, info):diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex e4d0c6bff7..ea0eb04943 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -1,5 +1,7 @@import graphene+from django.conf import settingsfrom graphql_jwt.decorators import permission_required+from prices import Money, TaxedMoneyfrom ...payment import PaymentErrorfrom ...payment.utils import (@@ -14,18 +16,21 @@ from .types import PaymentGatewayEnum, PaymentMethodclass PaymentMethodInput(graphene.InputObjectType):gateway = PaymentGatewayEnum()- checkout_id = graphene.ID(description='Checkout ID')- transaction_token = graphene.Argument(- graphene.String,+ checkout_id = graphene.ID(description='Checkout ID.')+ transaction_token = graphene.String(+ required=True, description='One time transaction token.')+ tax = Decimal(required=True,- description='One time transaction token')- amount = graphene.Argument(- Decimal, required=True, description='Transaction amount')+ description='Tax included in the transaction\'s total amount.')+ amount = Decimal(+ required=True,+ description=(+ 'Total amount of the transaction, including '+ 'all taxes and discounts.'))billing_address = AddressInput(description='Billing address')- store_payment_method = graphene.Argument(- graphene.Boolean,+ store_payment_method = graphene.Boolean(default_value=False,- description='Store card for further usage')+ description='Store card for further usage.')class CheckoutPaymentMethodCreate(BaseMutation):@@ -55,9 +60,14 @@ class CheckoutPaymentMethodCreate(BaseMutation):billing_data = cls.clean_billing_address(input['billing_address'])# create payment method+ # FIXME should take amount and tax into the consideration+ gross = Money(input['amount'], currency=settings.DEFAULT_CURRENCY)+ tax = Money(input['amount'], currency=settings.DEFAULT_CURRENCY)+ net = (gross - tax) or grosspayment_method = create_payment_method(+ total_net=net, total_gross=gross,variant=input['gateway'], billing_email=checkout.email,- extra_data=extra_data, total=input['amount'], checkout=checkout,+ extra_data=extra_data, checkout=checkout,**billing_data)# authorize payment@@ -78,7 +88,7 @@ class CheckoutPaymentMethodCreate(BaseMutation):'billing_address_1': billing_address.street_address_1,'billing_address_2': billing_address.street_address_2,'billing_city': billing_address.city,- 'billing_postcode': billing_address.postal_code,+ 'billing_postal_code': billing_address.postal_code,'billing_country_code': billing_address.country,'billing_country_area': billing_address.country_area}return billing_data@@ -101,7 +111,7 @@ class PaymentMethodCapture(BaseMutation):class Arguments:payment_method_id = graphene.ID(required=True, description='Payment method ID')- amount = graphene.Argument(Decimal, description='Transaction amount')+ amount = Decimal(description='Transaction amount')@classmethod@permission_required('order.manage_orders')diff --git a/saleor/graphql/payment/resolvers.py b/saleor/graphql/payment/resolvers.pyindex 9df4f4537c..0bbf69240b 100644--- a/saleor/graphql/payment/resolvers.py+++ b/saleor/graphql/payment/resolvers.py@@ -6,10 +6,12 @@ PAYMENT_SEARCH_FIELDS = ['id']def resolve_payment_methods(info, query):+ # FIXME Add testsqueryset = models.PaymentMethod.objects.all().distinct()queryset = filter_by_query_param(queryset, query, PAYMENT_SEARCH_FIELDS)return querysetdef resolve_payment_client_token(gateway=None):+ # FIXME Add testsreturn gateway_get_client_token(gateway)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex b524cc82d6..62efda1c46 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -889,7 +889,7 @@ type Mutations {pageCreate(input: PageInput!): PageCreatepageDelete(id: ID!): PageDeletepageUpdate(id: ID!, input: PageInput!): PageUpdate- paymentMethodCharge(amount: Decimal, paymentMethodId: ID!): PaymentMethodCapture+ paymentMethodCapture(amount: Decimal, paymentMethodId: ID!): PaymentMethodCapturepaymentMethodRefund(amount: Decimal, paymentMethodId: ID!): PaymentMethodRefundpaymentMethodVoid(paymentMethodId: ID!): PaymentMethodVoidsaleCreate(input: SaleInput!): SaleCreate@@ -1189,7 +1189,7 @@ type PaymentMethod implements Node {isActive: Boolean!created: DateTime!modified: DateTime!- chargeStatus: PaymentMethodChargeStatus!+ chargeStatus: ChargeStatus!billingFirstName: String!billingLastName: String!billingAddress1: String!@@ -1216,7 +1216,7 @@ type PaymentMethodCapture {paymentMethod: PaymentMethod}-enum PaymentMethodChargeStatus {+enum ChargeStatus {CHARGEDNOT_CHARGEDFULLY_REFUNDEDdiff --git a/saleor/order/__init__.py b/saleor/order/__init__.pyindex ebbed6b769..870166bcc0 100644--- a/saleor/order/__init__.py+++ b/saleor/order/__init__.py@@ -11,6 +11,7 @@ class OrderAppConfig(AppConfig):name = 'saleor.order'def ready(self):+ #FIXME should work with new dashboardfrom payments.signals import status_changedfrom .signals import order_status_changestatus_changed.connect(order_status_change)diff --git a/saleor/order/forms.py b/saleor/order/forms.pyindex 2699a43c9b..eaf148e9ee 100644--- a/saleor/order/forms.py+++ b/saleor/order/forms.py@@ -3,7 +3,7 @@ from django.conf import settingsfrom django.utils.translation import pgettext_lazyfrom ..account.forms import SignupForm-from ..payment import PaymentMethodChargeStatus, can_be_voided+from ..payment import can_be_voidedfrom ..payment.models import PaymentMethodfrom .models import Orderdiff --git a/saleor/order/migrations/0001_initial.py b/saleor/order/migrations/0001_initial.pyindex 39ff15d6bf..7d34431e81 100644--- a/saleor/order/migrations/0001_initial.py+++ b/saleor/order/migrations/0001_initial.py@@ -104,7 +104,7 @@ class Migration(migrations.Migration):('billing_address_1', models.CharField(max_length=256, blank=True)),('billing_address_2', models.CharField(max_length=256, blank=True)),('billing_city', models.CharField(max_length=256, blank=True)),- ('billing_postcode', models.CharField(max_length=256, blank=True)),+ ('billing_postal_code', models.CharField(max_length=256, blank=True)),('billing_country_code', models.CharField(max_length=2, blank=True)),('billing_country_area', models.CharField(max_length=256, blank=True)),('billing_email', models.EmailField(max_length=254, blank=True)),diff --git a/saleor/order/models.py b/saleor/order/models.pyindex ec515d8d03..b88eeac272 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -19,12 +19,13 @@ from prices import Money, TaxedMoneyfrom . import FulfillmentStatus, OrderEvents, OrderStatus, display_order_eventfrom ..account.models import Address+from ..core import zero_moneyfrom ..core.utils import build_absolute_urifrom ..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 PaymentMethodChargeStatus+from ..payment import ChargeStatusfrom ..shipping.models import ShippingMethod@@ -97,17 +98,20 @@ class Order(models.Model):token = models.CharField(max_length=36, unique=True, blank=True)total_net = MoneyField(currency=settings.DEFAULT_CURRENCY, max_digits=12,- decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=zero_money)total_gross = MoneyField(currency=settings.DEFAULT_CURRENCY, max_digits=12,- decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=zero_money)total = TaxedMoneyField(net_field='total_net', gross_field='total_gross')voucher = models.ForeignKey(Voucher, blank=True, null=True, related_name='+',on_delete=models.SET_NULL)discount_amount = MoneyField(currency=settings.DEFAULT_CURRENCY, max_digits=12,- decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=zero_money)discount_name = models.CharField(max_length=255, default='', blank=True)translated_discount_name = models.CharField(max_length=255, default='', blank=True)@@ -131,8 +135,8 @@ class Order(models.Model):def is_fully_paid(self):payments = self.payment_methods.filter(- charge_status=PaymentMethodChargeStatus.CHARGED)- total_captured = [payment.get_captured_money() for payment in payments]+ charge_status=ChargeStatus.CHARGED)+ total_captured = [payment.captured_amount for payment in payments]total_paid = sum(total_captured, ZERO_TAXED_MONEY)return total_paid.gross >= self.total.gross@@ -158,7 +162,7 @@ class Order(models.Model):return reverse('order:details', kwargs={'token': self.token})def get_last_payment(self):- return max(self.payments.all(), default=None, key=attrgetter('pk'))+ return max(self.payment_methods.all(), default=None, key=attrgetter('pk'))def get_last_payment_status(self):last_payment = self.get_last_payment()@@ -177,7 +181,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 not self.payment_methods.filter(is_active=True).exists()+ return self.payment_methods.filter(is_active=True).exists()@propertydef quantity_fulfilled(self):diff --git a/saleor/order/views.py b/saleor/order/views.pyindex 240c811569..5ba923fda8 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -15,12 +15,12 @@ from . import FulfillmentStatusfrom ..account.forms import LoginFormfrom ..account.models import Userfrom ..core.utils import get_client_ip+from ..payment import ChargeStatusfrom ..payment.forms import PaymentMethodFormfrom ..payment.models import PaymentMethod-from ..payment import PaymentMethodChargeStatusfrom .forms import (CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentMethodsForm)-from .models import Order, Payment+from .models import Orderfrom .utils import attach_order_to_user, check_order_statuslogger = logging.getLogger(__name__)@@ -54,13 +54,13 @@ def payment(request, token):orders = orders.select_related('billing_address', 'shipping_address', 'user')order = get_object_or_404(orders, token=token)- payments = order.payments.all()+ payments = order.payment_methods.all()form_data = request.POST or Nonetry:- waiting_payment = order.payments.filter(+ waiting_payment = payments.filter(is_active=True,- charge_status=PaymentMethodChargeStatus.NOT_CHARGED)- except Payment.DoesNotExist:+ charge_status=ChargeStatus.NOT_CHARGED).get()+ except PaymentMethod.DoesNotExist:waiting_payment = Nonewaiting_payment_form = Noneelse:@@ -89,15 +89,13 @@ def start_payment(request, order, variant):billing = order.billing_addresstotal = order.totaldefaults = {- 'total': total.gross.amount,- 'tax': total.tax.amount,- 'currency': total.currency,+ 'total': total,'billing_first_name': billing.first_name,'billing_last_name': billing.last_name,'billing_address_1': billing.street_address_1,'billing_address_2': billing.street_address_2,'billing_city': billing.city,- 'billing_postcode': billing.postal_code,+ 'billing_postal_code': billing.postal_code,'billing_country_code': billing.country.code,'billing_email': order.user_email,'billing_country_area': billing.country_area,diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex ce3056cf0d..d6ed9d06d2 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -33,7 +33,7 @@ class TransactionType:(VOID, pgettext_lazy('transaction type', 'Void'))]-class PaymentMethodChargeStatus:+class ChargeStatus:"""- Charged: Funds were taken off the customer founding source, partly orcompletly covering the payment amount.@@ -74,4 +74,4 @@ def get_provider(provider_name):def can_be_voided(payment):- return payment.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+ return payment.charge_status == ChargeStatus.NOT_CHARGEDdiff --git a/saleor/payment/forms.py b/saleor/payment/forms.pyindex 78da79ffb1..be5862bbb3 100644--- a/saleor/payment/forms.py+++ b/saleor/payment/forms.py@@ -7,7 +7,7 @@ from .models import PaymentMethodclass PaymentMethodForm(forms.ModelForm):class Meta:model = PaymentMethod- fields = ['variant', 'is_active', 'total', 'charge_status']+ fields = ['variant', 'is_active', 'charge_status']def authorize_payment(self):self.instance.transactions.create(diff --git a/saleor/payment/migrations/0001_initial.py b/saleor/payment/migrations/0001_initial.pyindex f207d4b7d9..bd3fd582a1 100644--- a/saleor/payment/migrations/0001_initial.py+++ b/saleor/payment/migrations/0001_initial.py@@ -1,9 +1,10 @@-# Generated by Django 2.0.3 on 2018-08-14 12:04+# Generated by Django 2.1.1 on 2018-10-17 11:03-from decimal import Decimalimport django.contrib.postgres.fields.jsonbfrom django.db import migrations, modelsimport django.db.models.deletion+import django_prices.models+import saleor.coreclass Migration(migrations.Migration):@@ -11,8 +12,8 @@ class Migration(migrations.Migration):initial = Truedependencies = [- ('checkout', '0001_initial'),- ('order', '0051_merge_20180807_0704'),+ ('order', '0065_auto_20181017_0603'),+ ('checkout', '0017_auto_20181017_0603'),]operations = [@@ -30,31 +31,31 @@ class Migration(migrations.Migration):('billing_address_1', models.CharField(blank=True, max_length=256)),('billing_address_2', models.CharField(blank=True, max_length=256)),('billing_city', models.CharField(blank=True, max_length=256)),- ('billing_postcode', models.CharField(blank=True, max_length=256)),+ ('billing_postal_code', models.CharField(blank=True, max_length=256)),('billing_country_code', models.CharField(blank=True, max_length=2)),('billing_country_area', models.CharField(blank=True, max_length=256)),('billing_email', models.EmailField(blank=True, max_length=254)),('customer_ip_address', models.GenericIPAddressField(blank=True, null=True)),('extra_data', models.TextField(blank=True, default='')),('token', models.CharField(blank=True, default='', max_length=36)),- ('total', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=9)),- ('currency', models.CharField(max_length=10)),- ('captured_amount', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=9)),- ('tax', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=9)),+ ('total_net', django_prices.models.MoneyField(currency='USD', decimal_places=2, default=saleor.core.zero_money, max_digits=12)),+ ('total_gross', django_prices.models.MoneyField(currency='USD', decimal_places=2, default=saleor.core.zero_money, max_digits=12)),+ ('captured_amount', django_prices.models.MoneyField(currency='USD', decimal_places=2, default=saleor.core.zero_money, max_digits=12)),('checkout', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='payment_methods', to='checkout.Cart')),- ('order', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='payment_methods', to='order.Order')),+ ('order', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='payment_methods', to='order.Order')),],),migrations.CreateModel(name='Transaction',fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),+ ('created', models.DateTimeField(auto_now_add=True)),('token', models.CharField(blank=True, default='', max_length=64)),- ('transaction_type', models.CharField(choices=[('auth', 'Authorization'), ('charge', 'Charge'), ('refund', 'Refund'), ('void', 'Void')], max_length=10)),+ ('transaction_type', models.CharField(choices=[('auth', 'Authorization'), ('capture', 'Charge'), ('refund', 'Refund'), ('capture', 'Capture'), ('void', 'Void')], max_length=10)),('is_success', models.BooleanField(default=False)),- ('amount', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=9)),+ ('amount', django_prices.models.MoneyField(currency='USD', decimal_places=2, default=saleor.core.zero_money, max_digits=12)),('gateway_response', django.contrib.postgres.fields.jsonb.JSONField()),- ('payment_method', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='payment.PaymentMethod')),+ ('payment_method', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transactions', to='payment.PaymentMethod')),],),]diff --git a/saleor/payment/migrations/0002_auto_20181012_0517.py b/saleor/payment/migrations/0002_auto_20181012_0517.pydeleted file mode 100644index 5612656c7e..0000000000--- a/saleor/payment/migrations/0002_auto_20181012_0517.py+++ /dev/null@@ -1,41 +0,0 @@-# Generated by Django 2.1.1 on 2018-10-12 10:17--from django.db import migrations, models-import django.db.models.deletion---class Migration(migrations.Migration):-- dependencies = [- ('payment', '0001_initial'),- ]-- operations = [- migrations.AddField(- model_name='transaction',- name='created',- field=models.DateTimeField(auto_now_add=True, default=None),- preserve_default=False,- ),- migrations.AddField(- model_name='transaction',- name='currency',- field=models.CharField(default=None, editable=False, max_length=10),- preserve_default=False,- ),- migrations.AlterField(- model_name='paymentmethod',- name='order',- field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='payment_methods', to='order.Order'),- ),- migrations.AlterField(- model_name='transaction',- name='payment_method',- field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transactions', to='payment.PaymentMethod'),- ),- migrations.AlterField(- model_name='transaction',- name='transaction_type',- field=models.CharField(choices=[('auth', 'Authorization'), ('capture', 'Charge'), ('refund', 'Refund'), ('capture', 'Capture'), ('void', 'Void')], max_length=10),- ),- ]diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex 53de034ff0..5ebb6f8c28 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -1,11 +1,11 @@-from decimal import Decimal-+from django.conf import settingsfrom django.contrib.postgres.fields import JSONFieldfrom django.db import models-from prices import Money+from django_prices.models import MoneyField, TaxedMoneyField-from . import PaymentMethodChargeStatus, TransactionType+from . import ChargeStatus, TransactionTypefrom ..checkout.models import Cart+from ..core import zero_moneyfrom ..order.models import Order@@ -31,14 +31,16 @@ class PaymentMethod(models.Model):modified = models.DateTimeField(auto_now=True)charge_status = models.CharField(max_length=15,- choices=PaymentMethodChargeStatus.CHOICES,- default=PaymentMethodChargeStatus.NOT_CHARGED)+ choices=ChargeStatus.CHOICES,+ default=ChargeStatus.NOT_CHARGED)++ # FIXME assign it as a separate Address instance?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)billing_address_2 = models.CharField(max_length=256, blank=True)billing_city = models.CharField(max_length=256, blank=True)- billing_postcode = models.CharField(max_length=256, blank=True)+ billing_postal_code = models.CharField(max_length=256, blank=True)billing_country_code = models.CharField(max_length=2, blank=True)billing_country_area = models.CharField(max_length=256, blank=True)billing_email = models.EmailField(blank=True)@@ -46,14 +48,19 @@ class PaymentMethod(models.Model):extra_data = models.TextField(blank=True, default='')token = models.CharField(max_length=36, blank=True, default='')- # FIXME refactor to MoneyField- total = models.DecimalField(- max_digits=9, decimal_places=2, default=Decimal('0.0'))- currency = models.CharField(max_length=10)- captured_amount = models.DecimalField(- max_digits=9, decimal_places=2, default=Decimal('0.0'))- tax = models.DecimalField(- max_digits=9, decimal_places=2, default=Decimal('0.0'))+ total_net = MoneyField(+ currency=settings.DEFAULT_CURRENCY, max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=zero_money)+ total_gross = MoneyField(+ currency=settings.DEFAULT_CURRENCY, max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=zero_money)+ total = TaxedMoneyField(net_field='total_net', gross_field='total_gross')+ captured_amount = MoneyField(+ 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',@@ -62,18 +69,6 @@ class PaymentMethod(models.Model):Order, null=True, related_name='payment_methods',on_delete=models.PROTECT)- def _get_money(self, amount):- return Money(amount=amount, currency=self.currency)-- def get_total(self):- return self._get_money(self.total)-- def get_captured_money(self):- return self._get_money(self.captured_amount)-- def get_tax_money(self):- return self._get_money(self.tax)-def get_auth_transaction(self):txn = self.transactions.get(transaction_type=TransactionType.AUTH, is_success=True)@@ -118,11 +113,9 @@ class Transaction(models.Model):# FIXME probably we should have error/pending/success status instead of# a bool, eg for payments with 3d secureis_success = models.BooleanField(default=False)- amount = models.DecimalField(- max_digits=9, decimal_places=2, default=Decimal('0.0'))- currency = models.CharField(max_length=10, editable=False)+ amount = MoneyField(+ currency=settings.DEFAULT_CURRENCY, max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=zero_money)gateway_response = JSONField()-- def get_amount(self):- return Money(amount=self.amount, currency=self.currency)diff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.pyindex 1ee895e0a5..f3e4c6134d 100644--- a/saleor/payment/providers/braintree/__init__.py+++ b/saleor/payment/providers/braintree/__init__.py@@ -1,8 +1,8 @@from typing import Dict-import braintree as braintree_sdkfrom django.core.exceptions import ImproperlyConfiguredfrom django.utils.translation import pgettext_lazy+import braintree as braintree_sdkfrom ... import TransactionTypefrom ...utils import create_transaction@@ -88,10 +88,8 @@ def get_client_token(**client_kwargs):def authorize(payment_method, transaction_token, **client_kwargs):gateway = get_gateway(**client_kwargs)result = gateway.transaction.sale({- 'amount':- payment_method.total,- 'payment_method_nonce':- transaction_token,+ 'amount': str(payment_method.total.gross.amount),+ 'payment_method_nonce': transaction_token,'options': {'submit_for_settlement': AUTO_CHARGE,'three_d_secure': {'required': THREE_D_SECURE_REQUIRED}}})@@ -100,7 +98,7 @@ def authorize(payment_method, transaction_token, **client_kwargs):txn = create_transaction(payment_method=payment_method,transaction_type=TransactionType.AUTH,- amount=payment_method.total,+ amount=payment_method.total.gross.amount,gateway_response=gateway_response,token=result.transaction.id,is_success=result.is_success)@@ -114,7 +112,7 @@ def capture(payment_method, amount=None, **client_kwargs):auth_transaction = payment_method.transactions.filter(transaction_type=TransactionType.AUTH).first()if not amount:- amount = payment_method.total+ amount = payment_method.total.gross.amountresult = gateway.transaction.submit_for_settlement(transaction_id=auth_transaction.token, amount=amount)gateway_response = extract_gateway_response(result)@@ -142,7 +140,7 @@ def void(payment_method, **client_kwargs):txn = create_transaction(payment_method=payment_method,transaction_type=TransactionType.VOID,- amount=payment_method.total,+ amount=payment_method.total.gross.amount,gateway_response=gateway_response,token=result.transaction.id,is_success=result.is_success)diff --git a/saleor/payment/providers/dummy/__init__.py b/saleor/payment/providers/dummy/__init__.pyindex b2776f58e0..244d37a976 100644--- a/saleor/payment/providers/dummy/__init__.py+++ b/saleor/payment/providers/dummy/__init__.py@@ -20,7 +20,7 @@ def authorize(payment_method, transaction_token, **client_kwargs):txn = create_transaction(payment_method=payment_method,transaction_type=TransactionType.AUTH,- amount=payment_method.total,+ amount=payment_method.total.gross,gateway_response={},token=str(uuid.uuid4()),is_success=success)@@ -35,7 +35,7 @@ def void(payment_method, **client_kwargs):txn = create_transaction(payment_method=payment_method,transaction_type=TransactionType.VOID,- amount=payment_method.total,+ amount=payment_method.total.gross,gateway_response={},token=str(uuid.uuid4()),is_success=success)diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 6a4a741350..cb4a0874f3 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -2,10 +2,11 @@ from decimal import Decimalfrom functools import wrapsfrom typing import Dict, Optional+from django.conf import settingsfrom django.db import transaction+from prices import Money-from . import (- PaymentError, PaymentMethodChargeStatus, can_be_voided, get_provider)+from . import ChargeStatus, PaymentError, can_be_voided, get_providerfrom .models import PaymentMethod, Transaction@@ -14,7 +15,7 @@ def validate_payment_method(view):can be performed on it."""@wraps(view)- def func(payment_method, *args, **kwargs):+ def func(payment_method: PaymentMethod, *args, **kwargs):if not payment_method.is_active:raise PaymentError('This payment method is no longer active.')return view(payment_method, *args, **kwargs)@@ -40,14 +41,18 @@ def create_transaction(return txn-def gateway_get_client_token(provider_name):+def gateway_get_client_token(provider_name: str):+ # FIXME Add tests+provider, provider_params = get_provider(provider_name)return provider.get_client_token(**provider_params)@validate_payment_method-def gateway_authorize(payment_method, transaction_token) -> Transaction:- if not payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED:+def gateway_authorize(+ payment_method: PaymentMethod,+ transaction_token: str) -> Transaction:+ if not payment_method.charge_status == ChargeStatus.NOT_CHARGED:raise PaymentError('Charged transactions cannot be authorized again.')provider, provider_params = get_provider(payment_method.variant)@@ -55,7 +60,7 @@ def gateway_authorize(payment_method, transaction_token) -> Transaction:txn, error = provider.authorize(payment_method, transaction_token, **provider_params)if txn.is_success:- payment_method.charge_status = PaymentMethodChargeStatus.NOT_CHARGED+ payment_method.charge_status = ChargeStatus.NOT_CHARGEDpayment_method.save(update_fields=['charge_status'])if not txn.is_success:# TODO: Handle gateway response here somehow@@ -64,23 +69,26 @@ def gateway_authorize(payment_method, transaction_token) -> Transaction:@validate_payment_method-def gateway_capture(payment_method, amount) -> Transaction:+def gateway_capture(+ payment_method: PaymentMethod,+ amount: Decimal) -> Transaction:+ if amount <= 0:+ raise PaymentError('Amount should be a positive number.')+ amount = Money(amount, currency=settings.DEFAULT_CURRENCY)if payment_method.charge_status not in {- PaymentMethodChargeStatus.CHARGED,- PaymentMethodChargeStatus.NOT_CHARGED}:+ ChargeStatus.CHARGED,+ ChargeStatus.NOT_CHARGED}:raise PaymentError('This payment method cannot be captured.')- if amount > payment_method.total or amount > (- payment_method.total - payment_method.captured_amount):+ if amount > payment_method.total.gross or amount > (+ payment_method.total.gross - payment_method.captured_amount):raise PaymentError('Unable to capture more than authorized amount.')- if amount <= 0:- raise PaymentError('Amount should be a positive number.')provider, provider_params = get_provider(payment_method.variant)with transaction.atomic():txn, error = provider.capture(payment_method, amount=amount, **provider_params)if txn.is_success:- payment_method.charge_status = PaymentMethodChargeStatus.CHARGED+ payment_method.charge_status = ChargeStatus.CHARGEDpayment_method.captured_amount += txn.amountpayment_method.save(update_fields=['charge_status', 'captured_amount'])@@ -107,12 +115,15 @@ def gateway_void(payment_method) -> Transaction:@validate_payment_method-def gateway_refund(payment_method, amount) -> Transaction:- if amount > payment_method.captured_amount:- raise PaymentError('Cannot refund more than captured')+def gateway_refund(+ payment_method,+ amount: Decimal) -> Transaction:if amount <= 0:raise PaymentError('Amount should be a positive number.')- if not payment_method.charge_status == PaymentMethodChargeStatus.CHARGED:+ amount = Money(amount, currency=settings.DEFAULT_CURRENCY)+ if amount > payment_method.captured_amount:+ raise PaymentError('Cannot refund more than captured')+ if not payment_method.charge_status == ChargeStatus.CHARGED:raise PaymentError('Refund is possible only when transaction is captured.')@@ -121,8 +132,8 @@ def gateway_refund(payment_method, amount) -> Transaction:txn, error = provider.refund(payment_method, amount, **provider_params)if txn.is_success:changed_fields = ['captured_amount']- if txn.amount == payment_method.total:- payment_method.charge_status = PaymentMethodChargeStatus.FULLY_REFUNDED+ if txn.amount == payment_method.total.gross:+ payment_method.charge_status = ChargeStatus.FULLY_REFUNDEDpayment_method.is_active = Falsechanged_fields += ['charge_status', 'is_active']payment_method.captured_amount -= amountdiff --git a/templates/dashboard/order/detail.html b/templates/dashboard/order/detail.htmlindex 084528d8a7..da4997d5b4 100644--- a/templates/dashboard/order/detail.html+++ b/templates/dashboard/order/detail.html@@ -599,7 +599,7 @@{% render_status payment.charge_status payment.get_charge_status_display %}</td><td>- {{ payment.total|currencyfmt:payment.currency }}+ {% price payment.total %}</td></tr>{% endfor %}diff --git a/templates/dashboard/order/modal/capture.html b/templates/dashboard/order/modal/capture.htmlindex ea38f8903a..d4d4114c97 100644--- a/templates/dashboard/order/modal/capture.html+++ b/templates/dashboard/order/modal/capture.html@@ -25,7 +25,7 @@{% price payment.order.total.tax %}</li><li class="list-item">{% trans "Captured amount:" context "Modal capture payment list title" %}- {{ captured|currencyfmt:currency }}+ {% price captured %}</li></ul></div>diff --git a/templates/dashboard/order/modal/refund.html b/templates/dashboard/order/modal/refund.htmlindex 78568e7b5c..7d41475a18 100644--- a/templates/dashboard/order/modal/refund.html+++ b/templates/dashboard/order/modal/refund.html@@ -26,7 +26,7 @@{% price payment.order.total.tax %}</li><li class="list-item">{% trans "Captured amount:" context "Modal refund payment list title" %}- {{ captured|currencyfmt:currency }}+ {% price captured %}</li></ul></div>diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex d9000c48fb..0a70680e9c 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -385,18 +385,18 @@ def test_checkout_complete(checkout.shipping_address = addresscheckout.shipping_method = shipping_methodcheckout.save()- total = checkout.get_total().gross+ total = checkout.get_total()payment_method = payment_method_dummy- payment_method.total = total.amount- payment_method.currency = total.currency+ payment_method.is_active = True+ payment_method.total = total+ payment_method.captured_amount = total.grosspayment_method.checkout = checkout+ payment_method.save()payment_method.transactions.create(transaction_type=TransactionType.AUTH,is_success=True,gateway_response={},- amount=total.amount)- payment_method.save()-+ amount=total.gross.amount)checkout_id = graphene.Node.to_global_id('Checkout', checkout.pk)query = """@@ -414,15 +414,16 @@ def test_checkout_complete(}"""variables = {'checkoutId': checkout_id}- assert not Order.objects.exists()+ orders_count = Order.objects.count()response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response)data = content['data']['checkoutComplete']assert not data['errors']order_token = data['order']['token']- order = Order.objects.get()+ assert Order.objects.count() == orders_count + 1+ order = Order.objects.last()assert order.token == order_token- assert order.total.gross == total+ assert order.total.gross == total.grosscheckout_line = checkout.lines.first()order_line = order.lines.first()assert checkout_line.quantity == order_line.quantitydiff --git a/tests/api/test_order.py b/tests/api/test_order.pyindex 0a7abf76d1..21ab1caa36 100644--- a/tests/api/test_order.py+++ b/tests/api/test_order.py@@ -3,7 +3,6 @@ from unittest.mock import MagicMock, Mockimport pytestimport graphene-from payments import PaymentStatusfrom saleor.account.models import Addressfrom saleor.core.utils.taxes import ZERO_TAXED_MONEYfrom saleor.graphql.core.types import ReportingPeriod@@ -16,7 +15,8 @@ from saleor.graphql.order.types import (OrderEventsEmailsEnum, PaymentStatusEnum, OrderStatusFilter)from saleor.order import (CustomPaymentChoices, OrderEvents, OrderEventsEmails, OrderStatus)-from saleor.order.models import Order, OrderEvent, Payment+from saleor.order.models import Order, OrderEvent+from saleor.payment.models import PaymentMethodfrom saleor.shipping.models import ShippingMethodfrom tests.api.utils import get_graphql_content@@ -911,8 +911,9 @@ def test_order_cancel(def test_order_capture(- staff_api_client, permission_manage_orders, payment_preauth, staff_user):- order = payment_preauth.order+ staff_api_client, permission_manage_orders,+ payment_method_txn_preauth, staff_user):+ order = payment_method_txn_preauth.orderquery = """mutation captureOrder($id: ID!, $amount: Decimal!) {orderCapture(id: $id, amount: $amount) {@@ -927,14 +928,14 @@ def test_order_capture(}"""order_id = graphene.Node.to_global_id('Order', order.id)- amount = float(payment_preauth.get_total().gross.amount)+ amount = float(payment_method_txn_preauth.total.gross.amount)variables = {'id': order_id, 'amount': amount}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)data = content['data']['orderCapture']['order']order.refresh_from_db()- assert data['paymentStatus'] == PaymentStatusEnum.CONFIRMED.name+ assert data['paymentStatus'] == PaymentStatusEnum.CHARGED.nameassert data['isPaid']assert data['totalCaptured']['amount'] == float(amount)@@ -953,8 +954,9 @@ def test_order_capture(def test_paid_order_mark_as_paid(- staff_api_client, permission_manage_orders, payment_preauth):- order = payment_preauth.order+ staff_api_client, permission_manage_orders,+ payment_method_txn_preauth):+ order = payment_method_txn_preauth.orderquery = """mutation markPaid($id: ID!) {orderMarkAsPaid(id: $id) {@@ -1012,8 +1014,9 @@ def test_order_mark_as_paid(def test_order_release(- staff_api_client, permission_manage_orders, payment_preauth, staff_user):- order = payment_preauth.order+ staff_api_client, permission_manage_orders, payment_method_txn_preauth,+ staff_user):+ order = payment_method_txn_preauth.orderquery = """mutation releaseOrder($id: ID!) {orderRelease(id: $id) {@@ -1029,15 +1032,16 @@ def test_order_release(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)data = content['data']['orderRelease']['order']- assert data['paymentStatus'] == PaymentStatusEnum.REFUNDED.name+ assert data['paymentStatus'] == PaymentStatusEnum.NOT_CHARGED.nameevent_payment_released = order.events.last()assert event_payment_released.type == OrderEvents.PAYMENT_RELEASED.valueassert event_payment_released.user == staff_userdef test_order_refund(- staff_api_client, permission_manage_orders, payment_confirmed):- order = order = payment_confirmed.order+ staff_api_client, permission_manage_orders,+ payment_method_txn_captured):+ order = order = payment_method_txn_captured.orderquery = """mutation refundOrder($id: ID!, $amount: Decimal!) {orderRefund(id: $id, amount: $amount) {@@ -1050,7 +1054,7 @@ def test_order_refund(}"""order_id = graphene.Node.to_global_id('Order', order.id)- amount = float(payment_confirmed.get_total().gross.amount)+ amount = float(payment_method_txn_captured.total.gross.amount)variables = {'id': order_id, 'amount': amount}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])@@ -1058,7 +1062,7 @@ def test_order_refund(data = content['data']['orderRefund']['order']order.refresh_from_db()assert data['status'] == order.status.upper()- assert data['paymentStatus'] == PaymentStatusEnum.REFUNDED.name+ assert data['paymentStatus'] == PaymentStatusEnum.FULLY_REFUNDED.nameassert data['isPaid'] == Falseorder_event = order.events.last()@@ -1067,22 +1071,22 @@ def test_order_refund(def test_clean_order_release_payment():- payment = MagicMock(spec=Payment)- payment.status = 'not preauth'+ payment = MagicMock(spec=PaymentMethod)+ payment.is_active = Falseerrors = clean_release_payment(payment, [])assert errors[0].field == 'payment'assert errors[0].message == 'Only pre-authorized payments can be released'- payment.status = PaymentStatus.PREAUTH+ payment.is_active = Trueerror_msg = 'error has happened.'- payment.release = Mock(side_effect=ValueError(error_msg))+ payment.void = Mock(side_effect=ValueError(error_msg))errors = clean_release_payment(payment, [])assert errors[0].field == 'payment'assert errors[0].message == error_msgdef test_clean_order_refund_payment():- payment = MagicMock(spec=Payment)+ payment = MagicMock(spec=PaymentMethod)payment.variant = CustomPaymentChoices.MANUALamount = Mock(spec='string')errors = clean_refund_payment(payment, amount, [])@@ -1098,14 +1102,15 @@ def test_clean_order_capture():'There\'s no payment associated with the order.')-def test_clean_order_mark_as_paid(payment_preauth):- order = payment_preauth.order+def test_clean_order_mark_as_paid(payment_method_txn_preauth):+ order = payment_method_txn_preauth.ordererrors = clean_order_mark_as_paid(order, [])assert errors[0].field == 'payment'assert errors[0].message == ('Orders with payments can not be manually marked as paid.')- order.payments.all().delete()++def test_clean_order_mark_as_paid_no_payments(order):assert clean_order_mark_as_paid(order, []) == []diff --git a/tests/api/test_payment.py b/tests/api/test_payment.pyindex e8b4549459..bc865a8c95 100644--- a/tests/api/test_payment.py+++ b/tests/api/test_payment.py@@ -1,6 +1,6 @@import graphenefrom saleor.payment.models import (- PaymentMethodChargeStatus, Transaction, TransactionType)+ ChargeStatus, Transaction, TransactionType)from tests.api.utils import get_graphql_content@@ -57,6 +57,7 @@ def test_checkout_add_payment_method('gateway': 'DUMMY','transactionToken': 'sample-token','amount': str(cart.get_total().gross.amount),+ 'tax': str(cart.get_total().tax.amount),'billingAddress': graphql_address_data,'storePaymentMethod': False}}response = user_api_client.post_graphql(CREATE_QUERY, variables)@@ -68,16 +69,16 @@ def test_checkout_add_payment_method(txn = Transaction.objects.filter(token=transaction_id).first()assert txn.transaction_type == TransactionType.AUTHassert txn is not None- payment_method = txn.payment_method- assert payment_method.checkout == cart- assert payment_method.is_active- assert payment_method.total == cart.get_total().gross.amount- assert payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+ payment = txn.payment_method+ assert payment.checkout == cart+ assert payment.is_active+ assert payment.total == cart.get_total()+ assert payment.charge_status == ChargeStatus.NOT_CHARGEDCHARGE_QUERY = """mutation PaymentMethodCharge($paymentMethodId: ID!, $amount: Decimal!) {- paymentMethodCharge(paymentMethodId: $paymentMethodId, amount: $amount) {+ paymentMethodCapture(paymentMethodId: $paymentMethodId, amount: $amount) {paymentMethod {id,chargeStatus@@ -94,20 +95,20 @@ 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 == PaymentMethodChargeStatus.NOT_CHARGED+ assert payment_method.charge_status == ChargeStatus.NOT_CHARGEDpayment_method_id = graphene.Node.to_global_id('PaymentMethod', payment_method_dummy.pk)variables = {'paymentMethodId': payment_method_id,- 'amount': payment_method_dummy.total}+ 'amount': str(payment_method_dummy.total.gross.amount)}response = staff_api_client.post_graphql(CHARGE_QUERY, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content['data']['paymentMethodCharge']+ data = content['data']['paymentMethodCapture']assert not data['errors']payment_method_dummy.refresh_from_db()- assert payment_method.charge_status == PaymentMethodChargeStatus.CHARGED+ assert payment_method.charge_status == ChargeStatus.CHARGEDassert payment_method.transactions.count() == 1txn = payment_method.transactions.first()assert txn.transaction_type == TransactionType.CHARGE@@ -117,24 +118,24 @@ def test_payment_method_charge_gateway_error(staff_api_client, permission_manage_orders, payment_method_dummy,monkeypatch):payment_method = payment_method_dummy- assert payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+ assert payment_method.charge_status == ChargeStatus.NOT_CHARGEDpayment_method_id = graphene.Node.to_global_id('PaymentMethod', payment_method_dummy.pk)variables = {'paymentMethodId': payment_method_id,- 'amount': payment_method_dummy.total}+ 'amount': str(payment_method_dummy.total.gross.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']['paymentMethodCharge']+ data = content['data']['paymentMethodCapture']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 == PaymentMethodChargeStatus.NOT_CHARGED+ assert payment_method.charge_status == ChargeStatus.NOT_CHARGEDassert payment_method.transactions.count() == 1txn = payment_method.transactions.first()assert txn.transaction_type == TransactionType.CHARGE@@ -160,22 +161,22 @@ 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 = PaymentMethodChargeStatus.CHARGED- payment_method.captured_amount = payment_method.total+ payment_method.charge_status = ChargeStatus.CHARGED+ payment_method.captured_amount = payment_method.total.grosspayment_method.save()payment_method_id = graphene.Node.to_global_id('PaymentMethod', payment_method.pk)variables = {'paymentMethodId': payment_method_id,- 'amount': payment_method_dummy.total}+ 'amount': str(payment_method_dummy.total.gross.amount)}response = staff_api_client.post_graphql(REFUND_QUERY, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)data = content['data']['paymentMethodRefund']assert not data['errors']payment_method_dummy.refresh_from_db()- assert payment_method.charge_status == PaymentMethodChargeStatus.FULLY_REFUNDED+ assert payment_method.charge_status == ChargeStatus.FULLY_REFUNDEDassert payment_method.transactions.count() == 1txn = payment_method.transactions.first()assert txn.transaction_type == TransactionType.REFUND@@ -185,14 +186,14 @@ def test_payment_method_refund_error(staff_api_client, permission_manage_orders, payment_method_dummy,monkeypatch):payment_method = payment_method_dummy- payment_method.charge_status = PaymentMethodChargeStatus.CHARGED- payment_method.captured_amount = payment_method.total+ payment_method.charge_status = ChargeStatus.CHARGED+ payment_method.captured_amount = payment_method.total.grosspayment_method.save()payment_method_id = graphene.Node.to_global_id('PaymentMethod', payment_method_dummy.pk)variables = {'paymentMethodId': payment_method_id,- 'amount': payment_method.total}+ 'amount': str(payment_method.total.gross.amount)}monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)response = staff_api_client.post_graphql(@@ -204,7 +205,7 @@ def test_payment_method_refund_error(assert data['errors'][0]['field'] is Noneassert data['errors'][0]['message']payment_method_dummy.refresh_from_db()- assert payment_method.charge_status == PaymentMethodChargeStatus.CHARGED+ assert payment_method.charge_status == ChargeStatus.CHARGEDassert payment_method.transactions.count() == 1txn = payment_method.transactions.first()assert txn.transaction_type == TransactionType.REFUNDdiff --git a/tests/conftest.py b/tests/conftest.pyindex 1dc28b4010..acb37a91f8 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -29,8 +29,8 @@ from saleor.order import OrderStatus, OrderEventsfrom saleor.order.models import Order, OrderEventfrom saleor.order.utils import recalculate_orderfrom saleor.page.models import Page+from saleor.payment import ChargeStatus, TransactionTypefrom saleor.payment.models import PaymentMethod-from saleor.payment import TransactionType, PaymentMethodChargeStatusfrom saleor.product.models import (Attribute, AttributeTranslation, AttributeValue, Category, Collection,Product, ProductImage, ProductTranslation, ProductType, ProductVariant)@@ -466,25 +466,15 @@ def draft_order(order_with_lines):return order_with_lines-def payment_preauth(order_with_lines):- return order_with_lines.payments.create(- variant='default', status=PaymentStatus.PREAUTH,- fraud_status=FraudStatus.ACCEPT, currency='USD',- total=order_with_lines.total.gross.amount,- tax=order_with_lines.total.tax.amount)--@pytest.fixture()def payment_method_txn_preauth(order_with_lines, payment_method_dummy):order = order_with_linespayment = payment_method_dummypayment.order = order- payment.total = order.total.gross.amountpayment.save()payment.transactions.create(- amount=payment.total,+ amount=payment.total.gross,transaction_type=TransactionType.AUTH,gateway_response={},is_success=True)@@ -496,13 +486,12 @@ def payment_method_txn_captured(order_with_lines, payment_method_dummy):order = order_with_linespayment = payment_method_dummypayment.order = order- payment.total = order.total.gross.amount- payment.charge_status = PaymentMethodChargeStatus.CHARGED- payment.captured_amount = payment.total+ payment.charge_status = ChargeStatus.CHARGED+ payment.captured_amount = payment.total.grosspayment.save()payment.transactions.create(- amount=payment.total,+ amount=payment.total.gross,transaction_type=TransactionType.CAPTURE,gateway_response={},is_success=True)@@ -514,14 +503,12 @@ def payment_method_txn_refunded(order_with_lines, payment_method_dummy):order = order_with_linespayment = payment_method_dummypayment.order = order- payment.total = order.total.gross.amount- payment.charge_status = PaymentMethodChargeStatus.FULLY_REFUNDED- payment.captured_amount = 0+ payment.charge_status = ChargeStatus.FULLY_REFUNDEDpayment.is_active = Falsepayment.save()payment.transactions.create(- amount=payment.total,+ amount=payment.total.gross,transaction_type=TransactionType.REFUND,gateway_response={},is_success=True)@@ -529,45 +516,10 @@ def payment_method_txn_refunded(order_with_lines, payment_method_dummy):@pytest.fixture()-def payment_confirmed(order_with_lines):- order_amount = order_with_lines.total_gross.amount- return order_with_lines.payments.create(- variant='default', status=PaymentStatus.CONFIRMED,- fraud_status=FraudStatus.ACCEPT, currency='USD',- total=order_amount, captured_amount=order_amount,- tax=order_with_lines.total.tax.amount)---def payment_rejected(order_with_lines):- return order_with_lines.payments.create(- variant='default', status=PaymentStatus.REJECTED,- fraud_status=FraudStatus.ACCEPT, currency='USD',- total=order_with_lines.total_gross.amount)---def payment_refunded(order_with_lines):- return order_with_lines.payments.create(- variant='default', status=PaymentStatus.REFUNDED,- fraud_status=FraudStatus.ACCEPT, currency='USD',- total=order_with_lines.total_gross.amount)---def payment_error(order_with_lines):- return order_with_lines.payments.create(- variant='default', status=PaymentStatus.ERROR,- fraud_status=FraudStatus.ACCEPT, currency='USD',- total=order_with_lines.total_gross.amount)---def payment_input(order_with_lines):- return order_with_lines.payments.create(- variant='default', status=PaymentStatus.INPUT,- fraud_status=FraudStatus.ACCEPT, currency='USD',- total=order_with_lines.total_gross.amount)+def payment_method_not_authorized(payment_method_dummy):+ payment_method_dummy.is_active = False+ payment_method_dummy.save()+ return payment_method_dummy@pytest.fixture()@@ -775,6 +727,18 @@ def product_translation_fr(product):@pytest.fixture-def payment_method_dummy(db):+def payment_method_dummy(db, order_with_lines):return PaymentMethod.objects.create(- variant='dummy', is_active=True, total=100, currency='USD')+ variant='dummy',+ order=order_with_lines,+ is_active=True,+ total=order_with_lines.total,+ billing_first_name=order_with_lines.billing_address.first_name,+ billing_last_name=order_with_lines.billing_address.last_name,+ billing_address_1=order_with_lines.billing_address.street_address_1,+ billing_address_2=order_with_lines.billing_address.street_address_2,+ billing_city=order_with_lines.billing_address.city,+ billing_postal_code=order_with_lines.billing_address.postal_code,+ billing_country_code=order_with_lines.billing_address.country.code,+ billing_country_area=order_with_lines.billing_address.country_area,+ billing_email=order_with_lines.user_email)diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.pyindex b794419369..7598bcf204 100644--- a/tests/dashboard/test_order.py+++ b/tests/dashboard/test_order.py@@ -18,7 +18,7 @@ from saleor.order import (FulfillmentStatus, OrderEvents, OrderEventsEmails, OrderStatus)from saleor.order.models import Order, OrderEvent, OrderLinefrom saleor.order.utils import add_variant_to_order, change_order_line_quantity-from saleor.payment import PaymentMethodChargeStatus, TransactionType+from saleor.payment import ChargeStatus, TransactionTypefrom saleor.product.models import ProductVariantfrom saleor.shipping.models import ShippingZone@@ -78,8 +78,9 @@ def test_view_capture_order_payment_preauth('csrfmiddlewaretoken': 'hello','amount': str(order.total.gross.amount)})assert response.status_code == 302- assert order.payment_methods.last().charge_status == PaymentMethodChargeStatus.CHARGED- assert order.payment_methods.last().captured_amount == order.total.gross.amount+ payment = order.payment_methods.last()+ assert payment.charge_status == ChargeStatus.CHARGED+ assert payment.captured_amount == order.total.gross@pytest.mark.integration@@ -95,23 +96,26 @@ def test_view_capture_order_invalid_payment_confirmed_status(response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})assert response.status_code == 400- assert order.payment_methods.last().charge_status == PaymentMethodChargeStatus.CHARGED+ payment = order.payment_methods.last()+ assert payment.charge_status == ChargeStatus.CHARGED@pytest.mark.integrationdef test_view_capture_order_invalid_payment_rejected_status(- admin_client, order_with_lines, payment_rejected):- order = order_with_lines+ admin_client, payment_method_not_authorized):+ order = payment_method_not_authorized.orderurl = reverse('dashboard:capture-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_rejected.pk})+ 'order_pk': order.pk,+ 'payment_pk': payment_method_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- assert order.payments.last().status == PaymentStatus.REJECTED+ payment = order.payment_methods.last()+ assert payment.charge_status == ChargeStatus.NOT_CHARGED@pytest.mark.integration@@ -127,7 +131,8 @@ def test_view_capture_order_invalid_payment_refunded_status(response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})assert response.status_code == 400- assert order.payment_methods.last().charge_status == PaymentMethodChargeStatus.FULLY_REFUNDED+ payment = order.payment_methods.last()+ assert payment.charge_status == ChargeStatus.FULLY_REFUNDED@pytest.mark.integration@@ -144,10 +149,11 @@ def test_view_refund_order_payment_confirmed(response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello',- 'amount': str(payment_confirmed.captured_amount)})+ 'amount': str(payment_confirmed.captured_amount.amount)})assert response.status_code == 302- assert order.payment_methods.last().charge_status == PaymentMethodChargeStatus.FULLY_REFUNDED- assert order.payment_methods.last().get_captured_money() == Money(0, 'USD')+ payment = order.payment_methods.last()+ assert payment.charge_status == ChargeStatus.FULLY_REFUNDED+ assert payment.captured_amount == Money(0, 'USD')@pytest.mark.integration@@ -181,8 +187,8 @@ def test_view_refund_order_invalid_payment_preauth_status(response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})assert response.status_code == 400- assert order.payment_methods.last().charge_status == PaymentMethodChargeStatus.NOT_CHARGED-+ payment = order.payment_methods.last()+ assert payment.charge_status == ChargeStatus.NOT_CHARGED@pytest.mark.integration@@ -199,8 +205,8 @@ def test_view_refund_order_invalid_payment_refunded_status(response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello', 'amount': '20.00'})assert response.status_code == 400- assert order.payment_methods.last().charge_status == PaymentMethodChargeStatus.FULLY_REFUNDED-+ payment = order.payment_methods.last()+ assert payment.charge_status == ChargeStatus.FULLY_REFUNDED@pytest.mark.integration@@ -218,11 +224,11 @@ def test_view_release_order_payment_preauth('csrfmiddlewaretoken': 'hello'})assert response.status_code == 302order_payment = order.payment_methods.last()- assert order_payment.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+ assert order_payment.charge_status == ChargeStatus.NOT_CHARGEDlast_transaction = order_payment.transactions.latest('pk')assert last_transaction.transaction_type == TransactionType.VOID- assert order_payment.get_captured_money() == Money(0, 'USD')+ assert order_payment.captured_amount == Money(0, 'USD')@@ -241,9 +247,8 @@ def test_view_release_order_invalid_payment_confirmed_status('csrfmiddlewaretoken': 'hello'})assert response.status_code == 400order_payment = order.payment_methods.last()- assert order_payment.charge_status == PaymentMethodChargeStatus.CHARGED- assert order_payment.get_captured_money() == order.total.gross-+ assert order_payment.charge_status == ChargeStatus.CHARGED+ assert order_payment.captured_amount == order.total.gross@pytest.mark.integration@@ -260,10 +265,9 @@ def test_view_release_order_invalid_payment_refunded_status(response = admin_client.post(url, {'csrfmiddlewaretoken': 'hello'})assert response.status_code == 400- order_payment = order.payment_methods.last()- assert order_payment.charge_status == PaymentMethodChargeStatus.FULLY_REFUNDED- assert order_payment.get_captured_money() == Money(0, 'USD')-+ payment = order.payment_methods.last()+ assert payment.charge_status == ChargeStatus.FULLY_REFUNDED+ assert payment.captured_amount == Money(0, 'USD')@pytest.mark.integrationdiff --git a/tests/test_order.py b/tests/test_order.pyindex 93fbef3a20..ae20333ae0 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -16,7 +16,7 @@ from saleor.order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order, recalculate_order,restock_fulfillment_lines, restock_order_lines, update_order_prices,update_order_status)-from saleor.payment import PaymentMethodChargeStatus+from saleor.payment import ChargeStatusfrom tests.utils import get_redirect_location@@ -366,10 +366,9 @@ def test_order_queryset_to_ship():status=OrderStatus.PARTIALLY_FULFILLED, total=total)]for order in orders_to_ship:- order.payments.create(- variant='default', status=PaymentMethodChargeStatus.CHARGED,- currency='USD', total=order.total_gross.amount,- captured_amount=order.total_gross.amount)+ order.payment_methods.create(+ variant='default', charge_status=ChargeStatus.CHARGED,+ total=order.total, captured_amount=order.total_gross)orders_not_to_ship = [Order.objects.create(status=OrderStatus.DRAFT, total=total),@@ -457,9 +456,8 @@ def test_order_payment_flow(data = {'variant': 'dummy','is_active': True,- 'total': order.total.gross.amount,+ 'total': order.total,'charge_status': 'not-charged'}-response = client.post(redirect_url, data)assert response.status_code == 302@@ -469,9 +467,7 @@ def test_order_payment_flow(# Assert that payment object was created and contains correct datapayment = order.payment_methods.all()[0]- assert payment.total == order.total.gross.amount- assert payment.tax == order.total.tax.amount- assert payment.currency == order.total.currency+ assert payment.total == order.total.grossassert payment.transactions.count() == 1assert payment.transactions.first().transaction_type == 'auth'diff --git a/tests/test_payment.py b/tests/test_payment.pydeleted file mode 100644index 43923a9856..0000000000--- a/tests/test_payment.py+++ /dev/null@@ -1,44 +0,0 @@-from decimal import Decimal--from prices import Money--from saleor.order.models import Payment---def test_get_purchased_items(order_with_lines, settings, voucher):- payment = Payment.objects.create(order=order_with_lines, variant='paypal')- discount = Money('10.0', settings.DEFAULT_CURRENCY)-- assert len(payment.get_purchased_items()) == order_with_lines.lines.count()-- for p, o in zip(- payment.get_purchased_items(), order_with_lines.lines.all()):- assert p.sku == o.product_sku- assert p.quantity == o.quantity- assert p.price == o.unit_price_net.quantize(Decimal('0.01')).amount- assert p.currency == o.unit_price.currency-- order_with_lines.discount_name = 'Test'- order_with_lines.discount_amount = discount- order_with_lines.voucher = voucher- order_with_lines.save()-- settings.PAYMENT_VARIANTS = {'paypal': ('PaypalProvider', {})}-- assert len(payment.get_purchased_items()) == (- order_with_lines.lines.count() + 1)-- for p, o in zip(- payment.get_purchased_items()[:-1], order_with_lines.lines.all()):- assert p.sku == o.product_sku- assert p.quantity == o.quantity- assert p.price == o.unit_price_net.quantize(Decimal('0.01')).amount- assert p.currency == o.unit_price.currency-- discounted = payment.get_purchased_items()[-1]-- assert discounted.name == order_with_lines.discount_name- assert discounted.sku == 'DISCOUNT'- assert discounted.price == -1 * order_with_lines.discount_amount.amount- assert discounted.currency == order_with_lines.discount_amount.currency- assert discounted.quantity == 1diff --git a/tests/test_payments.py b/tests/test_payments.pyindex 71aa7646d1..2331d603ae 100644--- a/tests/test_payments.py+++ b/tests/test_payments.py@@ -1,7 +1,8 @@import pytest-from saleor.payment import (- PaymentError, PaymentMethodChargeStatus, TransactionType)+from saleor.payment import ChargeStatus, PaymentError, TransactionType++from .utils import moneydef test_authorize(payment_method_dummy):@@ -25,22 +26,22 @@ def test_authorize_gateway_error(payment_method_dummy, monkeypatch):def test_void_success(payment_method_dummy):assert payment_method_dummy.is_active- assert payment_method_dummy.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+ assert payment_method_dummy.charge_status == ChargeStatus.NOT_CHARGEDtxn = payment_method_dummy.void()assert txn.is_successassert txn.transaction_type == TransactionType.VOIDassert txn.payment_method == payment_method_dummypayment_method_dummy.refresh_from_db()assert not payment_method_dummy.is_active- assert payment_method_dummy.charge_status == PaymentMethodChargeStatus.NOT_CHARGED+ assert payment_method_dummy.charge_status == ChargeStatus.NOT_CHARGED@pytest.mark.parametrize('is_active, charge_status', [- (False, PaymentMethodChargeStatus.NOT_CHARGED),- (False, PaymentMethodChargeStatus.CHARGED),- (True, PaymentMethodChargeStatus.CHARGED),- (True, PaymentMethodChargeStatus.FULLY_REFUNDED), ])+ (False, ChargeStatus.NOT_CHARGED),+ (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_dummypayment_method.is_active = is_active@@ -61,22 +62,22 @@ def test_void_gateway_error(payment_method_dummy, monkeypatch):assert txn.payment_method == payment_method_dummy[email protected]('amount', [100, 90])[email protected]('amount', [80, 70])def test_charge_success(amount, payment_method_dummy):- txn = payment_method_dummy.charge(amount=amount)+ txn = payment_method_dummy.capture(amount=amount)assert txn.is_successassert txn.payment_method == payment_method_dummypayment_method_dummy.refresh_from_db()- assert payment_method_dummy.charge_status == PaymentMethodChargeStatus.CHARGED+ assert payment_method_dummy.charge_status == ChargeStatus.CHARGEDassert payment_method_dummy.is_active@pytest.mark.parametrize('amount, captured_amount, charge_status, is_active', [- (100, 0, PaymentMethodChargeStatus.NOT_CHARGED, False),- (100, 0, PaymentMethodChargeStatus.FULLY_REFUNDED, True),- (100, 100, PaymentMethodChargeStatus.CHARGED, True),- (120, 0, PaymentMethodChargeStatus.NOT_CHARGED, True), ])+ (80, money(0), ChargeStatus.NOT_CHARGED, False),+ (80, money(0), ChargeStatus.FULLY_REFUNDED, True),+ (80, money(80), ChargeStatus.CHARGED, True),+ (120, money(0), ChargeStatus.NOT_CHARGED, True), ])def test_charge_failed(amount, captured_amount, charge_status, is_active,payment_method_dummy):@@ -86,7 +87,7 @@ def test_charge_failed(payment_method.charge_status = charge_statuspayment_method.save()with pytest.raises(PaymentError):- txn = payment_method.charge(amount=amount)+ txn = payment_method.capture(amount=amount)assert txn is None@@ -94,7 +95,7 @@ def test_charge_gateway_error(payment_method_dummy, monkeypatch):monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)with pytest.raises(PaymentError):- txn = payment_method_dummy.charge(100)+ txn = payment_method_dummy.capture(80)assert txn.transaction_type == TransactionType.CHARGEassert not txn.is_successassert txn.payment_method == payment_method_dummy@@ -103,13 +104,13 @@ def test_charge_gateway_error(payment_method_dummy, monkeypatch):@pytest.mark.parametrize('initial_captured_amount, refund_amount, final_captured_amount, final_charge_status, active_after',[- (100, 100, 0, PaymentMethodChargeStatus.FULLY_REFUNDED, False),- (100, 10, 90, PaymentMethodChargeStatus.CHARGED, True), ])+ (money(80), 80, money(0), ChargeStatus.FULLY_REFUNDED, False),+ (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 = PaymentMethodChargeStatus.CHARGED+ payment_method.charge_status = ChargeStatus.CHARGEDpayment_method.captured_amount = initial_captured_amountpayment_method.save()txn = payment_method.refund(refund_amount)@@ -123,9 +124,9 @@ def test_refund_success(@pytest.mark.parametrize('initial_captured_amount, refund_amount, initial_charge_status', [- (100, 0, PaymentMethodChargeStatus.FULLY_REFUNDED),- (0, 10, PaymentMethodChargeStatus.NOT_CHARGED),- (10, 20, PaymentMethodChargeStatus.CHARGED), ])+ (money(80), 0, ChargeStatus.FULLY_REFUNDED),+ (money(0), 10, ChargeStatus.NOT_CHARGED),+ (money(10), 20, ChargeStatus.CHARGED), ])def test_refund_failed(initial_captured_amount, refund_amount, initial_charge_status,payment_method_dummy):@@ -142,14 +143,14 @@ def test_refund_gateway_error(payment_method_dummy, monkeypatch):monkeypatch.setattr('saleor.payment.providers.dummy.dummy_success', lambda: False)payment_method = payment_method_dummy- payment_method.charge_status = PaymentMethodChargeStatus.CHARGED- payment_method.captured_amount = 100+ payment_method.charge_status = ChargeStatus.CHARGED+ payment_method.captured_amount = money(80)payment_method.save()with pytest.raises(PaymentError):- txn = payment_method.refund(100)+ txn = payment_method.refund(80)payment_method.refresh_from_db()assert txn.transaction_type == TransactionType.REFUNDassert not txn.is_successassert txn.payment_method == payment_method- assert payment_method.charge_status == PaymentMethodChargeStatus.CHARGED- assert payment_method.captured_amount == 100+ assert payment_method.charge_status == ChargeStatus.CHARGED+ assert payment_method.captured_amount == money(80)diff --git a/tests/test_shipping.py b/tests/test_shipping.pyindex 36d77cc7e5..37c982cb76 100644--- a/tests/test_shipping.py+++ b/tests/test_shipping.py@@ -8,11 +8,7 @@ from saleor.core.utils import format_moneyfrom saleor.core.utils.taxes import get_taxed_shipping_pricefrom saleor.shipping.models import (ShippingMethod, ShippingMethodType, ShippingZone)---def money(amount):- return Money(amount, 'USD')-+from .utils import money@pytest.mark.parametrize('price, charge_taxes, expected_price', [(Money(10, 'USD'), False, TaxedMoney(diff --git a/tests/utils.py b/tests/utils.pyindex c6161a61fd..857b9ba92d 100644--- a/tests/utils.py+++ b/tests/utils.py@@ -1,4 +1,3 @@-import jsonfrom io import BytesIOfrom urllib.parse import urlparse@@ -6,6 +5,7 @@ from django.core.files.uploadedfile import SimpleUploadedFilefrom django.db.models import Qfrom django.utils.encoding import smart_textfrom PIL import Image+from prices import Moneydef get_url_path(url):@@ -55,3 +55,7 @@ def create_pdf_file_with_image_ext():file_data = SimpleUploadedFile(file_name, b'product_data', 'application/pdf')return file_data, file_name+++def money(amount):+ return Money(amount, 'USD')