Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Split logic responsible for managing payments into separate views and forms
Marcin Gębala413fa429f8f5
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex fb682e53b5..f4e269766e 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -29,16 +29,41 @@ class ManagePaymentForm(forms.Form):self.payment = kwargs.pop('payment')super(ManagePaymentForm, self).__init__(*args, **kwargs)- def handle_action(self, action, user):++class CapturePaymentForm(ManagePaymentForm):+ def clean(self):+ if self.payment.status != 'preauth':+ raise forms.ValidationError(+ _('Only preauthorized payments can be captured'))++ def capture(self):amount = self.cleaned_data['amount']- if action == 'capture' and self.payment.status == 'preauth':- self.payment.capture(amount.gross)- elif action == 'refund' and self.payment.status == 'confirmed':- self.payment.refund(amount.gross)- elif action == 'release' and self.payment.status == 'preauth':- self.payment.release()- else:- raise ValueError(_('Invalid payment action'))+ self.payment.capture(amount.gross)+++class RefundPaymentForm(ManagePaymentForm):+ def clean(self):+ if self.payment.status != 'confirmed':+ raise forms.ValidationError(+ _('Only confirmed payments can be refunded'))++ def refund(self):+ amount = self.cleaned_data['amount']+ self.payment.refund(amount.gross)+++class ReleasePaymentForm(forms.Form):+ def __init__(self, *args, **kwargs):+ self.payment = kwargs.pop('payment')+ super(ReleasePaymentForm, self).__init__(*args, **kwargs)++ def clean(self):+ if self.payment.status != 'preauth':+ raise forms.ValidationError(+ _('Only preauthorized payments can be released'))++ def release(self):+ self.payment.release()class MoveItemsForm(forms.Form):diff --git a/saleor/dashboard/order/urls.py b/saleor/dashboard/order/urls.pyindex 1a9ea9e50e..5b8187863a 100644--- a/saleor/dashboard/order/urls.py+++ b/saleor/dashboard/order/urls.py@@ -11,8 +11,14 @@ urlpatterns = [views.order_add_note, name='order-add-note'),url(r'^(?P<order_pk>\d+)/address/(?P<address_type>billing|shipping)/$',views.address_view, name='address-edit'),- url(r'^(?P<order_pk>\d+)/payment/(?P<payment_pk>\d+)/(?P<action>capture|refund|release)/$',- views.manage_payment, name='manage-payment'),++ url(r'^(?P<order_pk>\d+)/payment/(?P<payment_pk>\d+)/capture/$',+ views.capture_payment, name='capture-payment'),+ url(r'^(?P<order_pk>\d+)/payment/(?P<payment_pk>\d+)/release/$',+ views.release_payment, name='release-payment'),+ url(r'^(?P<order_pk>\d+)/payment/(?P<payment_pk>\d+)/refund/$',+ views.refund_payment, name='refund-payment'),+url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/change/$', views.orderline_change_quantity,name='orderline-change-quantity'),url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/split/$', views.orderline_split,diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 4f74b1cebd..ea3410bb59 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -3,7 +3,6 @@ from __future__ import unicode_literalsfrom django.contrib import messagesfrom django.core.context_processors import csrffrom django.db import transaction-from django.http import Http404from django.shortcuts import get_object_or_404, redirectfrom django.template.response import TemplateResponsefrom django.utils.translation import ugettext_lazy as _@@ -16,8 +15,9 @@ from ...order.models import Order, OrderedItem, OrderNotefrom ...userprofile.forms import AddressFormfrom ..views import (StaffMemberOnlyMixin, FilterByStatusMixin,staff_member_required)-from .forms import (OrderNoteForm, ManagePaymentForm, MoveItemsForm,- ChangeQuantityForm, ShipGroupForm)+from .forms import (OrderNoteForm, MoveItemsForm,+ ChangeQuantityForm, ShipGroupForm, CapturePaymentForm,+ ReleasePaymentForm, RefundPaymentForm)class OrderListView(StaffMemberOnlyMixin, FilterByStatusMixin, ListView):@@ -77,54 +77,78 @@ def order_add_note(request, order_pk):@staff_member_required-def manage_payment(request, order_pk, payment_pk, action):+def capture_payment(request, order_pk, payment_pk):order = get_object_or_404(Order, pk=order_pk)- payment = get_object_or_404(order.payments.all(), pk=payment_pk)- if action == 'release':- amount = 0- template = 'dashboard/order/modal_release.html'- elif action == 'refund':- amount = payment.captured_amount- template = 'dashboard/order/modal_capture_refund.html'- elif action == 'capture':- amount = payment.order.get_total().quantize('0.01').gross- template = 'dashboard/order/modal_capture_refund.html'- else:- raise Http404()- initial = {'amount': amount, 'action': action}- form = ManagePaymentForm(request.POST or None, payment=payment,- initial=initial)+ payment = get_object_or_404(order.payments, pk=payment_pk)+ amount = order.get_total().quantize('0.01').gross+ form = CapturePaymentForm(request.POST or None, payment=payment,+ initial={'amount': amount})status = 200if form.is_valid():try:- form.handle_action(action, request.user)+ form.capture()except (PaymentError, ValueError) as e:messages.error(request, _('Payment gateway error: %s') % e.message)else:amount = form.cleaned_data['amount']- comment = None- currency = payment.currency- if action == 'capture':- comment = _('Captured %(amount)s') % {- 'amount': gross(amount)}- payment.order.create_history_entry(comment=comment,- user=request.user)- elif action == 'refund':- comment = _('Refunded %(amount)s') % {- 'amount': gross(amount)}- payment.order.create_history_entry(comment=comment,- user=request.user)- elif action == 'release':- comment = _('Released payment')- payment.order.create_history_entry(comment=comment,- user=request.user)- messages.success(request, comment)+ msg = _('Captured %(amount)s') % {'amount': gross(amount)}+ payment.order.create_history_entry(comment=msg, user=request.user)+ messages.success(request, msg)elif form.errors:status = 400- ctx = {'form': form, 'action': action, 'currency': payment.currency,- 'captured': payment.captured_amount, 'order': order,- 'payment': payment}- return TemplateResponse(request, template, ctx, status=status)+ ctx = {'captured': payment.captured_amount, 'currency': payment.currency,+ 'form': form, 'order': order, 'payment': payment}+ return TemplateResponse(request, 'dashboard/order/modal_capture.html', ctx,+ status=status)+++@staff_member_required+def refund_payment(request, order_pk, payment_pk):+ order = get_object_or_404(Order, pk=order_pk)+ payment = get_object_or_404(order.payments, pk=payment_pk)+ amount = payment.captured_amount+ form = RefundPaymentForm(request.POST or None, payment=payment,+ initial={'amount': amount})+ status = 200+ if form.is_valid():+ try:+ form.refund()+ except (PaymentError, ValueError) as e:+ messages.error(request, _('Payment gateway error: %s') % e.message)+ else:+ amount = form.cleaned_data['amount']+ msg = _('Refunded %(amount)s') % {'amount': gross(amount)}+ payment.order.create_history_entry(comment=msg, user=request.user)+ messages.success(request, msg)+ elif form.errors:+ status = 400+ ctx = {'captured': payment.captured_amount, 'currency': payment.currency,+ 'form': form, 'order': order, 'payment': payment}+ return TemplateResponse(request, 'dashboard/order/modal_refund.html', ctx,+ status=status)+++@staff_member_required+def release_payment(request, order_pk, payment_pk):+ order = get_object_or_404(Order, pk=order_pk)+ payment = get_object_or_404(order.payments, pk=payment_pk)+ form = ReleasePaymentForm(request.POST or None, payment=payment)+ status = 200+ if form.is_valid():+ try:+ form.release()+ except (PaymentError, ValueError) as e:+ messages.error(request, _('Payment gateway error: %s') % e.message)+ else:+ msg = _('Released payment')+ payment.order.create_history_entry(comment=msg, user=request.user)+ messages.success(request, msg)+ elif form.errors:+ status = 400+ ctx = {'captured': payment.captured_amount, 'currency': payment.currency,+ 'form': form, 'order': order, 'payment': payment}+ return TemplateResponse(request, 'dashboard/order/modal_release.html', ctx,+ status=status)@staff_member_requireddiff --git a/saleor/dashboard/templates/dashboard/order/detail.html b/saleor/dashboard/templates/dashboard/order/detail.htmlindex 435f5ba739..5610a303fe 100644--- a/saleor/dashboard/templates/dashboard/order/detail.html+++ b/saleor/dashboard/templates/dashboard/order/detail.html@@ -220,14 +220,14 @@{% if can_capture or can_refund or can_release %}<div class="card-action">{% if can_capture %}- <a href="#base-modal" data-href="{% url 'dashboard:manage-payment' order_pk=order.pk payment_pk=payment.pk action='capture' %}"+ <a href="#base-modal" data-href="{% url 'dashboard:capture-payment' order_pk=order.pk payment_pk=payment.pk %}"class="modal-trigger-custom">{% trans "Capture" %}</a>{% elif can_refund %}- <a href="#base-modal" data-href="{% url 'dashboard:manage-payment' order_pk=order.pk payment_pk=payment.pk action='refund' %}"+ <a href="#base-modal" data-href="{% url 'dashboard:refund-payment' order_pk=order.pk payment_pk=payment.pk %}"class="modal-trigger-custom">{% trans "Refund" %}</a>{% endif %}{% if can_release %}- <a href="#base-modal" data-href="{% url 'dashboard:manage-payment' order_pk=order.pk payment_pk=payment.pk action='release' %}"+ <a href="#base-modal" data-href="{% url 'dashboard:release-payment' order_pk=order.pk payment_pk=payment.pk %}"class="modal-trigger-custom">{% trans "Release" %}</a>{% endif %}</div>diff --git a/saleor/dashboard/templates/dashboard/order/modal_capture_refund.html b/saleor/dashboard/templates/dashboard/order/modal_capture.htmlsimilarity index 75%rename from saleor/dashboard/templates/dashboard/order/modal_capture_refund.htmlrename to saleor/dashboard/templates/dashboard/order/modal_capture.htmlindex da7eb4c71d..b1cc03e3d8 100644--- a/saleor/dashboard/templates/dashboard/order/modal_capture_refund.html+++ b/saleor/dashboard/templates/dashboard/order/modal_capture.html@@ -4,11 +4,11 @@{% load materializecss %}{% load prices_i18n %}-<form role="form" method="post" action="{% url 'dashboard:manage-payment' order_pk=order.pk payment_pk=payment.pk action=action %}" class="form-async">+<form role="form" method="post" action="{% url 'dashboard:capture-payment' order_pk=order.pk payment_pk=payment.pk %}" class="form-async">{% csrf_token %}<div class="modal-content">- <h5>{{ action|capfirst }} {% trans "payment" %}</h5>+ <h5>{% trans "Capture payment" %}</h5><div class="row">{{ form.amount|materializecss }}@@ -23,7 +23,7 @@</div><div class="modal-footer">- <button type="submit" class="modal-action btn-flat blue-text">{{ action|capfirst }}</button>+ <button type="submit" class="modal-action btn-flat blue-text">{% trans 'Capture' %}</button><a href="#!" aria-hidden="true" class="modal-action modal-close btn-flat blue-text">{% trans "Cancel" %}</a></div></form>diff --git a/saleor/dashboard/templates/dashboard/order/modal_refund.html b/saleor/dashboard/templates/dashboard/order/modal_refund.htmlnew file mode 100644index 0000000000..aea4672e05--- /dev/null+++ b/saleor/dashboard/templates/dashboard/order/modal_refund.html@@ -0,0 +1,29 @@+{% load i18n %}+{% load babel %}+{% load bootstrap %}+{% load materializecss %}+{% load prices_i18n %}++<form role="form" method="post" action="{% url 'dashboard:refund-payment' order_pk=order.pk payment_pk=payment.pk %}" class="form-async">+ {% csrf_token %}++ <div class="modal-content">+ <h5>{% trans "Refund payment" %}</h5>++ <div class="row">+ {{ form.amount|materializecss }}+ </div>++ <h5>{% trans "Before this action" %}</h5>++ <ul class="list">+ <li class="list-item">{% trans "Order total: " %}{% gross payment.order.get_total %}</li>+ <li class="list-item">{% trans "Captured amount: " %}{{ captured|currencyfmt:currency }} </li>+ </ul>+ </div>++ <div class="modal-footer">+ <button type="submit" class="modal-action btn-flat blue-text">{% trans 'Refund' %}</button>+ <a href="#!" aria-hidden="true" class="modal-action modal-close btn-flat blue-text">{% trans "Cancel" %}</a>+ </div>+</form>diff --git a/saleor/dashboard/templates/dashboard/order/modal_release.html b/saleor/dashboard/templates/dashboard/order/modal_release.htmlindex 684d27eefd..e966447911 100644--- a/saleor/dashboard/templates/dashboard/order/modal_release.html+++ b/saleor/dashboard/templates/dashboard/order/modal_release.html@@ -9,7 +9,7 @@<div class="modal-footer"><form id="release-form" method="post" role="form" class="form-async"- action="{% url 'dashboard:manage-payment' order_pk=order.pk payment_pk=payment.pk action=action %}">+ action="{% url 'dashboard:release-payment' order_pk=order.pk payment_pk=payment.pk %}">{% csrf_token %}<input type="hidden" name="{{ form.amount.name }}" value="0">