Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Feature: allow to disable stock management
NyanKiyoshifcf5e1ddad27
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex e1f820b36e..479988045c 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -386,7 +386,7 @@ class CancelOrderLineForm(forms.Form):super().__init__(*args, **kwargs)def cancel_line(self):- if self.line.variant:+ if self.line.variant and self.line.variant.handle_stock:deallocate_stock(self.line.variant, self.line.quantity)order = self.line.orderself.line.delete()@@ -427,7 +427,7 @@ class ChangeQuantityForm(forms.ModelForm):def save(self):quantity = self.cleaned_data['quantity']variant = self.instance.variant- if variant is not None:+ if variant and variant.handle_stock:# update stock allocationdelta = quantity - self.initial_quantityallocate_stock(variant, delta)diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.pyindex 44ebb215b2..efe462064b 100644--- a/saleor/dashboard/order/utils.py+++ b/saleor/dashboard/order/utils.py@@ -47,9 +47,10 @@ def create_packing_slip_pdf(order, fulfillment, absolute_url):def fulfill_order_line(order_line, quantity):"""Fulfill order line with given quantity."""- decrease_stock(order_line.variant, quantity)- order_line.quantity_fulfilled += quantity- order_line.save(update_fields=['quantity_fulfilled'])+ if order_line.variant.handle_stock:+ decrease_stock(order_line.variant, quantity)+ order_line.quantity_fulfilled += quantity+ order_line.save(update_fields=['quantity_fulfilled'])def update_order_with_user_addresses(order):diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 3e6fc7c1a8..d638e7045e 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -273,17 +273,22 @@ class ProductVariantForm(forms.ModelForm, AttributesMixin):class Meta:model = ProductVariant- fields = ['sku', 'price_override', 'quantity', 'cost_price']+ fields = [+ 'sku', 'price_override', 'handle_stock', 'quantity', 'cost_price']labels = {'sku': pgettext_lazy('SKU', 'SKU'),'price_override': pgettext_lazy('Override price', 'Selling price override'),'quantity': pgettext_lazy('Integer number', 'Number in stock'),- 'cost_price': pgettext_lazy('Currency amount', 'Cost price')}+ 'cost_price': pgettext_lazy('Currency amount', 'Cost price'),+ 'handle_stock': pgettext_lazy(+ 'Manage stock field', 'Automatically manage the stock')}- def __init__(self, *args, **kwargs):+ def __init__(self, *args, handle_stock_by_default=True, **kwargs):super().__init__(*args, **kwargs)+ self.initial['handle_stock'] = handle_stock_by_default+if self.instance.product.pk:self.fields['price_override'].widget.attrs['placeholder'] = self.instance.product.price.amountdiff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex aea313a261..fabd57481c 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -100,6 +100,7 @@ def product_select_type(request):@staff_member_required@permission_required('product.edit_product')def product_create(request, type_pk):+ site_settings = request.site.settingsproduct_type = get_object_or_404(ProductType, pk=type_pk)create_variant = not product_type.has_variantsproduct = Product()@@ -108,7 +109,9 @@ def product_create(request, type_pk):if create_variant:variant = ProductVariant(product=product)variant_form = forms.ProductVariantForm(- request.POST or None, instance=variant, prefix='variant')+ request.POST or None,+ handle_stock_by_default=site_settings.handle_stock_by_default,+ instance=variant, prefix='variant')variant_errors = not variant_form.is_valid()else:variant_form = None@@ -312,9 +315,13 @@ def variant_details(request, product_pk, variant_pk):@staff_member_required@permission_required('product.edit_product')def variant_create(request, product_pk):+ site_settings = request.site.settingsproduct = get_object_or_404(Product.objects.all(), pk=product_pk)variant = ProductVariant(product=product)- form = forms.ProductVariantForm(request.POST or None, instance=variant)+ form = forms.ProductVariantForm(+ request.POST or None,+ handle_stock_by_default=site_settings.handle_stock_by_default,+ instance=variant)if form.is_valid():form.save()msg = pgettext_lazy(diff --git a/saleor/dashboard/sites/forms.py b/saleor/dashboard/sites/forms.pyindex d3ecc35f92..e42e244e19 100644--- a/saleor/dashboard/sites/forms.py+++ b/saleor/dashboard/sites/forms.py@@ -19,12 +19,15 @@ class SiteForm(forms.ModelForm):class SiteSettingsForm(forms.ModelForm):class Meta:model = SiteSettings- fields = ['header_text', 'description']+ fields = ['header_text', 'description', 'handle_stock_by_default']labels = {'header_text': pgettext_lazy('Header text', 'Header text'),'description': pgettext_lazy(- 'Description', 'Description')}+ 'Description', 'Description'),+ 'handle_stock_by_default': pgettext_lazy(+ 'Manage the stock by default settings toggle label',+ 'Manage the stock by default')}class AuthorizationKeyForm(forms.ModelForm):diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex cb6e96b86b..8462e2ed2d 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -4,7 +4,6 @@ from django.shortcuts import get_object_or_404, redirectfrom ..account.utils import store_user_addressfrom ..checkout import AddressType-from ..core.exceptions import InsufficientStockfrom ..core.utils.taxes import (ZERO_MONEY, get_tax_rate_by_name, get_taxes_for_address)from ..dashboard.order.utils import get_voucher_discount_for_order@@ -150,8 +149,7 @@ def add_variant_to_order(order, variant, quantity, discounts=None, taxes=None):Raises InsufficientStock exception if quantity could not be fulfilled."""- if quantity > variant.quantity_available:- raise InsufficientStock(variant)+ variant.check_quantity(quantity)try:line = order.lines.get(variant=variant)@@ -167,7 +165,8 @@ def add_variant_to_order(order, variant, quantity, discounts=None, taxes=None):unit_price=variant.get_price(discounts, taxes),tax_rate=get_tax_rate_by_name(variant.product.tax_rate, taxes))- allocate_stock(variant, quantity)+ if variant.handle_stock:+ allocate_stock(variant, quantity)def change_order_line_quantity(line, new_quantity):@@ -182,18 +181,20 @@ def change_order_line_quantity(line, new_quantity):def restock_order_lines(order):"""Return ordered products to corresponding stocks."""for line in order:- if line.variant:+ if line.variant and line.variant.handle_stock:if line.quantity_unfulfilled > 0:deallocate_stock(line.variant, line.quantity_unfulfilled)if line.quantity_fulfilled > 0:increase_stock(line.variant, line.quantity_fulfilled)- line.quantity_fulfilled = 0- line.save(update_fields=['quantity_fulfilled'])++ if line.quantity_fulfilled > 0:+ line.quantity_fulfilled = 0+ line.save(update_fields=['quantity_fulfilled'])def restock_fulfillment_lines(fulfillment):"""Return fulfilled products to corresponding stocks."""for line in fulfillment:- if line.order_line.variant:+ if line.order_line.variant and line.order_line.variant.handle_stock:increase_stock(line.order_line.variant, line.quantity, allocate=True)diff --git a/saleor/product/migrations/0064_productvariant_handle_stock.py b/saleor/product/migrations/0064_productvariant_handle_stock.pynew file mode 100644index 0000000000..336277b995--- /dev/null+++ b/saleor/product/migrations/0064_productvariant_handle_stock.py@@ -0,0 +1,18 @@+# Generated by Django 2.0.3 on 2018-06-03 11:52++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0063_required_attr_value_order'),+ ]++ operations = [+ migrations.AddField(+ model_name='productvariant',+ name='handle_stock',+ field=models.BooleanField(default=True, help_text='Allow or not to automatically handle stock units from orders'),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex fd8103eea2..3168718e1d 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -185,6 +185,11 @@ class ProductVariant(models.Model):Product, related_name='variants', on_delete=models.CASCADE)attributes = HStoreField(default={}, blank=True)images = models.ManyToManyField('ProductImage', through='VariantImage')+ handle_stock = models.BooleanField(+ default=True,+ help_text=pgettext_lazy(+ 'product variant handle stock field help text',+ 'Allow or not to automatically handle stock units from orders'))quantity = models.IntegerField(validators=[MinValueValidator(0)], default=Decimal(1))quantity_allocated = models.IntegerField(@@ -204,7 +209,10 @@ class ProductVariant(models.Model):return max(self.quantity - self.quantity_allocated, 0)def check_quantity(self, quantity):- if quantity > self.quantity_available:+ """ Check if there is at least the given quantity in stock+ if stock handling is enabled.+ """+ if self.handle_stock and quantity > self.quantity_available:raise InsufficientStock(self)@propertydiff --git a/saleor/site/migrations/0015_sitesettings_handle_stock_by_default.py b/saleor/site/migrations/0015_sitesettings_handle_stock_by_default.pynew file mode 100644index 0000000000..0589e6e5f0--- /dev/null+++ b/saleor/site/migrations/0015_sitesettings_handle_stock_by_default.py@@ -0,0 +1,18 @@+# Generated by Django 2.0.3 on 2018-06-03 11:52++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('site', '0014_handle_taxes'),+ ]++ operations = [+ migrations.AddField(+ model_name='sitesettings',+ name='handle_stock_by_default',+ field=models.BooleanField(default=True, help_text='This will set the default value of stock handling on product and variant creation'),+ ),+ ]diff --git a/saleor/site/models.py b/saleor/site/models.pyindex fc39ca70e9..c0104640ba 100644--- a/saleor/site/models.py+++ b/saleor/site/models.py@@ -22,6 +22,12 @@ class SiteSettings(models.Model):include_taxes_in_prices = models.BooleanField(default=True)display_gross_prices = models.BooleanField(default=True)charge_taxes_on_shipping = models.BooleanField(default=True)+ handle_stock_by_default = models.BooleanField(+ default=True,+ help_text=pgettext_lazy(+ 'handle stock by default settings field help text',+ 'This will set the default value of stock handling '+ 'on product and variant creation'))class Meta:permissions = (diff --git a/templates/dashboard/product/form.html b/templates/dashboard/product/form.htmlindex 77b331dff3..07b4caf193 100644--- a/templates/dashboard/product/form.html+++ b/templates/dashboard/product/form.html@@ -97,6 +97,9 @@<div class="row">{{ variant_form.quantity|materializecss }}</div>+ <div class="row">+ {{ variant_form.handle_stock|materializecss }}+ </div>{% endif %}<div class="row">{{ product_form.category|materializecss }}diff --git a/templates/dashboard/product/product_variant/form.html b/templates/dashboard/product/product_variant/form.htmlindex 9cf352e95c..2aab4c0e84 100644--- a/templates/dashboard/product/product_variant/form.html+++ b/templates/dashboard/product/product_variant/form.html@@ -95,6 +95,9 @@<div class="row">{{ form.cost_price|materializecss }}</div>+ <div class="row">+ {{ form.handle_stock|materializecss }}+ </div></div></div></div>diff --git a/templates/dashboard/sites/form.html b/templates/dashboard/sites/form.htmlindex d519175659..88e318d642 100644--- a/templates/dashboard/sites/form.html+++ b/templates/dashboard/sites/form.html@@ -49,6 +49,9 @@<div class="row">{{ site_settings_form.description|materializecss }}</div>+ <div class="row">+ {{ site_settings_form.handle_stock_by_default|materializecss }}+ </div></div><div class="card-action right-align"><a class="btn-flat waves-effect" href="{% url 'dashboard:site-details' pk=site.pk %}" target="_blank">diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.pyindex 82f72b4885..41e977f8bd 100644--- a/tests/dashboard/test_order.py+++ b/tests/dashboard/test_order.py@@ -5,7 +5,6 @@ from django.conf import settingsfrom django.urls import reversefrom payments import PaymentStatusfrom prices import Money-from tests.utils import get_form_errors, get_redirect_locationfrom saleor.checkout import AddressType@@ -379,13 +378,17 @@ def test_view_release_order_invalid_payment_input_status(@pytest.mark.integration-def test_view_cancel_order_line(admin_client, draft_order):[email protected]('handle_stock', (True, False))+def test_view_cancel_order_line(admin_client, draft_order, handle_stock):lines_before = draft_order.lines.all()lines_before_count = lines_before.count()line = lines_before.first()line_quantity = line.quantityquantity_allocated_before = line.variant.quantity_allocated+ line.variant.handle_stock = handle_stock+ line.variant.save()+url = reverse('dashboard:orderline-cancel', kwargs={'order_pk': draft_order.pk,@@ -400,10 +403,16 @@ def test_view_cancel_order_line(admin_client, draft_order):# check ordered item removallines_after = Order.objects.get().lines.all()assert lines_before_count - 1 == lines_after.count()+# check stock deallocationline.variant.refresh_from_db()- assert line.variant.quantity_allocated == (- quantity_allocated_before - line_quantity)++ if handle_stock:+ assert line.variant.quantity_allocated == (+ quantity_allocated_before - line_quantity)+ else:+ assert line.variant.quantity_allocated == quantity_allocated_before+url = reverse('dashboard:orderline-cancel', kwargs={'order_pk': draft_order.pk,@@ -416,11 +425,16 @@ def test_view_cancel_order_line(admin_client, draft_order):@pytest.mark.integration-def test_view_change_order_line_quantity(admin_client, draft_order):[email protected]('handle_stock', (True, False))+def test_view_change_order_line_quantity(+ admin_client, draft_order, handle_stock):lines_before_quantity_change = draft_order.lines.all()lines_before_quantity_change_count = lines_before_quantity_change.count()line = lines_before_quantity_change.first()+ line.variant.handle_stock = handle_stock+ line.variant.save()+url = reverse('dashboard:orderline-change-quantity',kwargs={'order_pk': draft_order.pk, 'line_pk': line.pk})@@ -437,8 +451,14 @@ def test_view_change_order_line_quantity(admin_client, draft_order):lines_after = Order.objects.get().lines.all()# order should have the same linesassert lines_before_quantity_change_count == lines_after.count()- # stock allocation should be 2 now- assert line.variant.quantity_allocated == 2+ line.variant.refresh_from_db()++ if handle_stock:+ # stock allocation should be 2 now+ assert line.variant.quantity_allocated == 2+ else:+ assert line.variant.quantity_allocated == 3+line.refresh_from_db()# source line quantity should be decreased to 2assert line.quantity == 2diff --git a/tests/test_cart.py b/tests/test_cart.pyindex f9c092d666..07a006a7aa 100644--- a/tests/test_cart.py+++ b/tests/test_cart.py@@ -375,8 +375,12 @@ def test_form_when_variant_does_not_exist():assert not form.is_valid()-def test_add_to_cart_form_when_insufficient_stock(product):[email protected]('handle_stock', (True, False))+def test_add_to_cart_form_when_insufficient_stock(product, handle_stock):variant = product.variants.first()+ variant.handle_stock = handle_stock+ variant.save()+cart_lines = []cart = Mock(add=lambda variant, quantity: cart_lines.append(variant),@@ -384,7 +388,11 @@ def test_add_to_cart_form_when_insufficient_stock(product):form = forms.AddToCartForm(data={'quantity': 1}, cart=cart, product=Mock())form.get_variant = Mock(return_value=variant)- assert not form.is_valid()++ if handle_stock:+ assert not form.is_valid()+ else:+ assert form.is_valid()def test_replace_cart_line_form(cart, product):diff --git a/tests/test_order.py b/tests/test_order.pyindex 85b41f3ca0..06bf513da7 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -5,7 +5,6 @@ from django.urls import reversefrom django_countries.fields import Countryfrom payments import FraudStatus, PaymentStatusfrom prices import Money, TaxedMoney-from tests.utils import get_redirect_locationfrom saleor.account.models import User@@ -81,15 +80,22 @@ def test_add_variant_to_order_adds_line_for_new_variant(assert line.tax_rate == taxes[product.tax_rate]['value'][email protected]('handle_stock', (True, False))def test_add_variant_to_order_allocates_stock_for_new_variant(- order_with_lines, product):+ order_with_lines, product, handle_stock):variant = product.variants.get()+ variant.handle_stock = handle_stock+ variant.save()+stock_before = variant.quantity_allocatedadd_variant_to_order(order_with_lines, variant, 1)variant.refresh_from_db()- assert variant.quantity_allocated == stock_before + 1+ if handle_stock:+ assert variant.quantity_allocated == stock_before + 1+ else:+ assert variant.quantity_allocated == stock_beforedef test_add_variant_to_order_edits_line_for_existing_variant(@@ -163,12 +169,22 @@ def test_add_note_to_order(order_with_lines):assert order.notes.first().content == 'test_note'-def test_restock_order_lines(order_with_lines):[email protected]('handle_stock', (True, False))+def test_restock_order_lines(order_with_lines, handle_stock):+order = order_with_linesline_1 = order.lines.first()line_2 = order.lines.last()++ line_1.variant.handle_stock = handle_stock+ line_2.variant.handle_stock = handle_stock++ line_1.variant.save()+ line_2.variant.save()+stock_1_quantity_allocated_before = line_1.variant.quantity_allocatedstock_2_quantity_allocated_before = line_2.variant.quantity_allocated+stock_1_quantity_before = line_1.variant.quantitystock_2_quantity_before = line_2.variant.quantity@@ -176,10 +192,18 @@ def test_restock_order_lines(order_with_lines):line_1.variant.refresh_from_db()line_2.variant.refresh_from_db()- assert line_1.variant.quantity_allocated == (- stock_1_quantity_allocated_before - line_1.quantity)- assert line_2.variant.quantity_allocated == (- stock_2_quantity_allocated_before - line_2.quantity)++ if handle_stock:+ assert line_1.variant.quantity_allocated == (+ stock_1_quantity_allocated_before - line_1.quantity)+ assert line_2.variant.quantity_allocated == (+ stock_2_quantity_allocated_before - line_2.quantity)+ else:+ assert line_1.variant.quantity_allocated == (+ stock_1_quantity_allocated_before)+ assert line_2.variant.quantity_allocated == (+ stock_2_quantity_allocated_before)+assert line_1.variant.quantity == stock_1_quantity_beforeassert line_2.variant.quantity == stock_2_quantity_beforeassert line_1.quantity_fulfilled == 0diff --git a/tests/test_product.py b/tests/test_product.pyindex 1bcf370b6e..f49dae5c50 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -21,22 +21,22 @@ from .utils import filter_products_by_attribute@pytest.mark.parametrize(- 'func, expected_quanitty, expected_quant_allocated',+ 'func, expected_quantity, expected_quantity_allocated',((increase_stock, 150, 80),(decrease_stock, 50, 30),(deallocate_stock, 100, 30),(allocate_stock, 100, 130)))def test_stock_utils(- product, func, expected_quanitty, expected_quant_allocated):+ product, func, expected_quantity, expected_quantity_allocated):variant = product.variants.first()variant.quantity = 100variant.quantity_allocated = 80variant.save()func(variant, 50)variant.refresh_from_db()- assert variant.quantity == expected_quanitty- assert variant.quantity_allocated == expected_quant_allocated+ assert variant.quantity == expected_quantity+ assert variant.quantity_allocated == expected_quantity_allocateddef test_product_page_redirects_to_correct_slug(client, product):