Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix order weight mechanism

Aleksander Spyra272f244b232c
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index dd4b7efe86..b18c5b48e9 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -16,7 +16,7 @@ from ...order import OrderStatus
from ...order.models import Fulfillment, FulfillmentLine, Order, OrderLine
from ...order.utils import (
add_variant_to_order, cancel_fulfillment, cancel_order,
- change_order_line_quantity, recalculate_order)
+ change_order_line_quantity, delete_order_line, recalculate_order)
from ...payment import ChargeStatus, CustomPaymentChoices, PaymentError
from ...payment.utils import (
clean_mark_order_as_paid, gateway_capture, gateway_refund, gateway_void,
@@ -362,11 +362,12 @@ class CancelOrderLineForm(forms.Form):
super().__init__(*args, **kwargs)
def cancel_line(self):
- if self.line.variant and self.line.variant.track_inventory:
- deallocate_stock(self.line.variant, self.line.quantity)
- order = self.line.order
- self.line.delete()
- recalculate_order(order)
+ if self.line.variant:
+ if self.line.variant.track_inventory:
+ deallocate_stock(self.line.variant, self.line.quantity)
+ order = self.line.order
+ delete_order_line(self.line)
+ recalculate_order(order)
class ChangeQuantityForm(forms.ModelForm):
@@ -401,12 +402,13 @@ class ChangeQuantityForm(forms.ModelForm):
def save(self):
quantity = self.cleaned_data['quantity']
variant = self.instance.variant
- if variant and variant.track_inventory:
- # update stock allocation
- delta = quantity - self.initial_quantity
- allocate_stock(variant, delta)
- change_order_line_quantity(self.instance, quantity)
- recalculate_order(self.instance.order)
+ if variant:
+ if variant.track_inventory:
+ # update stock allocation
+ delta = quantity - self.initial_quantity
+ allocate_stock(variant, delta)
+ change_order_line_quantity(self.instance, quantity)
+ recalculate_order(self.instance.order)
return self.instance
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index a4d2864e30..2f0ddb3c27 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -9,7 +9,8 @@ from ....core.exceptions import InsufficientStock
from ....core.utils.taxes import ZERO_TAXED_MONEY
from ....order import OrderEvents, OrderStatus, models
from ....order.utils import (
- add_variant_to_order, allocate_stock, recalculate_order)
+ add_variant_to_order, allocate_stock,
+ change_order_line_quantity, delete_order_line, recalculate_order)
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
@@ -286,9 +287,12 @@ class DraftOrderLineDelete(BaseMutation):
if order.status != OrderStatus.DRAFT:
cls.add_error(
errors, 'id', 'Only draft orders can be edited.')
+ if not line.variant:
+ cls.add_error(
+ errors, None, 'Order line without variant can not be deleted.')
if not errors:
db_id = line.id
- line.delete()
+ delete_order_line(line)
line.id = db_id
recalculate_order(order)
return DraftOrderLineDelete(
@@ -325,11 +329,15 @@ class DraftOrderLineUpdate(ModelMutation):
cls.add_error(
errors, 'quantity',
'Ensure this value is greater than or equal to 1.')
+
+ if not instance.variant:
+ cls.add_error(
+ errors, None, 'Order line without variant can not be edited')
return cleaned_input
@classmethod
def save(cls, info, instance, cleaned_input):
- instance.save(update_fields=['quantity'])
+ change_order_line_quantity(instance, instance.quantity)
recalculate_order(instance.order)
@classmethod
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 9bf5aef4f4..dc49c549a3 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -7,6 +7,8 @@ def can_finalize_draft_order(order, errors):
Checks, if given order has a proper customer data, shipping
address and method set up and return list of errors if not.
+ Checks if product variants for order lines still exists in
+ database, too.
"""
if order.get_total_quantity() == 0:
errors.append(
@@ -25,6 +27,13 @@ def can_finalize_draft_order(order, errors):
field='shipping',
message='Shipping method is not valid for chosen shipping '
'address'))
+ line_variants = [line.variant for line in order]
+ if None in line_variants:
+ errors.append(
+ Error(
+ field='lines',
+ message='Could not create orders with non-existing products.'))
+
return errors
diff --git a/saleor/order/models.py b/saleor/order/models.py
index b62bbdc6c3..8b98f1f33d 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -274,11 +274,7 @@ class Order(models.Model):
return self.total_captured - self.total.gross
def get_total_weight(self):
- # Cannot use `sum` as it parses an empty Weight to an int
- weights = Weight(kg=0)
- for line in self:
- weights += line.variant.get_weight() * line.quantity
- return weights
+ return self.weight
class OrderLine(models.Model):
@@ -315,6 +311,16 @@ class OrderLine(models.Model):
def __str__(self):
return self.product_name
+ def save(self, *args, **kwargs):
+ print(kwargs)
+ if not self.pk:
+ if ('order' in kwargs and 'variant' in kwargs
+ and 'quantity' in kwargs):
+ order = kwargs['order']
+ order.weight += kwargs['variant'].get_weight() * kwargs['quantity']
+ order.save()
+ super().save(*args, **kwargs)
+
def get_total(self):
return self.unit_price * self.quantity
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 08f857e157..6d407184eb 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,6 +1,7 @@
from functools import wraps
from django.conf import settings
+from django.db import transaction
from django.shortcuts import get_object_or_404, redirect
from prices import Money, TaxedMoney
@@ -163,8 +164,13 @@ def attach_order_to_user(order, user):
def add_variant_to_order(
- order, variant, quantity, discounts=None, taxes=None,
- allow_overselling=False, track_inventory=True):
+ order,
+ variant,
+ quantity,
+ discounts=None,
+ taxes=None,
+ allow_overselling=False,
+ track_inventory=True):
"""Add total_quantity of variant to order.
Returns an order line the variant was added to.
@@ -177,7 +183,10 @@ def add_variant_to_order(
try:
line = order.lines.get(variant=variant)
line.quantity += quantity
- line.save(update_fields=['quantity'])
+ order.weight += variant.get_weight() * quantity
+ with transaction.atomic():
+ line.save(update_fields=['quantity'])
+ order.save(update_fields=['weight'])
except OrderLine.DoesNotExist:
product_name = variant.display_product()
translated_product_name = variant.display_product(translated=True)
@@ -192,6 +201,7 @@ def add_variant_to_order(
variant=variant,
unit_price=variant.get_price(discounts, taxes),
tax_rate=get_tax_rate_by_name(variant.product.tax_rate, taxes))
+
if variant.track_inventory and track_inventory:
allocate_stock(variant, quantity)
return line
@@ -200,10 +210,27 @@ def add_variant_to_order(
def change_order_line_quantity(line, new_quantity):
"""Change the quantity of ordered items in a order line."""
if new_quantity:
+ old_quantity = OrderLine.objects.get(pk=line.pk).quantity
+ order = line.order
+ variant_weight = line.variant.get_weight()
line.quantity = new_quantity
- line.save(update_fields=['quantity'])
+ order.weight += (
+ new_quantity * variant_weight - old_quantity * variant_weight)
+ with transaction.atomic():
+ line.save(update_fields=['quantity'])
+ order.save(update_fields=['weight'])
else:
+ delete_order_line(line)
+
+
+def delete_order_line(line):
+ """Delete order line from order"""
+ order = line.order
+ quantity = line.quantity
+ order.weight -= quantity * line.variant.get_weight()
+ with transaction.atomic():
line.delete()
+ order.save(update_fields=['weight'])
def restock_order_lines(order):
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index 876c47885c..cd101dd94d 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -416,6 +416,21 @@ def test_can_finalize_draft_order_no_order_lines(order):
assert errors[0].message == 'Could not create order without any products.'
+def test_can_finalize_draft_order_non_existing_variant(order_with_lines):
+ order = order_with_lines
+ line = order.lines.first()
+ variant = line.variant
+ variant.delete()
+ line.refresh_from_db()
+ assert line.variant is None
+
+ order.refresh_from_db()
+ errors = can_finalize_draft_order(order, [])
+ assert (
+ errors[0].message ==
+ 'Could not create orders with non-existing products.')
+
+
def test_draft_order_complete(
staff_api_client, permission_manage_orders, staff_user, draft_order):
order = draft_order
@@ -658,6 +673,22 @@ def test_draft_order_line_update(
assert data['errors'][0]['field'] == 'quantity'
+def test_draft_order_update_with_non_existing_product(
+ draft_order, staff_api_client, permission_manage_orders):
+ query = DRAFT_ORDER_LINE_UPDATE_MUTATION
+ order = draft_order
+ line = order.lines.first()
+ variant = line.variant
+ variant.delete()
+ line_id = graphene.Node.to_global_id('OrderLine', line.id)
+ variables = {'lineId': line_id, 'quantity': 2}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders])
+ content = get_graphql_content(response)
+ data = content['data']['draftOrderLineUpdate']
+ assert data['errors']
+
+
def test_require_draft_order_when_updating_lines(
order_with_lines, staff_api_client, permission_manage_orders):
query = DRAFT_ORDER_LINE_UPDATE_MUTATION
@@ -720,6 +751,22 @@ def test_require_draft_order_when_removing_lines(
assert data['errors']
+def test_draft_order_remove_with_non_existing_product(
+ draft_order, staff_api_client, permission_manage_orders):
+ query = DRAFT_ORDER_LINE_DELETE_MUTATION
+ order = draft_order
+ line = order.lines.first()
+ variant = line.variant
+ variant.delete()
+ line_id = graphene.Node.to_global_id('OrderLine', line.id)
+ variables = {'id': line_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders])
+ content = get_graphql_content(response)
+ data = content['data']['draftOrderLineDelete']
+ assert data['errors']
+
+
def test_order_update(
staff_api_client, permission_manage_orders, order_with_lines,
graphql_address_data):
@@ -1119,10 +1166,9 @@ def test_clean_order_void_payment():
payment.is_active = True
error_msg = 'error has happened.'
- with patch(
- 'saleor.graphql.order.mutations.orders.gateway_void',
- side_effect=ValueError(error_msg)):
- errors = clean_void_payment(payment, [])
+ with patch('saleor.graphql.order.mutations.orders.gateway_void',
+ side_effect=ValueError(error_msg)):
+ errors = clean_void_payment(payment, [])
assert errors[0].field == 'payment'
assert errors[0].message == error_msg
diff --git a/tests/test_order.py b/tests/test_order.py
index a21ae379bc..57b36562eb 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -3,6 +3,7 @@ from decimal import Decimal
import pytest
from django.urls import reverse
from django_countries.fields import Country
+from measurement.measures import Weight
from prices import Money, TaxedMoney
from saleor.account.models import User
@@ -13,7 +14,8 @@ from saleor.core.utils.taxes import (
from saleor.order import FulfillmentStatus, OrderStatus, models
from saleor.order.models import Order
from saleor.order.utils import (
- add_variant_to_order, cancel_fulfillment, cancel_order, recalculate_order,
+ add_variant_to_order, cancel_fulfillment, cancel_order,
+ change_order_line_quantity, delete_order_line, recalculate_order,
restock_fulfillment_lines, restock_order_lines, update_order_prices,
update_order_status)
from saleor.payment import ChargeStatus
@@ -515,3 +517,70 @@ def test_add_order_note_view(order, authorized_client, customer_user):
assert get_redirect_location(response) == redirect_url
order.refresh_from_db()
assert order.customer_note == customer_note
+
+
+def _calculate_order_weight_from_lines(order):
+ weight = Weight(kg=0)
+ for line in order:
+ weight += line.variant.get_weight() * line.quantity
+ return weight
+
+
+def test_order_weight(order_with_lines):
+ order_weight = order_with_lines.weight
+ calculated_weight = _calculate_order_weight_from_lines(order_with_lines)
+
+ assert calculated_weight == order_weight
+
+
+def test_order_weight_add_more_variant(order_with_lines):
+ variant = order_with_lines.lines.first().variant
+
+ add_variant_to_order(order_with_lines, variant, 2)
+ order_with_lines.refresh_from_db()
+
+ assert order_with_lines.weight == _calculate_order_weight_from_lines(
+ order_with_lines)
+
+
+def test_order_weight_add_new_variant(order_with_lines, product):
+ variant = product.variants.first()
+
+ add_variant_to_order(order_with_lines, variant, 2)
+ order_with_lines.refresh_from_db()
+
+ assert order_with_lines.weight == _calculate_order_weight_from_lines(
+ order_with_lines)
+
+
+def test_order_weight_change_line_quantity(order_with_lines):
+ line = order_with_lines.lines.first()
+ new_quantity = line.quantity + 2
+ change_order_line_quantity(line, new_quantity)
+ order_with_lines.refresh_from_db()
+
+ assert order_with_lines.weight == _calculate_order_weight_from_lines(
+ order_with_lines)
+
+
+def test_order_weight_delete_line(order_with_lines):
+ line = order_with_lines.lines.first()
+ delete_order_line(line)
+
+ assert order_with_lines.weight == _calculate_order_weight_from_lines(
+ order_with_lines)
+
+
+def test_get_order_weight_non_existing_product(order_with_lines, product):
+ # Removing product should not affect order's weight
+ order = order_with_lines
+ variant = product.variants.first()
+ add_variant_to_order(order, variant, 1)
+ old_weight = order.get_total_weight()
+
+ product.delete()
+
+ order.refresh_from_db()
+ new_weight = order.get_total_weight()
+
+ assert old_weight == new_weight