Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Save fulfillment lines with formset
Anna Siwik8b56ae8765c1
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 52812853cc..6846faca19 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -15,7 +15,7 @@ from ...order.emails import send_note_confirmationfrom ...order.models import Fulfillment, FulfillmentLine, OrderLine, OrderNotefrom ...order.utils import (add_variant_to_order, cancel_order, change_order_line_quantity,- merge_duplicates_into_order_line, recalculate_order)+ fulfill_order_line, merge_duplicates_into_order_line, recalculate_order)from ...product.models import Product, ProductVariant, Stockfrom ...product.utils import allocate_stock, deallocate_stockfrom ..forms import AjaxSelect2ChoiceField@@ -324,7 +324,22 @@ class FulfillmentForm(forms.ModelForm):self.instance.order = order+class BaseFulfillmentLineFormSet(forms.BaseModelFormSet):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ for form in self.forms:+ form.empty_permitted = False++class FulfillmentLineForm(forms.ModelForm):class Meta:model = FulfillmentLine- fields = ['fulfillment', 'order_line', 'quantity']+ fields = ['order_line', 'quantity']++ def clean_quantity(self):+ quantity = self.cleaned_data.get('quantity')+ if quantity == 0:+ raise forms.ValidationError(pgettext_lazy(+ 'Fulfill order line form error',+ 'Order line could not be fulfilled with zero quantity.'))+ return quantitydiff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 8dbc9574b7..54957fbb71 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -15,15 +15,16 @@ from prices import Money, TaxedMoneyfrom ...core.exceptions import InsufficientStockfrom ...core.utils import ZERO_TAXED_MONEY, get_paginator_itemsfrom ...order import OrderStatus-from ...order.models import Fulfillment, Order, OrderLine, OrderNote, FulfillmentLine+from ...order.models import (+ FulfillmentLine, Fulfillment, Order, OrderLine, OrderNote)from ...product.models import StockLocationfrom ..views import staff_member_requiredfrom .filters import OrderFilterfrom .forms import (- AddressForm, AddVariantToOrderForm, CancelOrderForm, CancelOrderLineForm,- CapturePaymentForm, ChangeQuantityForm, ChangeStockForm, FulfillmentForm,- OrderNoteForm, RefundPaymentForm, ReleasePaymentForm, RemoveVoucherForm,- FulfillmentLineForm)+ AddressForm, AddVariantToOrderForm, BaseFulfillmentLineFormSet,+ CancelOrderForm, CancelOrderLineForm, CapturePaymentForm,+ ChangeQuantityForm, ChangeStockForm, FulfillmentForm, FulfillmentLineForm,+ OrderNoteForm, RefundPaymentForm, ReleasePaymentForm, RemoveVoucherForm)from .utils import (create_invoice_pdf, create_packing_slip_pdf, get_statics_absolute_url)@@ -373,21 +374,26 @@ def orderline_change_stock(request, order_pk, line_pk):def fulfill_order_lines(request, order_pk):qs = Order.objects.prefetch_related('lines')order = get_object_or_404(qs, pk=order_pk)- lines = order.lines.all()+ lines = order.get_unfulfilled_lines()status = 200form = FulfillmentForm(request.POST or None, order=order, instance=Fulfillment())FulfillmentLineFormSet = modelformset_factory(- FulfillmentLine, form=FulfillmentLineForm, extra=lines.count())- initial_kwargs = [- {'order_line': line, 'quantity': line.quantity} for line in lines]+ FulfillmentLine, form=FulfillmentLineForm, extra=len(lines),+ formset=BaseFulfillmentLineFormSet)+ initial = [+ {'order_line': line, 'quantity': line.quantity_unfulfilled}+ for line in lines]formset = FulfillmentLineFormSet(- request.POST or None, initial=initial_kwargs)- if form.is_valid():+ request.POST or None, queryset=FulfillmentLine.objects.none(),+ initial=initial)+ valid_forms = [line_form for line_form in formset if line_form.is_valid()]+ if valid_forms and form.is_valid():fulfillment = form.save()- for form in formset:- # TODO: save forms with fulfillment (only if quantity > 0)- pass+ for line_form in valid_forms:+ line = line_form.save(commit=False)+ line.fulfillment = fulfillment+ line.save()elif form.errors:status = 400ctx = {'form': form, 'formset': formset, 'order': order}diff --git a/saleor/order/models.py b/saleor/order/models.pyindex d92fa1610f..4a527aff66 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -120,6 +120,9 @@ class Order(models.Model):def __str__(self):return '#%d' % (self.id,)+ def get_unfulfilled_lines(self):+ return [line for line in self if not line.is_fulfilled()]+def get_absolute_url(self):return reverse('order:details', kwargs={'token': self.token})@@ -193,6 +196,11 @@ class OrderLine(models.Model):def get_total(self):return self.unit_price * self.quantity+ @property+ def quantity_unfulfilled(self):+ lines = FulfillmentLine.objects.filter(order_line=self)+ return self.quantity - sum([line.quantity for line in lines])+def is_fulfilled(self):lines = FulfillmentLine.objects.filter(order_line=self)return sum([line.quantity for line in lines]) >= self.quantitydiff --git a/templates/dashboard/order/detail.html b/templates/dashboard/order/detail.htmlindex c75062f0f9..19cc409b0e 100644--- a/templates/dashboard/order/detail.html+++ b/templates/dashboard/order/detail.html@@ -438,7 +438,7 @@Tracking number: {{ tracking }}{% endblocktrans %}{% else %}- {% trans "Tracking number: no tracking number" context "Fulfillment table text" %}+ {% trans "Tracking number: -" context "Fulfillment table text" %}{% endif %}</td></tr>diff --git a/templates/dashboard/order/modal/fulfill_order_lines.html b/templates/dashboard/order/modal/fulfill_order_lines.htmlindex 3dade31045..8db45f1dbb 100644--- a/templates/dashboard/order/modal/fulfill_order_lines.html+++ b/templates/dashboard/order/modal/fulfill_order_lines.html@@ -30,7 +30,7 @@</tr></thead><tbody>- {% for line in order %}+ {% for line in order.get_unfulfilled_lines %}<tr><td>{{ line.product_name }}<br>@@ -40,13 +40,18 @@</td><td class="right-align">{% get_formset_form formset forloop.counter0 as line_form %}+ <input id="{{ line_form.order_line.auto_id }}"+ type="hidden"+ name="{{ line_form.order_line.html_name }}"+ required="{{ line_form.order_line.field.required }}"+ value="{{ line_form.order_line.value }}"><input id="{{ line_form.quantity.auto_id }}"- max="{{ line.quantity }}"+ max="{{ line.quantity_unfulfilled }}"min="0"name="{{ line_form.quantity.html_name }}"required="{{ line_form.quantity.field.required }}"type="number"- value="{% if line_form.quantity.value %}{{ line_form.quantity.value }}{% endif %}">+ value="{{ line_form.quantity.value }}"></td></tr>{% endfor %}