Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
(De)allocate stock when editing quantity
Patryk Zawadzki0a51cf26d525
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 4f9dcb0763..df9f6381c7 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -2,7 +2,6 @@ from __future__ import unicode_literalsfrom django import formsfrom django.conf import settings-from django.db.models import Ffrom django.shortcuts import get_object_or_404from django.utils.translation import ugettext_lazy as _from django.utils.translation import pgettext_lazy@@ -13,7 +12,7 @@ from satchless.item import InsufficientStockfrom ...cart.forms import QuantityFieldfrom ...order.models import DeliveryGroup, Order, OrderedItem, OrderNote-from ...product.models import ProductVariant+from ...product.models import ProductVariant, Stockclass OrderNoteForm(forms.ModelForm):@@ -111,7 +110,7 @@ class MoveItemsForm(forms.Form):choice = self.cleaned_data['target_group']old_group = self.item.delivery_groupif choice == 'new':- # For new group we are set the same delivery name but with zero price+ # For new group we use the same delivery name but zero pricetarget_group = old_group.order.groups.create(status=old_group.status,shipping_method_name=old_group.shipping_method_name)@@ -128,8 +127,9 @@ class ChangeQuantityForm(forms.ModelForm):def __init__(self, *args, **kwargs):super(ChangeQuantityForm, self).__init__(*args, **kwargs)+ self.initial_quantity = self.instance.quantityself.fields['quantity'].widget.attrs.update({'min': 1})- self.fields['quantity'].initial = self.instance.quantity+ self.fields['quantity'].initial = self.initial_quantitydef clean_quantity(self):quantity = self.cleaned_data['quantity']@@ -145,6 +145,11 @@ class ChangeQuantityForm(forms.ModelForm):def save(self):quantity = self.cleaned_data['quantity']+ stock = self.instance.stock+ if stock is not None:+ # update stock allocation+ delta = quantity - self.initial_quantity+ Stock.objects.allocate_stock(stock, delta)self.instance.change_quantity(quantity)@@ -168,11 +173,8 @@ class ShipGroupForm(forms.ModelForm):for line in self.instance.items.all():stock = line.stockif stock is not None:- quantity = line.quantity# remove and deallocate quantity- stock.quantity = F('quantity') - quantity- stock.quantity_allocated = F('quantity_allocated') - quantity- stock.save(update_fields=['quantity', 'quantity_allocated'])+ Stock.objects.decrease_stock(stock, line.quantity)self.instance.change_status('shipped')statuses = [g.status for g in order.groups.all()]if 'shipped' in statuses and 'new' not in statuses:diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 519e15cc53..e7b1720181 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -9,7 +9,6 @@ from django.core.exceptions import ObjectDoesNotExistfrom django.core.urlresolvers import reversefrom django.core.validators import MaxValueValidator, MinValueValidatorfrom django.db import models-from django.db.models import Ffrom django.utils.encoding import python_2_unicode_compatible, smart_textfrom django.utils.timezone import nowfrom django.utils.translation import pgettext_lazy@@ -21,7 +20,7 @@ from satchless.item import ItemLine, ItemSetfrom ..core.utils import build_absolute_urifrom ..discount.models import Voucher-from ..product.models import Product, ProductVariant, Stock+from ..product.models import Product, Stockfrom ..userprofile.models import Address@@ -29,14 +28,12 @@ from ..userprofile.models import Addressclass Order(models.Model, ItemSet):STATUS_CHOICES = (('new', pgettext_lazy('Order status field value', 'Processing')),- ('cancelled', pgettext_lazy('Order status field value',- 'Cancelled')),+ ('cancelled', pgettext_lazy('Order status field value', 'Cancelled')),('payment-pending', pgettext_lazy('Order status field value','Waiting for payment')),('fully-paid', pgettext_lazy('Order status field value','Fully paid')),- ('shipped', pgettext_lazy('Order status field value',- 'Shipped')))+ ('shipped', pgettext_lazy('Order status field value', 'Shipped')))status = models.CharField(pgettext_lazy('Order field', 'order status'),max_length=32, choices=STATUS_CHOICES, default='new')@@ -49,13 +46,14 @@ class Order(models.Model, ItemSet):user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='orders',verbose_name=pgettext_lazy('Order field', 'user'))- tracking_client_id = models.CharField(max_length=36, blank=True,- editable=False)- billing_address = models.ForeignKey(Address, related_name='+',- editable=False)- shipping_address = models.ForeignKey(Address, related_name='+',- editable=False, null=True)- anonymous_user_email = models.EmailField(blank=True, default='', editable=False)+ tracking_client_id = models.CharField(+ max_length=36, blank=True, editable=False)+ billing_address = models.ForeignKey(+ Address, related_name='+', editable=False)+ shipping_address = models.ForeignKey(+ Address, related_name='+', editable=False, null=True)+ anonymous_user_email = models.EmailField(+ blank=True, default='', editable=False)token = models.CharField(pgettext_lazy('Order field', 'token'), max_length=36, unique=True)total_net = PriceField(@@ -233,8 +231,7 @@ class DeliveryGroup(models.Model, ItemSet):stock_location=stock.location if stock else None)if stock:# allocate quantity to avoid overselling- stock.quantity_allocated = F('quantity_allocated') + quantity- stock.save(update_fields=['quantity_allocated'])+ Stock.objects.allocate_stock(stock, quantity)def get_total_quantity(self):return sum([item.get_quantity() for item in self])@@ -260,6 +257,7 @@ class OrderedItemManager(models.Manager):delivery_group=target_group, product=item.product,product_name=item.product_name, product_sku=item.product_sku,quantity=quantity, unit_price_net=item.unit_price_net,+ stock=item.stock,unit_price_gross=item.unit_price_gross)else:target_item.quantity += quantitydiff --git a/saleor/product/models/base.py b/saleor/product/models/base.pyindex a403c59734..c1b0d040fe 100644--- a/saleor/product/models/base.py+++ b/saleor/product/models/base.py@@ -7,7 +7,7 @@ from django.conf import settingsfrom django.core.urlresolvers import reversefrom django.core.validators import MinValueValidator, RegexValidatorfrom django.db import models-from django.db.models import Q, Manager+from django.db.models import F, Q, Managerfrom django.utils.encoding import python_2_unicode_compatible, smart_textfrom django.utils.text import slugifyfrom django.utils.translation import pgettext_lazy@@ -228,6 +228,22 @@ class ProductVariant(models.Model, Item):return stock.cost_price+class StockManager(models.Manager):++ def allocate_stock(self, stock, quantity):+ stock.quantity_allocated = F('quantity_allocated') + quantity+ stock.save(update_fields=['quantity_allocated'])++ def deallocate_stock(self, stock, quantity):+ stock.quantity_allocated = F('quantity_allocated') - quantity+ stock.save(update_fields=['quantity_allocated'])++ def decrease_stock(self, stock, quantity):+ stock.quantity = F('quantity_allocated') - quantity+ stock.quantity_allocated = F('quantity_allocated') - quantity+ stock.save(update_fields=['quantity', 'quantity_allocated'])++@python_2_unicode_compatibleclass Stock(models.Model):variant = models.ForeignKey(@@ -246,6 +262,8 @@ class Stock(models.Model):currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,blank=True, null=True)+ objects = StockManager()+class Meta:app_label = 'product'unique_together = ('variant', 'location')