Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor code. Order weight is calculated by iterating lines where it is possible
Aleksander Spyrada1fb1c4808f
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex b18c5b48e9..dcf33a5b22 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -362,12 +362,11 @@ class CancelOrderLineForm(forms.Form):super().__init__(*args, **kwargs)def cancel_line(self):- 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)+ if self.line.variant and 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):@@ -402,13 +401,12 @@ class ChangeQuantityForm(forms.ModelForm):def save(self):quantity = self.cleaned_data['quantity']variant = self.instance.variant- 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)+ 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)return self.instancediff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 2f0ddb3c27..2f01f739cd 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -9,8 +9,8 @@ from ....core.exceptions import InsufficientStockfrom ....core.utils.taxes import ZERO_TAXED_MONEYfrom ....order import OrderEvents, OrderStatus, modelsfrom ....order.utils import (- add_variant_to_order, allocate_stock,- change_order_line_quantity, delete_order_line, recalculate_order)+ add_variant_to_order, allocate_stock, change_order_line_quantity,+ delete_order_line, recalculate_order)from ...account.i18n import I18nMixinfrom ...account.types import AddressInputfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation@@ -287,9 +287,6 @@ 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.iddelete_order_line(line)@@ -330,9 +327,6 @@ class DraftOrderLineUpdate(ModelMutation):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@classmethoddiff --git a/saleor/order/models.py b/saleor/order/models.pyindex 51e3b80ff3..28e73a2e92 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -311,16 +311,6 @@ class OrderLine(models.Model):def __str__(self):return self.product_name- def save(self, *args, **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.quantitydiff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 6d407184eb..c4dff3dec1 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -9,6 +9,7 @@ from ..account.utils import store_user_addressfrom ..checkout import AddressTypefrom ..core.utils.taxes import (ZERO_MONEY, get_tax_rate_by_name, get_taxes_for_address)+from ..core.weight import zero_weightfrom ..dashboard.order.utils import get_voucher_discount_for_orderfrom ..discount.models import NotApplicablefrom ..order import FulfillmentStatus, OrderStatus@@ -77,6 +78,23 @@ def recalculate_order(order, **kwargs):total -= order.discount_amountorder.total = totalorder.save()+ recalculate_order_weight(order)+++def recalculate_order_weight(order):+ """Recalculate order weights.++ It removes lines with non-existing variants.+ """+ lines_to_remove = order.lines.filter(variant=None)+ if lines_to_remove.exists():+ lines_to_remove.delete()++ weight = zero_weight()+ for line in order:+ weight += line.variant.get_weight() * line.quantity+ order.weight = weight+ order.save()def update_order_prices(order, discounts):@@ -180,10 +198,11 @@ def add_variant_to_order("""if not allow_overselling:variant.check_quantity(quantity)++ order.weight += variant.get_weight() * quantitytry:line = order.lines.get(variant=variant)line.quantity += quantity- order.weight += variant.get_weight() * quantitywith transaction.atomic():line.save(update_fields=['quantity'])order.save(update_fields=['weight'])@@ -192,15 +211,17 @@ def add_variant_to_order(translated_product_name = variant.display_product(translated=True)if translated_product_name == product_name:translated_product_name = ''- line = order.lines.create(- product_name=product_name,- translated_product_name=translated_product_name,- product_sku=variant.sku,- is_shipping_required=variant.is_shipping_required(),- quantity=quantity,- variant=variant,- unit_price=variant.get_price(discounts, taxes),- tax_rate=get_tax_rate_by_name(variant.product.tax_rate, taxes))+ with transaction.atomic():+ line = order.lines.create(+ product_name=product_name,+ translated_product_name=translated_product_name,+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ quantity=quantity,+ variant=variant,+ unit_price=variant.get_price(discounts, taxes),+ tax_rate=get_tax_rate_by_name(variant.product.tax_rate, taxes))+ order.save(update_fields=['weight'])if variant.track_inventory and track_inventory:allocate_stock(variant, quantity)@@ -210,27 +231,15 @@ 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- order.weight += (- new_quantity * variant_weight - old_quantity * variant_weight)- with transaction.atomic():- line.save(update_fields=['quantity'])- order.save(update_fields=['weight'])+ line.save(update_fields=['quantity'])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'])+ line.delete()def restock_order_lines(order):diff --git a/tests/api/test_order.py b/tests/api/test_order.pyindex cd101dd94d..752f30deb4 100644--- a/tests/api/test_order.py+++ b/tests/api/test_order.py@@ -675,6 +675,7 @@ def test_draft_order_line_update(def test_draft_order_update_with_non_existing_product(draft_order, staff_api_client, permission_manage_orders):+ # To keep data integrity, delete broken lines from draft orderquery = DRAFT_ORDER_LINE_UPDATE_MUTATIONorder = draft_orderline = order.lines.first()@@ -686,7 +687,9 @@ def test_draft_order_update_with_non_existing_product(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)data = content['data']['draftOrderLineUpdate']- assert data['errors']+ assert not data['errors']+ with pytest.raises(line._meta.model.DoesNotExist):+ line.refresh_from_db()def test_require_draft_order_when_updating_lines(@@ -751,22 +754,6 @@ 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):