Skip to content

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

Cancel fulfillment functionality

Anna Siwike2fc6f989f3c
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index c24092e9bc..6104e53767 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -11,12 +11,13 @@ from ...account.i18n import (
from ...cart.forms import QuantityField
from ...core.exceptions import InsufficientStock
from ...discount.utils import decrease_voucher_usage
-from ...order import OrderStatus
+from ...order import FulfillmentStatus, OrderStatus
from ...order.emails import send_note_confirmation
from ...order.models import Fulfillment, FulfillmentLine, OrderLine, OrderNote
from ...order.utils import (
add_variant_to_order, change_order_line_quantity,
- merge_duplicates_into_order_line, recalculate_order, restock_order_lines)
+ merge_duplicates_into_order_line, recalculate_order,
+ restock_fulfillment_lines, restock_order_lines)
from ...product.models import Product, ProductVariant, Stock
from ...product.utils import allocate_stock, deallocate_stock
from ..forms import AjaxSelect2ChoiceField
@@ -201,6 +202,38 @@ class CancelOrderForm(forms.Form):
self.order.save(update_fields=['status'])
+class CancelFulfillmentForm(forms.Form):
+ """Allow canceling an entire fulfillment.
+
+ Increase corresponding stocks for each fulfillment line.
+ """
+ restock = forms.BooleanField(initial=True, required=False)
+
+ def __init__(self, *args, **kwargs):
+ self.fulfillment = kwargs.pop('fulfillment')
+ super().__init__(*args, **kwargs)
+ self.fields['restock'].label = npgettext_lazy(
+ 'Cancel fulfillment form action',
+ 'Restock %(quantity)d item',
+ 'Restock %(quantity)d items',
+ 'quantity') % {'quantity': self.fulfillment.get_total_quantity()}
+
+ def clean(self):
+ data = super().clean()
+ if not self.fulfillment.can_cancel():
+ raise forms.ValidationError(
+ pgettext_lazy(
+ 'Cancel fulfillment form error',
+ 'This fulfillment can\'t be canceled'))
+ return data
+
+ def cancel_fulfillment(self):
+ if self.cleaned_data.get('restock'):
+ restock_fulfillment_lines(self.fulfillment)
+ self.fulfillment.status = FulfillmentStatus.CANCELED
+ self.fulfillment.save(update_fields=['status'])
+
+
class RemoveVoucherForm(forms.Form):
def __init__(self, *args, **kwargs):
diff --git a/saleor/dashboard/order/urls.py b/saleor/dashboard/order/urls.py
index 36a7d1f703..9228d49efa 100644
--- a/saleor/dashboard/order/urls.py
+++ b/saleor/dashboard/order/urls.py
@@ -32,6 +32,8 @@ urlpatterns = [
views.add_variant_to_order, name='add-variant-to-order'),
url(r'^(?P<order_pk>\d+)/fulfill/$',
views.fulfill_order_lines, name='fulfill-order-lines'),
+ url(r'^(?P<order_pk>\d+)/fulfillment/(?P<fulfillment_pk>\d+)/cancel/$',
+ views.cancel_fulfillment, name='fulfillment-cancel'),
url(r'^(?P<order_pk>\d+)/invoice/$',
views.order_invoice, name='order-invoice'),
url(r'^(?P<order_pk>\d+)/packing-slips/$',
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index 58b01437cf..34e5ac078e 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -22,9 +22,10 @@ from ..views import staff_member_required
from .filters import OrderFilter
from .forms import (
AddressForm, AddVariantToOrderForm, BaseFulfillmentLineFormSet,
- CancelOrderForm, CancelOrderLineForm, CapturePaymentForm,
- ChangeQuantityForm, ChangeStockForm, FulfillmentForm, FulfillmentLineForm,
- OrderNoteForm, RefundPaymentForm, ReleasePaymentForm, RemoveVoucherForm)
+ CancelOrderForm, CancelFulfillmentForm, CancelOrderLineForm,
+ CapturePaymentForm, ChangeQuantityForm, ChangeStockForm, FulfillmentForm,
+ FulfillmentLineForm, OrderNoteForm, RefundPaymentForm, ReleasePaymentForm,
+ RemoveVoucherForm)
from .utils import (
create_invoice_pdf, create_packing_slip_pdf, get_statics_absolute_url)
@@ -429,3 +430,36 @@ def fulfill_order_lines(request, order_pk):
ctx = {'form': form, 'formset': formset, 'order': order}
template = 'dashboard/order/fulfillment.html'
return TemplateResponse(request, template, ctx, status=status)
+
+
+@staff_member_required
+@permission_required('order.edit_order')
+def cancel_fulfillment(request, order_pk, fulfillment_pk):
+ status = 200
+ order = get_object_or_404(Order, pk=order_pk)
+ fulfillment = get_object_or_404(
+ order.fulfillments.all(), pk=fulfillment_pk)
+ form = CancelFulfillmentForm(request.POST or None, fulfillment=fulfillment)
+ if form.is_valid():
+ msg = pgettext_lazy(
+ 'Dashboard message', 'Fulfillment #%(fulfillment)s canceled') % {
+ 'fulfillment': fulfillment.composed_id}
+ with transaction.atomic():
+ form.cancel_fulfillment()
+ if form.cleaned_data.get('restock'):
+ restock_msg = npgettext_lazy(
+ 'Dashboard message',
+ 'Restocked %(quantity)d item',
+ 'Restocked %(quantity)d items',
+ 'quantity') % {
+ 'quantity': fulfillment.get_total_quantity()}
+ order.history.create(content=restock_msg, user=request.user)
+ order.history.create(content=msg, user=request.user)
+ messages.success(request, msg)
+ return redirect('dashboard:order-details', order_pk=order.pk)
+ elif form.errors:
+ status = 400
+ ctx = {'form': form, 'order': order, 'fulfillment': fulfillment}
+ return TemplateResponse(
+ request, 'dashboard/order/modal/cancel_fulfillment.html', ctx,
+ status=status)
diff --git a/saleor/order/models.py b/saleor/order/models.py
index ab19ffd80b..bcb8e46af5 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -213,6 +213,9 @@ class Fulfillment(models.Model):
return pgettext_lazy(
'Fulfillment str', 'Fulfillment #%s') % (self.composed_id,)
+ def __iter__(self):
+ return iter(self.lines.all())
+
def save(self, *args, **kwargs):
""""Assign an auto incremented value as a fulfillment order."""
if not self.pk:
@@ -227,6 +230,12 @@ class Fulfillment(models.Model):
def composed_id(self):
return '%s-%s' % (self.order.id, self.fulfillment_order)
+ def can_cancel(self):
+ return self.status != FulfillmentStatus.CANCELED
+
+ def get_total_quantity(self):
+ return sum([line.quantity for line in self])
+
class FulfillmentLine(models.Model):
order_line = models.ForeignKey(
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 271186e470..2600ee0725 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -156,3 +156,10 @@ def restock_order_lines(order):
increase_stock(line.stock, line.quantity_fulfilled)
if line.quantity_unfulfilled > 0:
deallocate_stock(line.stock, line.quantity_unfulfilled)
+
+
+def restock_fulfillment_lines(fulfillment):
+ """Return fulfilled products to corresponding stocks."""
+ for line in fulfillment:
+ if line.order_line.stock:
+ increase_stock(line.order_line.stock, line.quantity)
diff --git a/templates/dashboard/order/detail.html b/templates/dashboard/order/detail.html
index 5d51e1b827..01c050158f 100644
--- a/templates/dashboard/order/detail.html
+++ b/templates/dashboard/order/detail.html
@@ -436,20 +436,28 @@
</td>
</tr>
{% endfor %}
- <tr>
- <td colspan="2">
- {% if fulfillment.tracking_number %}
- {% blocktrans trimmed with tracking=fulfillment.tracking_number context "Fulfillment table text" %}
- Tracking number: {{ tracking }}
- {% endblocktrans %}
- {% else %}
- {% trans "Tracking number: -" context "Fulfillment table text" %}
- {% endif %}
- </td>
- </tr>
+ <tr>
+ <td colspan="2">
+ {% if fulfillment.tracking_number %}
+ {% blocktrans trimmed with tracking=fulfillment.tracking_number context "Fulfillment table text" %}
+ Tracking number: {{ tracking }}
+ {% endblocktrans %}
+ {% else %}
+ {% trans "Tracking number: -" context "Fulfillment table text" %}
+ {% endif %}
+ </td>
+ </tr>
</tbody>
</table>
</div>
+ {% if perms.order.edit_order and fulfillment.can_cancel %}
+ <div class="data-table-action">
+ <a href="#base-modal" data-href="{% url 'dashboard:fulfillment-cancel' order_pk=order.pk fulfillment_pk=fulfillment.pk %}"
+ class="btn-flat waves-effect modal-trigger-custom" title="{% trans "Cancel fulfillment" context "Fulfillment summary card action title" %}">
+ {% trans "Cancel" context "Fulfillment summary card action" %}
+ </a>
+ </div>
+ {% endif %}
</div>
{% endfor %}
<div class="card order-notes{% if not notes %} print-hide{% endif %}" id="order-notes">
diff --git a/templates/dashboard/order/modal/cancel_fulfillment.html b/templates/dashboard/order/modal/cancel_fulfillment.html
new file mode 100644
index 0000000000..2dfbd35915
--- /dev/null
+++ b/templates/dashboard/order/modal/cancel_fulfillment.html
@@ -0,0 +1,31 @@
+{% extends "dashboard/base_modal.html" %}
+
+{% load i18n %}
+{% load materializecss %}
+
+{% block action_url %}
+{% url 'dashboard:fulfillment-cancel' order_pk=order.pk fulfillment_pk=fulfillment.pk %}
+{% endblock %}
+
+{% block title %}
+{% blocktrans trimmed with fulfillment=fulfillment.composed_id context "Modal cancel fulfillment title" %}
+ Cancel fulfillment #{{ fulfillment }}
+{% endblocktrans %}
+{% endblock %}
+
+{% block content %}
+ <div class="col s12">
+ {% blocktrans trimmed with fulfillment=fulfillment.composed_id context "Modal cancel fulfillment text" %}
+ Are you sure you want cancel fulfillment #{{ fulfillment }}?
+ {% endblocktrans %}
+ {{ form.restock|materializecss }}
+ </div>
+{% endblock %}
+
+{% block cancel_action %}
+{% trans "Abort" context "Modal cancel fulfillment cancel action" %}
+{% endblock %}
+
+{% block primary_action %}
+{% trans "Cancel Fulfillment" context "Modal cancel fulfillment primary action" %}
+{% endblock %}