Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Drop Stock WIP
Pacu29f360b21d84b
diff --git a/saleor/cart/forms.py b/saleor/cart/forms.pyindex 48146e074e..3706a500ad 100644--- a/saleor/cart/forms.py+++ b/saleor/cart/forms.py@@ -71,7 +71,7 @@ class AddToCartForm(forms.Form):try:product_variant.check_quantity(new_quantity)except InsufficientStock as e:- remaining = e.item.get_stock_quantity() - used_quantity+ remaining = e.item.quantity_available - used_quantityif remaining:msg = self.error_messages['insufficient-stock']self.add_error('quantity', msg % remaining)@@ -122,7 +122,7 @@ class ReplaceCartLineForm(AddToCartForm):except InsufficientStock as e:msg = self.error_messages['insufficient-stock']raise forms.ValidationError(- msg % e.item.get_stock_quantity())+ msg % e.item.quantity_available)return quantitydef clean(self):diff --git a/saleor/cart/utils.py b/saleor/cart/utils.pyindex 6d449a20de..aefae7f340 100644--- a/saleor/cart/utils.py+++ b/saleor/cart/utils.py@@ -54,7 +54,7 @@ def remove_unavailable_variants(cart):try:cart.add(line.variant, quantity=line.quantity, replace=True)except InsufficientStock as e:- quantity = e.item.get_stock_quantity()+ quantity = e.item.quantity_availablecart.add(line.variant, quantity=quantity, replace=True)diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 07e699fe99..3ccf0f1405 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -387,17 +387,16 @@ def create_order_line(order):product = Product.objects.all().order_by('?')[0]variant = product.variants.all()[0]quantity = random.randrange(1, 5)- stock = variant.stock.first()- stock.quantity += quantity- stock.quantity_allocated += quantity- stock.save()+ variant.quantity += quantity+ variant.quantity_allocated += quantity+ variant.save()return order.lines.create(product=product,product_name=product.name,product_sku=variant.sku,is_shipping_required=product.product_type.is_shipping_required,quantity=quantity,- stock=stock,+ variant=variant,unit_price=TaxedMoney(net=product.price, gross=product.price))diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 44c5ed83b8..d31ef70552 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -20,8 +20,7 @@ from ...order.models import (Fulfillment, FulfillmentLine, Order, OrderLine, OrderNote, Payment)from ...order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order,- change_order_line_quantity, merge_duplicates_into_order_line,- recalculate_order)+ change_order_line_quantity, recalculate_order)from ...product.models import Product, ProductVariantfrom ...product.utils import allocate_stock, deallocate_stockfrom ...shipping.models import ANY_COUNTRY, ShippingMethodCountry@@ -387,8 +386,8 @@ class CancelOrderLineForm(forms.Form):super().__init__(*args, **kwargs)def cancel_line(self):- if self.line.stock:- deallocate_stock(self.line.stock, self.line.quantity)+ if self.line.variant:+ deallocate_stock(self.line.variant, self.line.quantity)order = self.line.orderself.line.delete()recalculate_order(order)@@ -413,8 +412,8 @@ class ChangeQuantityForm(forms.ModelForm):def clean_quantity(self):quantity = self.cleaned_data['quantity']delta = quantity - self.initial_quantity- stock = self.instance.stock- if stock and delta > stock.quantity_available:+ variant = self.instance.variant+ if variant and delta > variant.quantity_available:raise forms.ValidationError(npgettext_lazy('Change quantity form error',@@ -422,16 +421,16 @@ class ChangeQuantityForm(forms.ModelForm):'Only %(remaining)d remaining in stock.','remaining') % {'remaining': (- self.initial_quantity + stock.quantity_available)})+ self.initial_quantity + variant.quantity_available)}) # noqareturn quantitydef save(self):quantity = self.cleaned_data['quantity']- stock = self.instance.stock- if stock is not None:+ variant = self.instance.variant+ if variant is not None:# update stock allocationdelta = quantity - self.initial_quantity- allocate_stock(stock, delta)+ allocate_stock(variant, delta)change_order_line_quantity(self.instance, quantity)recalculate_order(self.instance.order)return self.instance@@ -551,48 +550,6 @@ class PaymentFilterForm(forms.Form):status = forms.ChoiceField(choices=PAYMENT_STATUS_CHOICES)-class StockChoiceField(forms.ModelChoiceField):- def label_from_instance(self, obj):- return obj.location.name---class ChangeStockForm(forms.ModelForm):- stock = StockChoiceField(queryset=Stock.objects.none())-- class Meta:- model = OrderLine- fields = ['stock']- labels = {- 'stock': pgettext_lazy(- 'Stock record', 'Stock')}-- def __init__(self, *args, **kwargs):- super().__init__(*args, **kwargs)- sku = self.instance.product_sku- self.fields['stock'].queryset = Stock.objects.filter(variant__sku=sku)- self.old_stock = self.instance.stock-- def clean_stock(self):- stock = self.cleaned_data['stock']- if stock and stock.quantity_available < self.instance.quantity:- raise forms.ValidationError(- pgettext_lazy(- 'Change stock form error',- 'Only %(remaining)d remaining in this stock.') % {- 'remaining': stock.quantity_available})- return stock-- def save(self, commit=True):- quantity = self.instance.quantity- stock = self.instance.stock- if self.old_stock:- deallocate_stock(self.old_stock, quantity)- allocate_stock(stock, quantity)- super().save(commit)- merge_duplicates_into_order_line(self.instance)- return self.instance--class AddVariantToOrderForm(forms.Form):"""Allow adding lines with given quantity to an order."""@@ -624,7 +581,7 @@ class AddVariantToOrderForm(forms.Form):'Add item form error','Could not add item. ''Only %(remaining)d remaining in stock.' %- {'remaining': e.item.get_stock_quantity()}))+ {'remaining': e.item.quantity_available}))self.add_error('quantity', error)return cleaned_datadiff --git a/saleor/dashboard/order/urls.py b/saleor/dashboard/order/urls.pyindex 4bc2ccce22..9308cc21dc 100644--- a/saleor/dashboard/order/urls.py+++ b/saleor/dashboard/order/urls.py@@ -43,8 +43,8 @@ urlpatterns = [views.orderline_change_quantity, name='orderline-change-quantity'),url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/cancel/$',views.orderline_cancel, name='orderline-cancel'),- url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/change-stock/$',- views.orderline_change_stock, name='orderline-change-stock'),+ url(r'^(?P<order_pk>\d+)/remove-voucher/$',+ views.remove_order_voucher, name='order-remove-voucher'),url(r'^(?P<order_pk>\d+)/add-variant/$',views.add_variant_to_order, name='add-variant-to-order'),url(r'^(?P<order_pk>\d+)/fulfill/$',diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.pyindex a4925c5eaa..f313e74320 100644--- a/saleor/dashboard/order/utils.py+++ b/saleor/dashboard/order/utils.py@@ -47,7 +47,7 @@ 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.stock, quantity)+ decrease_stock(order_line.variant, quantity)order_line.quantity_fulfilled += quantityorder_line.save(update_fields=['quantity_fulfilled'])diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 168bf8caa1..7970b894a5 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -32,10 +32,12 @@ from .forms import (FulfillmentTrackingNumberForm, OrderCustomerForm, OrderEditDiscountForm,OrderEditVoucherForm, OrderMarkAsPaidForm, OrderNoteForm,OrderRemoveCustomerForm, OrderRemoveShippingForm, OrderRemoveVoucherForm,- OrderShippingForm, RefundPaymentForm, ReleasePaymentForm)+ OrderShippingForm, RefundPaymentForm, ReleasePaymentForm,+ RemoveVoucherForm)from .utils import (create_invoice_pdf, create_packing_slip_pdf, get_statics_absolute_url,- save_address_in_order)+ save_address_in_order, send_fulfillment_confirmation,+ send_fulfillment_update)@staff_member_required@@ -560,27 +562,6 @@ def fulfillment_packing_slips(request, order_pk, fulfillment_pk):return response-@staff_member_required-@permission_required('order.edit_order')-def orderline_change_stock(request, order_pk, line_pk):- orders = Order.objects.drafts().prefetch_related('lines')- order = get_object_or_404(orders, pk=order_pk)- line = get_object_or_404(order.lines, pk=line_pk)- status = 200- form = ChangeStockForm(request.POST or None, instance=line)- if form.is_valid():- form.save()- msg = pgettext_lazy(- 'Dashboard message',- 'Stock location changed for %s') % form.instance.product_sku- messages.success(request, msg)- elif form.errors:- status = 400- ctx = {'order_pk': order_pk, 'line_pk': line_pk, 'form': form}- template = 'dashboard/order/modal/order_line_stock.html'- return TemplateResponse(request, template, ctx, status=status)--@staff_member_required@permission_required('order.edit_order')def fulfill_order_lines(request, order_pk):diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 84b6c6a656..9397efb02e 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -12,7 +12,7 @@ from mptt.forms import TreeNodeChoiceFieldfrom . import ProductBulkActionfrom ...product.models import (AttributeChoiceValue, Category, Collection, Product, ProductAttribute,- ProductImage, ProductType, ProductVariant, Stock, VariantImage)+ ProductImage, ProductType, ProductVariant, VariantImage)from ...product.thumbnails import create_product_thumbnailsfrom ...product.utils.attributes import get_name_from_attributesfrom ..forms import ModelChoiceOrCreationField, OrderedModelMultipleChoiceField@@ -304,14 +304,6 @@ class VariantBulkDeleteForm(forms.Form):items.delete()-class StockBulkDeleteForm(forms.Form):- items = forms.ModelMultipleChoiceField(queryset=Stock.objects)-- def delete(self):- items = Stock.objects.filter(pk__in=self.cleaned_data['items'])- items.delete()--class ProductImageForm(forms.ModelForm):use_required_attribute = Falsevariants = forms.ModelMultipleChoiceField(diff --git a/saleor/dashboard/product/urls.py b/saleor/dashboard/product/urls.pyindex 92f82bf718..61830bde14 100644--- a/saleor/dashboard/product/urls.py+++ b/saleor/dashboard/product/urls.py@@ -40,18 +40,6 @@ urlpatterns = [url(r'^(?P<product_pk>[0-9]+)/variants/(?P<variant_pk>[0-9]+)/images/$',views.variant_images, name='variant-images'),- url(r'^(?P<product_pk>[0-9]+)/variants/(?P<variant_pk>[0-9]+)/stock/add/$',- views.stock_add, name='variant-stock-add'),- url(r'^(?P<product_pk>[0-9]+)/variants/(?P<variant_pk>[0-9]+)/stock/'- r'(?P<stock_pk>[0-9]+)/$',- views.stock_details, name='variant-stock-details'),- url(r'^(?P<product_pk>[0-9]+)/variants/(?P<variant_pk>[0-9]+)/stock/'- r'(?P<stock_pk>[0-9]+)/update/$',- views.stock_edit, name='variant-stock-update'),- url(r'^(?P<product_pk>[0-9]+)/variants/(?P<variant_pk>[0-9]+)/stock/'- r'(?P<stock_pk>[0-9]+)/delete/$',- views.stock_delete, name='variant-stock-delete'),-url(r'^(?P<product_pk>[0-9]+)/images/$', views.product_images,name='product-image-list'),url(r'^(?P<product_pk>[0-9]+)/images/add/$',diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex f47fb42a10..4900529998 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -191,13 +191,12 @@ def product_detail(request, pk):# management.no_variants = not product.product_type.has_variantsonly_variant = variants.first() if no_variants else None- stock = only_variant.stock.all() if only_variant else Stock.objects.none()ctx = {'product': product, 'sale_price': sale_price, 'variants': variants,'gross_price_range': gross_price_range, 'images': images,'no_variants': no_variants, 'only_variant': only_variant,- 'stock': stock, 'purchase_cost': purchase_cost,- 'gross_margin': gross_margin, 'is_empty': not variants.exists()}+ 'purchase_cost': purchase_cost, 'gross_margin': gross_margin,+ 'is_empty': not variants.exists()}return TemplateResponse(request, 'dashboard/product/detail.html', ctx)@@ -259,79 +258,6 @@ def product_delete(request, pk):{'product': product})-@staff_member_required-@permission_required('product.view_stock')-def stock_details(request, product_pk, variant_pk, stock_pk):- product = get_object_or_404(Product, pk=product_pk)- variant = get_object_or_404(product.variants, pk=variant_pk)- stock = get_object_or_404(variant.stock, pk=stock_pk)- ctx = {'stock': stock, 'product': product, 'variant': variant}- return TemplateResponse(- request,- 'dashboard/product/stock/detail.html',- ctx)---@staff_member_required-@permission_required('product.edit_stock')-def stock_add(request, product_pk, variant_pk):- product = get_object_or_404(Product, pk=product_pk)- variant = get_object_or_404(product.variants, pk=variant_pk)- stock = Stock()- form = forms.StockForm(- request.POST or None, instance=stock, variant=variant)- if form.is_valid():- form.save()- msg = pgettext_lazy('Dashboard message', 'Saved stock')- messages.success(request, msg)- return redirect(- 'dashboard:variant-details', product_pk=product.pk,- variant_pk=variant.pk)- ctx = {- 'form': form, 'product': product, 'variant': variant, 'stock': stock}- return TemplateResponse(request, 'dashboard/product/stock/form.html', ctx)---@staff_member_required-@permission_required('product.edit_stock')-def stock_edit(request, product_pk, variant_pk, stock_pk):- product = get_object_or_404(Product, pk=product_pk)- variant = get_object_or_404(product.variants, pk=variant_pk)- stock = get_object_or_404(variant.stock, pk=stock_pk)- form = forms.StockForm(- request.POST or None, instance=stock, variant=variant)- if form.is_valid():- form.save()- msg = pgettext_lazy('Dashboard message', 'Saved stock')- messages.success(request, msg)- return redirect(- 'dashboard:variant-details', product_pk=product.pk,- variant_pk=variant.pk)- ctx = {- 'form': form, 'product': product, 'variant': variant, 'stock': stock}- return TemplateResponse(request, 'dashboard/product/stock/form.html', ctx)---@staff_member_required-@permission_required('product.edit_stock')-def stock_delete(request, product_pk, variant_pk, stock_pk):- product = get_object_or_404(Product, pk=product_pk)- variant = get_object_or_404(product.variants, pk=variant_pk)- stock = get_object_or_404(Stock, pk=stock_pk)- if request.method == 'POST':- stock.delete()- msg = pgettext_lazy('Dashboard message', 'Removed stock')- messages.success(request, msg)- return redirect(- 'dashboard:variant-details', product_pk=product.pk,- variant_pk=variant.pk)- ctx = {'product': product, 'stock': stock, 'variant': variant}- return TemplateResponse(- request,- 'dashboard/product/stock/modal/confirm_delete.html',- ctx)--@staff_member_required@permission_required('product.view_product')def product_images(request, product_pk):diff --git a/saleor/dashboard/views.py b/saleor/dashboard/views.pyindex 021661f19b..f6fdb67446 100644--- a/saleor/dashboard/views.py+++ b/saleor/dashboard/views.py@@ -53,5 +53,5 @@ def styleguide(request):def get_low_stock_products():threshold = getattr(settings, 'LOW_STOCK_THRESHOLD', 10)products = Product.objects.annotate(- total_stock=Sum('variants__stock__quantity'))+ total_stock=Sum('variants__quantity'))return products.filter(Q(total_stock__lte=threshold)).distinct()diff --git a/saleor/data_feeds/google_merchant.py b/saleor/data_feeds/google_merchant.pyindex 4a4cc96553..15c68ba492 100644--- a/saleor/data_feeds/google_merchant.py+++ b/saleor/data_feeds/google_merchant.py@@ -122,7 +122,7 @@ def item_image_link(item, current_site):def item_availability(item):- if item.get_stock_quantity():+ if item.quantity_available:return 'in stock'return 'out of stock'diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.pyindex a195652312..854457d1f8 100644--- a/saleor/graphql/product/types.py+++ b/saleor/graphql/product/types.py@@ -52,7 +52,7 @@ class ProductVariant(CountableDjangoObjectType):model = models.ProductVariantdef resolve_stock_quantity(self, info):- return self.get_stock_quantity()+ return self.quantity_availabledef resolve_attributes(self, info):return resolve_attribute_list(self.attributes)diff --git a/saleor/order/models.py b/saleor/order/models.pyindex b69545a068..d102410f72 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -17,7 +17,7 @@ from . import FulfillmentStatus, OrderStatusfrom ..account.models import Addressfrom ..core.utils import ZERO_TAXED_MONEY, build_absolute_urifrom ..discount.models import Voucher-from ..product.models import Product+from ..product.models import Product, ProductVariantfrom ..shipping.models import ShippingMethodCountry@@ -180,11 +180,11 @@ class OrderLine(models.Model):product = models.ForeignKey(Product, blank=True, null=True, related_name='+',on_delete=models.SET_NULL)+ variant = models.ForeignKey(+ ProductVariant, related_name='stock', on_delete=models.CASCADE)product_name = models.CharField(max_length=128)product_sku = models.CharField(max_length=32)is_shipping_required = models.BooleanField()- stock = models.ForeignKey(- 'product.Stock', on_delete=models.SET_NULL, null=True)quantity = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(999)])quantity_fulfilled = models.IntegerField(diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 6f3346d79a..bd33390248 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -144,12 +144,12 @@ def add_variant_to_order(order, variant, total_quantity) if add_to_existing else total_quantityprice = variant.get_price_per_item(discounts)while quantity_left > 0:- stock = variant.select_stockrecord()- if not stock:+ quantity_available = variant.quantity_available()+ if not quantity_available:raise InsufficientStock(variant)quantity = (- stock.quantity_available- if quantity_left > stock.quantity_available+ quantity_available+ if quantity_left > quantity_availableelse quantity_left)order.lines.create(@@ -160,7 +160,7 @@ def add_variant_to_order(variant.product.product_type.is_shipping_required),quantity=quantity,unit_price=price,- stock=stock)+ variant=variant)allocate_stock(variant, quantity)# refresh stock for accessing quantity_allocatedvariant.refresh_from_db()diff --git a/saleor/product/models.py b/saleor/product/models.pyindex bd641e2c6e..134e6070e0 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -186,6 +186,13 @@ class ProductVariant(models.Model):Product, related_name='variants', on_delete=models.CASCADE)attributes = HStoreField(default={}, blank=True)images = models.ManyToManyField('ProductImage', through='VariantImage')+ quantity = models.IntegerField(+ validators=[MinValueValidator(0)], default=Decimal(1))+ quantity_allocated = models.IntegerField(+ validators=[MinValueValidator(0)], default=Decimal(0))+ cost_price = MoneyField(+ currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,+ blank=True, null=True)class Meta:app_label = 'product'@@ -193,14 +200,18 @@ class ProductVariant(models.Model):def __str__(self):return self.name+ @property+ def quantity_available(self):+ return max(self.quantity - self.quantity_allocated, 0)++ def get_total(self):+ if self.cost_price:+ return TaxedMoney(net=self.cost_price, gross=self.cost_price)+def check_quantity(self, quantity):- total_available_quantity = self.get_stock_quantity()- if quantity > total_available_quantity:+ if quantity > self.quantity_available:raise InsufficientStock(self)- def get_stock_quantity(self):- return sum([stock.quantity_available for stock in self.stock.all()])-def get_price_per_item(self, discounts=None):price = self.price_override or self.product.priceprice = TaxedMoney(net=price, gross=price)@@ -224,8 +235,7 @@ class ProductVariant(models.Model):return self.product.product_type.is_shipping_requireddef is_in_stock(self):- return any(- [stock.quantity_available > 0 for stock in self.stock.all()])+ return self.quantity_available > 0def display_product(self):variant_display = str(self)@@ -237,52 +247,6 @@ class ProductVariant(models.Model):def get_first_image(self):return self.product.get_first_image()- def select_stockrecord(self, quantity=1):- # By default selects stock with lowest cost price. If stock cost price- # is None we assume price equal to zero to allow sorting.- stock = [- stock_item for stock_item in self.stock.all()- if stock_item.quantity_available >= quantity]- zero_price = Money(0, settings.DEFAULT_CURRENCY)- stock = sorted(- stock, key=(lambda s: s.cost_price or zero_price), reverse=False)- if stock:- return stock[0]- return None-- def get_cost_price(self):- stock = self.select_stockrecord()- if stock:- return stock.cost_price- return None---class Stock(models.Model):- variant = models.ForeignKey(- ProductVariant, related_name='stock', on_delete=models.CASCADE)- quantity = models.IntegerField(- validators=[MinValueValidator(0)], default=Decimal(1))- quantity_allocated = models.IntegerField(- validators=[MinValueValidator(0)], default=Decimal(0))- cost_price = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,- blank=True, null=True)-- class Meta:- app_label = 'product'- unique_together = ('variant', 'location')-- def __str__(self):- return '%s - %s' % (self.variant.name, self.location)-- @property- def quantity_available(self):- return max(self.quantity - self.quantity_allocated, 0)-- def get_total(self):- if self.cost_price:- return TaxedMoney(net=self.cost_price, gross=self.cost_price)-class ProductAttribute(models.Model):slug = models.SlugField(max_length=50, unique=True)diff --git a/templates/dashboard/order/modal/order_line_stock.html b/templates/dashboard/order/modal/order_line_stock.htmldeleted file mode 100644index 6d07d2b021..0000000000--- a/templates/dashboard/order/modal/order_line_stock.html+++ /dev/null@@ -1,20 +0,0 @@-{% extends "dashboard/base_modal.html" %}--{% load i18n %}-{% load materializecss %}--{% block action_url %}-{% url 'dashboard:orderline-change-stock' order_pk=order_pk line_pk=line_pk %}-{% endblock %}--{% block title %}-{% trans "Change stock" context "Modal change stock title" %}-{% endblock %}--{% block content %}-{{ form|materializecss:"s12 m6" }}-{% endblock %}--{% block primary_action %}-{% trans "Change" context "Modal change stock primary action" %}-{% endblock %}diff --git a/tests/conftest.py b/tests/conftest.pyindex 48b3ba0497..124330f0e4 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -26,7 +26,7 @@ from saleor.order.utils import recalculate_orderfrom saleor.page.models import Pagefrom saleor.product.models import (AttributeChoiceValue, Category, Collection, Product, ProductAttribute,- ProductImage, ProductType, ProductVariant, Stock)+ ProductImage, ProductType, ProductVariant)from saleor.shipping.models import ShippingMethodfrom saleor.site.models import AuthorizationKey, SiteSettings@@ -380,7 +380,9 @@ def order_with_lines(order, product_type, default_category, shipping_method):product = Product.objects.create(name='Test product', price=Money('10.00', 'USD'),product_type=product_type, category=default_category)- variant = ProductVariant.objects.create(product=product, sku='SKU_A')+ variant = ProductVariant.objects.create(+ product=product, sku='SKU_A', cost_price=Money(1, 'USD'), quantity=5,+ quantity_allocated=3)order.lines.create(product=product,product_name=product.name,@@ -388,11 +390,14 @@ def order_with_lines(order, product_type, default_category, shipping_method):is_shipping_required=product.product_type.is_shipping_required,quantity=3,unit_price_net=Decimal('30.00'),- unit_price_gross=Decimal('30.00'))+ unit_price_gross=Decimal('30.00'),+ variant=variant)product = Product.objects.create(name='Test product 2', price=Money('20.00', 'USD'),product_type=product_type, category=default_category)- variant = ProductVariant.objects.create(product=product, sku='SKU_B')+ variant = ProductVariant.objects.create(+ product=product, sku='SKU_B', cost_price=Money(2, 'USD'), quantity=2,+ quantity_allocated=2)order.lines.create(product=product,product_name=product.name,@@ -400,7 +405,8 @@ def order_with_lines(order, product_type, default_category, shipping_method):is_shipping_required=product.product_type.is_shipping_required,quantity=2,unit_price_net=Decimal('20.00'),- unit_price_gross=Decimal('20.00'))+ unit_price_gross=Decimal('20.00'),+ variant=variant)order.shipping_address = order.billing_address.get_copy()order.shipping_method_name = shipping_method.namediff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.pyindex abacfb598e..3462086500 100644--- a/tests/dashboard/test_order.py+++ b/tests/dashboard/test_order.py@@ -1,4 +1,3 @@-from decimal import Decimalfrom unittest.mock import patchimport pytest@@ -19,7 +18,7 @@ from saleor.order.models import Order, OrderLine, OrderNotefrom saleor.order.utils import (add_variant_to_existing_lines, add_variant_to_order,change_order_line_quantity)-from saleor.product.models import ProductVariant, Stock+from saleor.product.models import ProductVariant@pytest.mark.integration@@ -427,7 +426,8 @@ def test_view_cancel_order_line(admin_client, draft_order):lines_after = Order.objects.get().lines.all()assert lines_before_count - 1 == lines_after.count()# check stock deallocation- assert Stock.objects.first().quantity_allocated == (+ line.refresh_from_db()+ assert line.quantity_allocated == (quantity_allocated_before - line_quantity)url = reverse('dashboard:orderline-cancel', kwargs={@@ -466,7 +466,7 @@ def test_view_change_order_line_quantity(admin_client, draft_order):# order should have the same linesassert lines_before_quantity_change_count == lines_after.count()# stock allocation should be 2 now- assert Stock.objects.first().quantity_allocated == 2+ assert line.quantity_allocated == 2line.refresh_from_db()# source line quantity should be decreased to 2assert line.quantity == 2@@ -593,98 +593,9 @@ def test_view_fulfillment_packing_slips_without_shipping(assert response['content-type'] == 'application/pdf'-def test_view_change_order_line_stock_valid(admin_client, draft_order):- line = draft_order.lines.last()- old_stock = line.stock- variant = ProductVariant.objects.get(sku=line.product_sku)- stock = Stock.objects.create(- variant=variant, cost_price=2, quantity=2, quantity_allocated=0)-- url = reverse(- 'dashboard:orderline-change-stock', kwargs={- 'order_pk': draft_order.pk,- 'line_pk': line.pk})- data = {'stock': stock.pk}- response = admin_client.post(url, data)-- assert response.status_code == 200-- line.refresh_from_db()- assert line.stock == stock- assert line.stock.quantity_allocated == 2-- old_stock.refresh_from_db()- assert old_stock.quantity_allocated == 0---def test_view_change_order_line_stock_insufficient_stock(- admin_client, draft_order):- line = draft_order.lines.last()- old_stock = line.stock- variant = ProductVariant.objects.get(sku=line.product_sku)- stock = Stock.objects.create(- variant=variant, cost_price=2, quantity=2, quantity_allocated=1)-- url = reverse(- 'dashboard:orderline-change-stock', kwargs={- 'order_pk': draft_order.pk,- 'line_pk': line.pk})- data = {'stock': stock.pk}- response = admin_client.post(url, data)-- assert response.status_code == 400-- line.refresh_from_db()- assert line.stock == old_stock-- old_stock.refresh_from_db()- assert old_stock.quantity_allocated == 2-- stock.refresh_from_db()- assert stock.quantity_allocated == 1---def test_view_change_order_line_stock_merges_lines(admin_client, draft_order):- line = draft_order.lines.first()- old_stock = line.stock- variant = ProductVariant.objects.get(sku=line.product_sku)- line_2 = draft_order.lines.create(- variant=variant,- cost_price=2,- quantity=2,- quantity_allocated=2,- product=line.product,- product_name=line.product.name,- product_sku='SKU_A',- is_shipping_required=line.is_shipping_required,- unit_price_net=Decimal('30.00'),- unit_price_gross=Decimal('30.00'))- lines_before = draft_order.lines.count()-- url = reverse(- 'dashboard:orderline-change-stock', kwargs={- 'order_pk': draft_order.pk,- 'line_pk': line_2.pk})- data = {'stock': old_stock.pk}- response = admin_client.post(url, data)-- assert response.status_code == 200- assert draft_order.lines.count() == lines_before - 1-- old_stock.refresh_from_db()- assert old_stock.quantity_allocated == 5-- stock.refresh_from_db()- assert stock.quantity_allocated == 0--def test_add_variant_to_existing_lines_one_line(- order_with_variant_from_different_stocks):- order = order_with_variant_from_different_stocks+ order_with_lines_and_stock):+ order = order_with_lines_and_stocklines = order.lines.filter(product_sku='SKU_A')variant_lines_before = lines.count()line = lines.first()@@ -700,8 +611,8 @@ def test_add_variant_to_existing_lines_one_line(def test_add_variant_to_existing_lines_multiple_lines(- order_with_variant_from_different_stocks):- order = order_with_variant_from_different_stocks+ order_with_lines_and_stock):+ order = order_with_lines_and_stocklines = order.lines.filter(product_sku='SKU_A').all()variant_lines_before = lines.count()line_1 = lines[0]@@ -720,8 +631,8 @@ def test_add_variant_to_existing_lines_multiple_lines(def test_add_variant_to_existing_lines_multiple_lines_with_rest(- order_with_variant_from_different_stocks):- order = order_with_variant_from_different_stocks+ order_with_lines_and_stock):+ order = order_with_lines_and_stocklines = order.lines.filter(product_sku='SKU_A').all()variant_lines_before = lines.count()line_1 = lines[0]@@ -740,10 +651,9 @@ def test_add_variant_to_existing_lines_multiple_lines_with_rest(def test_view_add_variant_to_order(- admin_client, order_with_variant_from_different_stocks):- order = order_with_variant_from_different_stocks+ admin_client, order_with_lines_and_stock):order.status = OrderStatus.DRAFT- order.save()+ order = order_with_lines_and_stockvariant = ProductVariant.objects.get(sku='SKU_A')line = OrderLine.objects.get(product_sku='SKU_A')url = reverse(diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.pyindex 4a5f464799..cc78901a4d 100644--- a/tests/dashboard/test_product.py+++ b/tests/dashboard/test_product.py@@ -2,7 +2,6 @@ import jsonfrom io import BytesIOfrom unittest.mock import MagicMock, Mock, patch-import pytestfrom django.conf import settingsfrom django.core.files.uploadedfile import SimpleUploadedFilefrom django.forms import HiddenInput@@ -45,28 +44,6 @@ def test_product_variant_form(product_in_stock):assert variant.name == example_size-def test_stock_record_update_works(admin_client, product):- variant = product.variants.get()- stock = variant.stock.order_by('-quantity_allocated').first()- quantity = stock.quantity- quantity_allocated = stock.quantity_allocated- url = reverse(- 'dashboard:variant-stock-update',- kwargs={- 'product_pk': product.pk,- 'variant_pk': variant.pk,- 'stock_pk': stock.pk})- admin_client.post(url, {- 'variant': stock.variant_id, 'location': stock.location.id,- 'cost_price': stock.cost_price.amount,- 'quantity': quantity + 5})- new_stock = variant.stock.get(pk=stock.pk)- assert new_stock.quantity == quantity + 5- assert new_stock.quantity_allocated == quantity_allocated--def test_valid_product_type_form(color_attribute, size_attribute):data = {'name': "Testing Type",@@ -355,35 +332,6 @@ def test_view_product_variant_delete(admin_client, product):assert not ProductVariant.objects.filter(pk=product_variant_pk)-def test_view_stock_not_deleted_before_confirmation(- admin_client, product):- product_variant = product.variants.first()- stock = Stock.objects.filter(variant=product_variant).first()- url = reverse(- 'dashboard:variant-stock-delete',- kwargs={- 'product_pk': product.pk,- 'variant_pk': product_variant.pk,- 'stock_pk': stock.pk})- response = admin_client.get(url)- assert response.status_code == HTTP_STATUS_OK- assert Stock.objects.filter(pk=stock.pk)---def test_view_stock_delete(admin_client, product):- product_variant = product.variants.first()- stock = Stock.objects.filter(variant=product_variant).first()- url = reverse(- 'dashboard:variant-stock-delete',- kwargs={- 'product_pk': product.pk,- 'variant_pk': product_variant.pk,- 'stock_pk': stock.pk})- response = admin_client.post(url)- assert response.status_code == HTTP_REDIRECTION- assert not Stock.objects.filter(pk=stock.pk)--def test_view_attribute_not_deleted_before_confirmation(admin_client, color_attribute):url = reverse(diff --git a/tests/test_order.py b/tests/test_order.pyindex 8b5252fafd..36a1cbb4dc 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -54,13 +54,12 @@ def test_add_variant_to_order_allocates_stock_for_new_variant(order_with_lines, product):order = order_with_linesvariant = product.variants.get()- stock = variant.select_stockrecord()- stock_before = stock.quantity_allocated+ stock_before = variant.quantity_allocatedadd_variant_to_order(order, variant, 1)- stock.refresh_from_db()- assert stock.quantity_allocated == stock_before + 1+ variant.refresh_from_db()+ assert variant.quantity_allocated == stock_before + 1def test_add_variant_to_order_edits_line_for_existing_variant(diff --git a/tests/test_product.py b/tests/test_product.pyindex c110cac55b..5ebf011aa0 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -16,46 +16,23 @@ from saleor.product.utils.variants_picker import get_variant_picker_datafrom .utils import filter_products_by_attribute-def test_allocate_stock(product):- variant = product.variants.get()- stock = variant.select_stockrecord(5)- assert stock.quantity_allocated == 0- allocate_stock(stock, 1)- stock.refresh_from_db()- assert stock.quantity_allocated == 1---def test_deallocate_stock(product):- stock = product.variants.first().stock.first()- stock.quantity = 100- stock.quantity_allocated = 80- stock.save()- deallocate_stock(stock, 50)- stock.refresh_from_db()- assert stock.quantity == 100- assert stock.quantity_allocated == 30---def test_decrease_stock(product):- stock = product.variants.first().stock.first()- stock.quantity = 100- stock.quantity_allocated = 80- stock.save()- decrease_stock(stock, 50)- stock.refresh_from_db()- assert stock.quantity == 50- assert stock.quantity_allocated == 30---def test_increase_stock(product):- stock = product.variants.first().stock.first()- stock.quantity = 100- stock.quantity_allocated = 80- stock.save()- increase_stock(stock, 50)- stock.refresh_from_db()- assert stock.quantity == 150- assert stock.quantity_allocated == 80+ 'func, expected_quanitty, expected_quant_allocated',+ (+ (increase_stock, 150, 80),+ (decrease_stock, 50, 30),+ (deallocate_stock, 100, 30),+ (allocate_stock, 10, 1)))+def test_stock_utils(+ product, func, expected_quanitty, expected_quant_allocated):+ variant = product.variants.first()+ variant.quantity = 100+ variant.quantity_allocated = 80+ variant.save()+ func(variant, 50)+ variant.refresh_from_db()+ assert variant.quantity == expected_quanitty+ assert variant.quantity_allocated == expected_quant_allocateddef test_product_page_redirects_to_correct_slug(client, product):