Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Introduce stock selection logic
Patryk Zawadzki2e104f9fe262
diff --git a/saleor/order/models.py b/saleor/order/models.pyindex de3f192f2d..17557d4e8d 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -20,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+from ..product.models import Product, ProductVariant, Stockfrom ..userprofile.models import Address@@ -219,16 +219,21 @@ class DeliveryGroup(models.Model, ItemSet):for item_line in partition:product_variant = item_line.productprice = item_line.get_price_per_item()- stock = product_variant.select_stockrecord()+ quantity = item_line.get_quantity()+ stock = product_variant.select_stockrecord(quantity)self.items.create(product=product_variant.product,- quantity=item_line.get_quantity(),+ quantity=quantity,unit_price_net=price.net,product_name=smart_text(product_variant),product_sku=product_variant.sku,unit_price_gross=price.gross,stock=stock,stock_location=stock.location if stock else None)+ if stock:+ stock.quantity_allocated = (+ models.F('quantity_allocated') + quantity)+ stock.save(update_fields=['quantity_allocated'])def get_total_quantity(self):return sum([item.get_quantity() for item in self])diff --git a/saleor/order/test_order.py b/saleor/order/test_order.pyindex d72fae93f9..a05c4d2214 100644--- a/saleor/order/test_order.py+++ b/saleor/order/test_order.py@@ -1,23 +1,39 @@from prices import Price-from .models import Order+from ..cart import Cart, SessionCart+from ..product.models import Stock+from ..product.test_product import product_in_stock+from ..userprofile.test_userprofile import billing_address+from . import modelsdef test_total_property():- order = Order(total_net=20, total_tax=5)+ order = models.Order(total_net=20, total_tax=5)assert order.total.gross == 25assert order.total.tax == 5assert order.total.net == 20def test_total_property_empty_value():- order = Order(total_net=None, total_tax=None)+ order = models.Order(total_net=None, total_tax=None)assert order.total is Nonedef test_total_setter():price = Price(net=10, gross=20, currency='USD')- order = Order()+ order = models.Order()order.total = priceassert order.total_net.net == 10assert order.total_tax.net == 10+++def test_stock_allocation(billing_address, product_in_stock):+ variant = product_in_stock.variants.get()+ cart = Cart(session_cart=SessionCart())+ cart.add(variant, quantity=2)+ order = models.Order.objects.create(billing_address=billing_address)+ delivery_group = models.DeliveryGroup.objects.create(order=order)+ delivery_group.add_items_from_partition(cart)+ order_line = delivery_group.items.get()+ stock = order_line.stock+ assert stock.quantity_allocated == 2diff --git a/saleor/product/migrations/0011_stock_quantity_allocated.py b/saleor/product/migrations/0011_stock_quantity_allocated.pynew file mode 100644index 0000000000..1ea89543b6--- /dev/null+++ b/saleor/product/migrations/0011_stock_quantity_allocated.py@@ -0,0 +1,22 @@+# -*- coding: utf-8 -*-+# Generated by Django 1.9.2 on 2016-02-08 14:45+from __future__ import unicode_literals++from decimal import Decimal+import django.core.validators+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0010_auto_20160129_0826'),+ ]++ operations = [+ migrations.AddField(+ model_name='stock',+ name='quantity_allocated',+ field=models.IntegerField(default=Decimal('0'), validators=[django.core.validators.MinValueValidator(0)], verbose_name='allocated quantity'),+ ),+ ]diff --git a/saleor/product/models/base.py b/saleor/product/models/base.pyindex 4b6ceaef14..ea0ec0993b 100644--- a/saleor/product/models/base.py+++ b/saleor/product/models/base.py@@ -164,7 +164,7 @@ class ProductVariant(models.Model, Item):raise InsufficientStock(self)def get_stock_quantity(self):- return sum([stock.quantity for stock in self.stock.all()])+ return max([stock.quantity_available for stock in self.stock.all()])def get_price_per_item(self, discounts=None, **kwargs):price = self.price_override or self.product.price@@ -193,7 +193,7 @@ class ProductVariant(models.Model, Item):def is_in_stock(self):return any(- [stock_item.quantity > 0 for stock_item in self.stock.all()])+ [stock.quantity_available > 0 for stock in self.stock.all()])def get_attribute(self, pk):return self.attributes.get(str(pk))@@ -211,10 +211,12 @@ class ProductVariant(models.Model, Item):return '%s (%s)' % (smart_text(self.product),self.display_variant(attributes=attributes))- def select_stockrecord(self):+ def select_stockrecord(self, quantity=1):# By default selects stock with lowest cost price- stock = sorted(self.stock.all(), key=lambda stock: stock.cost_price,- reverse=True)+ stock = filter(+ lambda stock: stock.quantity_available >= quantity,+ self.stock.all())+ stock = sorted(stock, key=lambda stock: stock.cost_price, reverse=True)if stock:return stock[0]@@ -234,6 +236,9 @@ class Stock(models.Model):quantity = models.IntegerField(pgettext_lazy('Stock item field', 'quantity'),validators=[MinValueValidator(0)], default=Decimal(1))+ quantity_allocated = models.IntegerField(+ pgettext_lazy('Stock item field', 'allocated quantity'),+ validators=[MinValueValidator(0)], default=Decimal(0))cost_price = PriceField(pgettext_lazy('Stock item field', 'cost price'),currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,@@ -246,6 +251,10 @@ class Stock(models.Model):def __str__(self):return '%s - %s' % (self.variant.name, self.location)+ @property+ def quantity_available(self):+ return max(self.quantity - self.quantity_allocated, 0)+@python_2_unicode_compatibleclass ProductAttribute(models.Model):diff --git a/saleor/product/test_product.py b/saleor/product/test_product.pynew file mode 100644index 0000000000..b669a4fff5--- /dev/null+++ b/saleor/product/test_product.py@@ -0,0 +1,27 @@+import pytest++from . import models+++def product_in_stock(db):+ product = models.Product.objects.create(+ name='Test product', price=10, weight=1)+ variant = models.ProductVariant.objects.create(product=product, sku='123')+ models.Stock.objects.create(+ variant=variant, cost_price=1, quantity=5, quantity_allocated=5,+ location='Warehouse 1')+ models.Stock.objects.create(+ variant=variant, cost_price=100, quantity=5, quantity_allocated=5,+ location='Warehouse 2')+ models.Stock.objects.create(+ variant=variant, cost_price=10, quantity=5, quantity_allocated=0,+ location='Warehouse 3')+ return product+++def test_stock_slector(product_in_stock):+ variant = product_in_stock.variants.get()+ preferred_stock = variant.select_stockrecord(5)+ assert preferred_stock.quantity_available >= 5diff --git a/saleor/userprofile/test_userprofile.py b/saleor/userprofile/test_userprofile.pyindex 88bacf8b24..4a6261e915 100644--- a/saleor/userprofile/test_userprofile.py+++ b/saleor/userprofile/test_userprofile.py@@ -1,7 +1,22 @@+# encoding: utf-8+from __future__ import unicode_literals+import i18naddressimport pytestfrom . import forms+from . import models+++def billing_address(db):+ return models.Address.objects.create(+ first_name='John', last_name='Doe',+ company_name='Mirumee Software',+ street_address_1='Tęczowa 7',+ city='Wrocław',+ postal_code='53-601',+ country='PL')@pytest.mark.parametrize('country', ['CN', 'PL', 'US'])