Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add order line actions (changing quantity, moving items to other delivery groups)

Marcin Gębala001cb0ef7977
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 30b32e5049..ea8d49cf67 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -1,10 +1,9 @@
from django import forms
from django.utils.translation import ugettext_lazy as _
-from django.forms.formsets import BaseFormSet, DEFAULT_MAX_NUM
from satchless.item import InsufficientStock
from ...cart.forms import QuantityField
-from ...order.models import OrderNote
+from ...order.models import OrderNote, DeliveryGroup
from ...product.models import Product
@@ -26,13 +25,48 @@ class ManagePaymentForm(forms.Form):
amount = forms.DecimalField(min_value=0, decimal_places=2)
-class OrderLineForm(forms.Form):
+class MoveItemsForm(forms.Form):
quantity = QuantityField()
+ groups = forms.ChoiceField()
def __init__(self, *args, **kwargs):
self.item = kwargs.pop('item')
- super(OrderLineForm, self).__init__(*args, **kwargs)
+ super(MoveItemsForm, self).__init__(*args, **kwargs)
self.fields['quantity'].widget.attrs['max'] = self.item.quantity
+ self.fields['groups'].choices = self.get_delivery_group_choices()
+
+ def get_delivery_group_choices(self):
+ group = self.item.delivery_group
+ groups = group.order.groups.exclude(pk=group.pk)
+ choices = [('new', _('New'))]
+ choices.extend([(g.pk, 'Delivery group #%s' % g.pk) for g in groups])
+ return choices
+
+ def save(self, user=None):
+ quantity = self.cleaned_data['quantity']
+ choice = self.cleaned_data['groups']
+ if choice == 'new':
+ group = DeliveryGroup.objects.select_subclasses().get(
+ pk=self.item.delivery_group.pk)
+ new_group = group
+ new_group.pk = None
+ new_group.id = None
+ new_group.status = 'new'
+ new_group.save()
+ self.item.move_to_group(new_group, quantity, user)
+ else:
+ group = DeliveryGroup.objects.get(pk=choice)
+ self.item.move_to_group(group, quantity, user)
+
+
+class ChangeQuantityForm(forms.Form):
+ quantity = QuantityField()
+
+ def __init__(self, *args, **kwargs):
+ self.item = kwargs.pop('item')
+ super(ChangeQuantityForm, self).__init__(*args, **kwargs)
+ self.fields['quantity'].widget.attrs['max'] = self.item.quantity
+ self.fields['quantity'].initial = self.item.quantity
def get_variant(self):
p = Product.objects.select_subclasses().get(pk=self.item.product.pk)
@@ -52,30 +86,3 @@ class OrderLineForm(forms.Form):
new_quantity = self.cleaned_data['quantity']
if new_quantity != self.item.quantity:
self.item.change_quantity(new_quantity, user)
-
-
-class OrderContentFormset(BaseFormSet):
- absolute_max = 9999
- can_delete = False
- can_order = False
- extra = 0
- form = OrderLineForm
- max_num = DEFAULT_MAX_NUM
- validate_max = False
- min_num = None
- validate_min = False
-
- def __init__(self, *args, **kwargs):
- self.order = kwargs.pop('order')
- kwargs['initial'] = [{'quantity': item.quantity}
- for item in self.order.get_items()]
- super(OrderContentFormset, self).__init__(*args, **kwargs)
-
- def _construct_form(self, i, **kwargs):
- kwargs['item'] = self.order.get_items()[i]
- return super(OrderContentFormset, self)._construct_form(i, **kwargs)
-
- def save(self, user=None):
- for form in self.forms:
- if form.is_valid():
- form.save(user)
diff --git a/saleor/dashboard/order/urls.py b/saleor/dashboard/order/urls.py
index 6bbab2e9b3..1f70448e64 100644
--- a/saleor/dashboard/order/urls.py
+++ b/saleor/dashboard/order/urls.py
@@ -10,5 +10,8 @@ urlpatterns = patterns(
name='order-details'),
url(r'^(?P<order_pk>[0-9]+)/address/(?P<address_type>billing|shipping)$',
views.AddressView.as_view(),
- name='address-edit')
+ name='address-edit'),
+ url(r'^line/(?P<pk>[0-9]+)$',
+ views.OrderLineEdit.as_view(),
+ name='order-line-edit')
)
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index 73d96e9608..6028780e77 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -8,10 +8,11 @@ from django.http import HttpResponse
from django.core.context_processors import csrf
from payments import PaymentError
-from ...order.models import Order, Address
+from ...order.models import Order, OrderedItem, Address
from ...userprofile.forms import AddressForm
from ..views import StaffMemberOnlyMixin, FilterByStatusMixin
-from .forms import OrderNoteForm, ManagePaymentForm, OrderContentFormset
+from .forms import (OrderNoteForm, ManagePaymentForm, MoveItemsForm,
+ ChangeQuantityForm)
class OrderListView(StaffMemberOnlyMixin, FilterByStatusMixin, ListView):
@@ -29,7 +30,6 @@ class OrderDetails(StaffMemberOnlyMixin, DetailView):
context_object_name = 'order'
payment_form_class = ManagePaymentForm
note_form_class = OrderNoteForm
- order_formset_class = OrderContentFormset
def get_queryset(self):
qs = super(OrderDetails, self).get_queryset()
@@ -65,17 +65,9 @@ class OrderDetails(StaffMemberOnlyMixin, DetailView):
ctx['can_capture'] = ctx['can_release'] = ctx['can_refund'] = False
ctx['payment_form'] = self.payment_form_class()
- ctx['order_formset'] = self.order_formset_class(
- order=self.object)
-
+ ctx['delivery_groups'] = self.object.groups.select_subclasses().all()
return ctx
- def get_delivery_info(self):
- try:
- return self.object.groups.select_subclasses().get()
- except self.model.DoesNotExist:
- return None
-
def get(self, request, *args, **kwargs):
self.object = self.get_object()
ctx = self.get_context_data()
@@ -104,11 +96,8 @@ class OrderDetails(StaffMemberOnlyMixin, DetailView):
elif 'note_form' in request.POST:
form = self.note_form_class(request.POST)
self.handle_note_form(form)
- elif 'order_formset' in request.POST:
- formset = self.order_formset_class(
- request.POST or None,
- order=self.get_object())
- self.handle_order_formset(formset)
+ elif 'line_action' in request.POST:
+ self.handle_line_action()
return self.get(request, *args, **kwargs)
def handle_release_action(self):
@@ -162,13 +151,18 @@ class OrderDetails(StaffMemberOnlyMixin, DetailView):
else:
messages.error(self.request, _('Form has errors'))
- def handle_order_formset(self, formset):
- if formset.is_valid():
- if formset.has_changed():
- formset.save(user=self.request.user)
- messages.success(self.request, _('Quantities updated'))
+ def handle_line_action(self):
+ action = self.request.POST['line_action']
+ item = OrderedItem.objects.get(pk=self.request.POST['item_pk'])
+ if action == 'move_items':
+ form = MoveItemsForm(self.request.POST, item=item)
+ elif action == 'change_quantity':
+ form = ChangeQuantityForm(self.request.POST, item=item)
+ if form.is_valid():
+ form.save(user=self.request.user)
+ messages.success(self.request, _('Order line updated'))
else:
- messages.error(self.request, _('Problem with updating quantities'))
+ messages.error(self.request, _('Cannot update order line'))
class AddressView(StaffMemberOnlyMixin, UpdateView):
@@ -198,3 +192,26 @@ class AddressView(StaffMemberOnlyMixin, UpdateView):
_('%(address_type)s address updated' % {'address_type': _type_str})
)
return reverse('dashboard:order-details', kwargs={'pk': self.order.pk})
+
+
+class OrderLineEdit(StaffMemberOnlyMixin, UpdateView):
+ model = OrderedItem
+ quantity_form = ChangeQuantityForm
+ move_items_form = MoveItemsForm
+
+ def get_context_data(self, **kwargs):
+ ctx = super(OrderLineEdit, self).get_context_data(**kwargs)
+ ctx['quantity_form'] = self.quantity_form(item=self.get_object())
+ ctx['move_items_form'] = self.move_items_form(item=self.get_object())
+ return ctx
+
+ def get(self, request, *args, **kwargs):
+ self.object = self.get_object()
+ ctx = self.get_context_data(*args, **kwargs)
+ ctx.update(csrf(request))
+ if request.is_ajax():
+ template = 'dashboard/includes/modal_order_line_edit.html'
+ rendered = render_to_string(template, ctx)
+ return HttpResponse(rendered)
+ else:
+ return self.render_to_response(ctx)
diff --git a/saleor/dashboard/templates/dashboard/includes/modal_order_line_edit.html b/saleor/dashboard/templates/dashboard/includes/modal_order_line_edit.html
new file mode 100644
index 0000000000..41d7dc6a0b
--- /dev/null
+++ b/saleor/dashboard/templates/dashboard/includes/modal_order_line_edit.html
@@ -0,0 +1,32 @@
+{% load i18n %}
+{% load bootstrap %}
+
+ {% csrf_token %}
+ <div class="modal-header">
+ <a href="#" data-dismiss="modal" aria-hidden="true" class="close">×</a>
+ <h3>{% trans "Edit order line " %}{{ object.product }} ({{ object }})</h3>
+ </div>
+ <div class="modal-body">
+ <form class="form-inline" method="post" role="form">
+ {% csrf_token %}
+ <div class="form-group">
+ <p>{% trans "Change quantity: " %}
+ {% render_widget quantity_form.quantity class="form-control input-sm" %}
+ <input type="hidden" name="line_action" value="change_quantity" />
+ <input type="hidden" name="item_pk" value={{ object.pk }} />
+ <button type="submit" class="btn btn-default btn-sm">OK</button></p>
+ </div>
+ </form>
+ <form class="form-inline" method="post" role="form">
+ {% csrf_token %}
+ <div class="form-group">
+ <p>Move {% render_widget move_items_form.quantity class="form-control input-sm" %} items to delivery group: {% render_widget move_items_form.groups class="form-control input-sm" %}
+ <input type="hidden" name="line_action" value="move_items" />
+ <input type="hidden" name="item_pk" value={{ object.pk }} />
+ <button type="submit" class="btn btn-default btn-sm">OK</button></p>
+ </div>
+ </form>
+ </div>
+ <div class="modal-footer">
+ <button data-dismiss="modal" aria-hidden="true" class="btn btn-default">{% trans "Cancel" %}</button>
+ </div>
\ No newline at end of file
diff --git a/saleor/dashboard/templates/dashboard/order/detail.html b/saleor/dashboard/templates/dashboard/order/detail.html
index 458cb68398..e7285a746b 100644
--- a/saleor/dashboard/templates/dashboard/order/detail.html
+++ b/saleor/dashboard/templates/dashboard/order/detail.html
@@ -14,51 +14,48 @@
<span class="panel-title">Order contents</span>
</div>
<div class="panel-body">
- <form method="post" action="">
- {{ order_formset.management_form }}
- <table class="table">
+ {% for group in delivery_groups %}
+ {% csrf_token %}
+ <table class="table table-condensed">
<thead>
<tr>
- <th class="col-sm-3">{% trans "Name" %}</th>
- <th class="col-sm-3">{% trans "Variant" %}</th>
- <th class="col-sm-3">{% trans "SKU" %}</th>
- <th class="col-sm-3">{% trans "Price" %}</th>
- <th class="col-sm-3">{% trans "Quantity" %}</th>
+ <th class="col-sm-1">Delivery group #{{ group.pk }}</th>
+ <th>{% include 'dashboard/includes/_status_label.html' with status=group.status status_display=group.status %}</th>
+ </tr>
+ <tr>
+ <th class="col-sm-2">{% trans "Name" %}</th>
+ <th class="col-sm-2">{% trans "Variant" %}</th>
+ <th class="col-sm-2">{% trans "SKU" %}</th>
+ <th class="col-sm-2">{% trans "Price" %}</th>
+ <th class="col-sm-2">{% trans "Quantity" %}</th>
+ <th class="col-sm-2">{% trans "Actions" %}</th>
</tr>
</thead>
<tbody>
- {% for form in order_formset %}
+ {% for item in group.items.all %}
<tr>
- <td class="col-sm-3"><a href="{% url "dashboard:product-update" pk=form.item.product_id %}">{{ form.item.product }}</a></td>
- <td>{{ form.item.product_name }}</td>
- <td>{{ form.item.product_sku }}</td>
- <td>{% gross form.item.get_price_per_item %}</td>
- <td>{{ form.quantity }}</td>
+ <td><a href="{% url "dashboard:product-update" pk=item.product_id %}">{{ item.product }}</a></td>
+ <td>{{ item.product_name }}</td>
+ <td>{{ item.product_sku }}</td>
+ <td>{% gross item.get_price_per_item %}</td>
+ <td>{{ item.quantity }}</td>
+ <td><a class="btn btn-link" data-target="#base-modal" href="{% url 'dashboard:order-line-edit' pk=item.pk %}" data-toggle="modal">Edit</a></td>
</tr>
{% endfor %}
</tbody>
- <tr>
- <td colspan="4"></td>
- <td>
- <button class="btn btn-default" type="submit" name="order_formset">
- {% csrf_token %}
- {% trans "Update quantities" %}
- </button>
- </td>
- </tr>
- <tr>
- <td colspan="5"><strong>{% trans "Order totals" %}</strong></td>
- </tr>
- <tr>
- <td colspan="4">{% trans "Delivery" %}</td>
- <td>{% gross order.get_delivery_total %}</td>
- </tr>
- <tr>
- <td colspan="4">{% trans "Total" %}</td>
- <td>{% gross order.get_total %}</td>
- </tr>
+ <tfoot>
+ <tr>
+ <td colspan=5>
+ <p>{% trans "Total: " %}{% gross group.get_total %}</p>
+ <p>{% trans "Delivery cost: " %}{% gross group.price %}</p>
+ </td>
+ <td>
+ <a class="btn btn-default btn-sm">Ship</a>
+ </td>
+ </tr>
+ </tfoot>
</table>
- </form>
+ {% endfor %}
</div>
</div>
<div class="panel panel-default">
@@ -68,12 +65,12 @@
<p>{% trans "Total amount:" %} {{ payment.total }} {{ payment.currency }}</p>
<p>{% trans "Captured amount:" %} {{ payment.captured_amount }} {{ payment.currency }}</p>
{% if can_capture %}
- <a class="btn btn-success" data-target="#payment-action-modal" href="{% url 'dashboard:order-details' pk=order.pk %}?action=capture" data-toggle="modal">{% trans "Capture" %}</a>
+ <a class="btn btn-success" data-target="#base-modal" href="{% url 'dashboard:order-details' pk=order.pk %}?action=capture" data-toggle="modal">{% trans "Capture" %}</a>
{% elif can_refund %}
- <a class="btn btn-danger" data-target="#payment-action-modal" href="{% url 'dashboard:order-details' pk=order.pk %}?action=refund" data-toggle="modal">{% trans "Refund" %}</a>
+ <a class="btn btn-danger" data-target="#base-modal" href="{% url 'dashboard:order-details' pk=order.pk %}?action=refund" data-toggle="modal">{% trans "Refund" %}</a>
{% endif %}
{% if can_release %}
- <a class="btn btn-danger" data-target="#payment-action-modal" href="{% url 'dashboard:order-details' pk=order.pk %}?action=release" data-toggle="modal">{% trans "Release" %}</a>
+ <a class="btn btn-danger" data-target="#base-modal" href="{% url 'dashboard:order-details' pk=order.pk %}?action=release" data-toggle="modal">{% trans "Release" %}</a>
{% endif %}
{% else %}
<span>{% trans "No payment for this order" %}</span>
@@ -211,24 +208,24 @@
{% endwith %}
</div>
<div class="panel panel-default">
- {% with view.get_delivery_info as delivery %}
+ {% for delivery in delivery_groups %}
<div class="panel-heading">
- <span class="panel-title">Shipping address</span>
+ <span class="panel-title">Shipping address - Delivery group #{{ delivery.pk }}</span>
<span class="pull-right"><a href="{% url "dashboard:address-edit" order_pk=order.pk address_type='shipping' %}"><i class="glyphicon glyphicon-cog"></i> Edit</a></span>
</div>
<div class="panel-body">
- {% if delivery %}
+ {% if delivery and delivery.address %}
{% include 'dashboard/includes/_address.html' with address=delivery.address only %}
{% else %}
<span>No shipping address</span>
{% endif %}
</div>
- {% endwith %}
+ {% endfor %}
</div>
</div>
</div>
-<div id="payment-action-modal" class="modal">
+<div id="base-modal" class="modal">
<div class="modal-dialog">
<div class="modal-content"></div>
</div>
@@ -239,7 +236,7 @@
{% block custom_js %}
{{ block.super }}
<script>
- $('#payment-action-modal').on('hide.bs.modal', function(e) {
+ $('#base-modal').on('hide.bs.modal', function(e) {
$(this).removeData();
});
</script>
diff --git a/saleor/order/models.py b/saleor/order/models.py
index bf50ede976..cd01860d26 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -5,6 +5,7 @@ from uuid import uuid4
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.validators import MinValueValidator, MaxValueValidator
+from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils.encoding import smart_text
from django.utils.timezone import now
@@ -250,10 +251,41 @@ class OrderedItem(models.Model, ItemLine):
'old_quantity': old_quantity,
'product': self.product})
order.history.create(status=order.status, comment=comment, user=user)
-
if not any([item.quantity for item in order.get_items()]):
order.change_status('cancelled')
+ def move_to_group(self, group, quantity, user=None):
+ try:
+ item = group.items.get(product=self.product,
+ product_name=self.product_name,
+ product_sku=self.product_sku)
+ except ObjectDoesNotExist:
+ new_item = OrderedItem(delivery_group=group,
+ product=self.product,
+ product_name=self.product_name,
+ product_sku=self.product_sku,
+ quantity=quantity,
+ unit_price_net=self.unit_price_net,
+ unit_price_gross=self.unit_price_gross)
+ new_item.save()
+ else:
+ item.quantity += quantity
+ item.save()
+
+ self.quantity -= quantity
+ self.save()
+
+ comment = pgettext_lazy(
+ 'Order history',
+ 'Moved %(quantity)s items %(item)s from group #%(old_group)s \
+ to group #%(new_group)s' % {'quantity': quantity,
+ 'item': self,
+ 'old_group': self.delivery_group.pk,
+ 'new_group': group.pk})
+
+ order = self.delivery_group.order
+ order.history.create(status=order.status, comment=comment, user=user)
+
class Payment(BasePayment):