Skip to content

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

Fix calculating total price on draft order

Damian Wbd8499658bee
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7af11c5c5f..d0149c32c9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,6 +36,8 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix invalid tax rates for lines - #7058 by @IKarbowiak
- Allow seeing unconfirmed orders - #7072 by @IKarbowiak
- Raise GraphQLError when too big integer value is provided - #7076 by @IKarbowiak
+- Recalculate draft order when product/variant was deleted - #7085 by @d-wysocki
+- Added validation for `DraftOrderCreate` with negative quantity line - #7085 by @d-wysocki
### Breaking
- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index ca7c59d9cb..28b12c2864 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -165,6 +165,15 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
field_name = "channel"
raise ValidationError({field_name: error})
quantities = [line.get("quantity") for line in lines]
+ if not all(quantity > 0 for quantity in quantities):
+ raise ValidationError(
+ {
+ "quantity": ValidationError(
+ "Ensure this value is greater than 0.",
+ code=OrderErrorCode.ZERO_QUANTITY,
+ )
+ }
+ )
cleaned_input["variants"] = variants
cleaned_input["quantities"] = quantities
@@ -219,7 +228,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
for variant, quantity in zip(variants, quantities):
lines.append((quantity, variant))
add_variant_to_draft_order(
- instance, variant, quantity, info.context.plugins
+ instance, variant, quantity, info.context.user, info.context.plugins
)
# New event
@@ -456,7 +465,7 @@ class DraftOrderLinesCreate(BaseMutation):
try:
lines = [
add_variant_to_draft_order(
- order, variant, quantity, info.context.plugins
+ order, variant, quantity, info.context.user, info.context.plugins
)
for quantity, variant in lines_to_add
]
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 5e77cae996..1af8f419c0 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -1647,6 +1647,47 @@ def test_draft_order_create_without_channel(
assert error["field"] == "channel"
+def test_draft_order_create_with_negative_quantity_line(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ channel_USD,
+ variant,
+ voucher,
+ graphql_address_data,
+):
+ variant_0 = variant
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ variant_1 = product_without_shipping.variants.first()
+ variant_1.quantity = 2
+ variant_1.save()
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": -2},
+ {"variantId": variant_1_id, "quantity": 1},
+ ]
+ variables = {
+ "user": user_id,
+ "lines": variant_list,
+ "channel": channel_id,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderCreate"]["orderErrors"][0]
+ assert error["code"] == OrderErrorCode.ZERO_QUANTITY.name
+ assert error["field"] == "quantity"
+
+
def test_draft_order_create_with_channel_with_unpublished_product(
staff_api_client,
permission_manage_orders,
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index a3cee95198..78841b99a8 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -8,6 +8,7 @@ from graphene.types import InputObjectType
from ....core.permissions import ProductPermissions, ProductTypePermissions
from ....order import OrderStatus
from ....order import models as order_models
+from ....order.tasks import recalculate_orders_task
from ....product import models
from ....product.error_codes import ProductErrorCode
from ....product.tasks import update_product_discounted_price_task
@@ -96,11 +97,11 @@ class ProductBulkDelete(ModelBulkDeleteMutation):
variants_ids = [variant_id for _, variant_id in product_to_variant]
# get draft order lines for products
- order_line_pks = list(
- order_models.OrderLine.objects.filter(
- variant_id__in=variants_ids, order__status=OrderStatus.DRAFT
- ).values_list("pk", flat=True)
- )
+ lines_id_and_orders_id = order_models.OrderLine.objects.filter(
+ variant__id__in=variants_ids, order__status=OrderStatus.DRAFT
+ ).values("pk", "order_id")
+ line_pks = {line["pk"] for line in lines_id_and_orders_id}
+ orders_id = {line["order_id"] for line in lines_id_and_orders_id}
response = super().perform_mutation(
_root,
info,
@@ -111,7 +112,8 @@ class ProductBulkDelete(ModelBulkDeleteMutation):
)
# delete order lines for deleted variants
- order_models.OrderLine.objects.filter(pk__in=order_line_pks).delete()
+ order_models.OrderLine.objects.filter(pk__in=line_pks).delete()
+ recalculate_orders_task.delay(orders_id)
return response
@@ -497,13 +499,11 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
@transaction.atomic
def perform_mutation(cls, _root, info, ids, **data):
_, pks = resolve_global_ids_to_primary_keys(ids, ProductVariant)
- # get draft order lines for variants
- order_line_pks = list(
- order_models.OrderLine.objects.filter(
- variant__pk__in=pks, order__status=OrderStatus.DRAFT
- ).values_list("pk", flat=True)
- )
-
+ lines_id_and_orders_id = order_models.OrderLine.objects.filter(
+ variant__pk__in=pks, order__status=OrderStatus.DRAFT
+ ).values("pk", "order_id")
+ line_pks = {line["pk"] for line in lines_id_and_orders_id}
+ orders_id = {line["order_id"] for line in lines_id_and_orders_id}
product_pks = list(
models.Product.objects.filter(variants__in=pks)
.distinct()
@@ -529,7 +529,8 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
)
# delete order lines for deleted variants
- order_models.OrderLine.objects.filter(pk__in=order_line_pks).delete()
+ order_models.OrderLine.objects.filter(pk__in=line_pks).delete()
+ recalculate_orders_task.delay(orders_id)
# set new product default variant if any has been removed
products = models.Product.objects.filter(
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index fbe196f748..50d638d651 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -16,6 +16,7 @@ from ....core.utils.editorjs import clean_editor_js
from ....core.utils.validators import get_oembed_data
from ....order import OrderStatus
from ....order import models as order_models
+from ....order.tasks import recalculate_orders_task
from ....product import ProductMediaTypes, models
from ....product.error_codes import CollectionErrorCode, ProductErrorCode
from ....product.tasks import (
@@ -688,14 +689,15 @@ class ProductDelete(ModelDeleteMutation):
instance = cls.get_node_or_error(info, node_id, only_type=Product)
variants_id = list(instance.variants.all().values_list("id", flat=True))
# get draft order lines for variant
- line_pks = list(
- order_models.OrderLine.objects.filter(
- variant_id__in=variants_id, order__status=OrderStatus.DRAFT
- ).values_list("pk", flat=True)
- )
+ lines_id_and_orders_id = order_models.OrderLine.objects.filter(
+ variant__id__in=variants_id, order__status=OrderStatus.DRAFT
+ ).values("pk", "order_id")
+ line_pks = {line["pk"] for line in lines_id_and_orders_id}
+ orders_id = {line["order_id"] for line in lines_id_and_orders_id}
response = super().perform_mutation(_root, info, **data)
# delete order lines for deleted variant
order_models.OrderLine.objects.filter(pk__in=line_pks).delete()
+ recalculate_orders_task.delay(orders_id)
info.context.plugins.product_deleted(instance, variants_id)
return response
@@ -993,11 +995,11 @@ class ProductVariantDelete(ModelDeleteMutation):
instance = cls.get_node_or_error(info, node_id, only_type=ProductVariant)
# get draft order lines for variant
- line_pks = list(
- order_models.OrderLine.objects.filter(
- variant__pk=instance.pk, order__status=OrderStatus.DRAFT
- ).values_list("pk", flat=True)
- )
+ lines_id_and_orders_id = order_models.OrderLine.objects.filter(
+ variant__pk=instance.pk, order__status=OrderStatus.DRAFT
+ ).values("pk", "order_id")
+ line_pks = {line["pk"] for line in lines_id_and_orders_id}
+ orders_id = {line["order_id"] for line in lines_id_and_orders_id}
# Get cached variant with related fields to fully populate webhook payload.
variant = (
@@ -1010,6 +1012,7 @@ class ProductVariantDelete(ModelDeleteMutation):
# delete order lines for deleted variant
order_models.OrderLine.objects.filter(pk__in=line_pks).delete()
+ recalculate_orders_task.delay(orders_id)
transaction.on_commit(
lambda: info.context.plugins.product_variant_deleted(variant)
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 8802442fd2..0ecfc68932 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -179,8 +179,14 @@ mutation productBulkDelete($ids: [ID]!) {
"""
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_products(
- staff_api_client, product_list, permission_manage_products, order_list, channel_USD
+ mocked_recalculate_orders_task,
+ staff_api_client,
+ product_list,
+ permission_manage_products,
+ order_list,
+ channel_USD,
):
# given
query = DELETE_PRODUCTS_MUTATION
@@ -248,10 +254,13 @@ def test_delete_products(
assert not OrderLine.objects.filter(pk__in=draft_order_lines_pks).exists()
assert OrderLine.objects.filter(pk__in=not_draft_order_lines_pks).exists()
+ assert mocked_recalculate_orders_task.called
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_products_trigger_webhook(
+ mocked_recalculate_orders_task,
mocked_webhook_trigger,
staff_api_client,
product_list,
@@ -276,21 +285,25 @@ def test_delete_products_trigger_webhook(
assert content["data"]["productBulkDelete"]["count"] == 3
assert mocked_webhook_trigger.called
+ assert mocked_recalculate_orders_task.called
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_products_variants_in_draft_order(
- staff_api_client, product_list, permission_manage_products
+ mocked_recalculate_orders_task,
+ draft_order,
+ staff_api_client,
+ product_list,
+ permission_manage_products,
):
query = DELETE_PRODUCTS_MUTATION
-
- assert ProductChannelListing.objects.filter(
- product_id__in=[product.id for product in product_list]
- ).exists()
+ products_id = draft_order.lines.all().values_list("variant__product_id", flat=True)
+ assert ProductChannelListing.objects.filter(product_id__in=products_id).exists()
variables = {
"ids": [
- graphene.Node.to_global_id("Product", product.id)
- for product in product_list
+ graphene.Node.to_global_id("Product", product_id)
+ for product_id in products_id
]
}
response = staff_api_client.post_graphql(
@@ -298,13 +311,10 @@ def test_delete_products_variants_in_draft_order(
)
content = get_graphql_content(response)
- assert content["data"]["productBulkDelete"]["count"] == 3
- assert not Product.objects.filter(
- id__in=[product.id for product in product_list]
- ).exists()
- assert not ProductChannelListing.objects.filter(
- product_id__in=[product.id for product in product_list]
- ).exists()
+ assert content["data"]["productBulkDelete"]["count"] == 2
+ assert not Product.objects.filter(id__in=products_id).exists()
+ assert not ProductChannelListing.objects.filter(product_id__in=products_id).exists()
+ mocked_recalculate_orders_task.assert_called_once_with({draft_order.id})
def test_delete_product_media(
@@ -375,7 +385,9 @@ mutation productVariantBulkDelete($ids: [ID]!) {
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_variants(
+ mocked_recalculate_orders_task,
product_variant_deleted_webhook_mock,
staff_api_client,
product_variant_list,
@@ -407,9 +419,12 @@ def test_delete_product_variants(
product_variant_deleted_webhook_mock.call_count
== content["data"]["productVariantBulkDelete"]["count"]
)
+ assert mocked_recalculate_orders_task.called
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_variants_in_draft_orders(
+ mocked_recalculate_orders_task,
staff_api_client,
product_variant_list,
permission_manage_products,
@@ -500,10 +515,15 @@ def test_delete_product_variants_in_draft_orders(
second_draft_order.refresh_from_db()
assert OrderLine.objects.filter(pk=order_line_not_in_draft_pk).exists()
+ mocked_recalculate_orders_task.assert_called_once_with({draft_order.id})
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_variants_delete_default_variant(
- staff_api_client, product, permission_manage_products
+ mocked_recalculate_orders_task,
+ staff_api_client,
+ product,
+ permission_manage_products,
):
# given
query = PRODUCT_VARIANT_BULK_DELETE_MUTATION
@@ -546,10 +566,15 @@ def test_delete_product_variants_delete_default_variant(
product.refresh_from_db()
assert product.default_variant.pk == new_default_variant.pk
+ assert mocked_recalculate_orders_task.called
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_variants_delete_all_product_variants(
- staff_api_client, product, permission_manage_products
+ mocked_recalculate_orders_task,
+ staff_api_client,
+ product,
+ permission_manage_products,
):
# given
query = PRODUCT_VARIANT_BULK_DELETE_MUTATION
@@ -591,10 +616,16 @@ def test_delete_product_variants_delete_all_product_variants(
product.refresh_from_db()
assert product.default_variant is None
+ assert mocked_recalculate_orders_task.called
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_variants_from_different_products(
- staff_api_client, product, product_with_two_variants, permission_manage_products
+ mocked_recalculate_orders_task,
+ staff_api_client,
+ product,
+ product_with_two_variants,
+ permission_manage_products,
):
# given
query = PRODUCT_VARIANT_BULK_DELETE_MUTATION
@@ -637,3 +668,4 @@ def test_delete_product_variants_from_different_products(
assert product_1.default_variant is None
assert product_2.default_variant.pk == product_2_second_variant.pk
+ assert mocked_recalculate_orders_task.called
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 01cb6a49ce..78a70bd003 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -5150,7 +5150,13 @@ DELETE_PRODUCT_MUTATION = """
"""
-def test_delete_product(staff_api_client, product, permission_manage_products):
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
+def test_delete_product(
+ mocked_recalculate_orders_task,
+ staff_api_client,
+ product,
+ permission_manage_products,
+):
query = DELETE_PRODUCT_MUTATION
node_id = graphene.Node.to_global_id("Product", product.id)
variables = {"id": node_id}
@@ -5163,10 +5169,13 @@ def test_delete_product(staff_api_client, product, permission_manage_products):
with pytest.raises(product._meta.model.DoesNotExist):
product.refresh_from_db()
assert node_id == data["product"]["id"]
+ assert mocked_recalculate_orders_task.called
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_trigger_webhook(
+ mocked_recalculate_orders_task,
mocked_webhook_trigger,
staff_api_client,
product,
@@ -5194,9 +5203,12 @@ def test_delete_product_trigger_webhook(
mocked_webhook_trigger.assert_called_once_with(
WebhookEventType.PRODUCT_DELETED, expected_data
)
+ assert mocked_recalculate_orders_task.called
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_variant_in_draft_order(
+ mocked_recalculate_orders_task,
staff_api_client,
product_with_two_variants,
permission_manage_products,
@@ -5262,6 +5274,7 @@ def test_delete_product_variant_in_draft_order(
assert not OrderLine.objects.filter(pk__in=draft_order_lines_pks).exists()
assert OrderLine.objects.filter(pk__in=not_draft_order_lines_pks).exists()
+ mocked_recalculate_orders_task.assert_called_once_with({draft_order.id})
def test_product_type(user_api_client, product_type, channel_USD):
diff --git a/saleor/graphql/product/tests/test_product_discounted_price.py b/saleor/graphql/product/tests/test_product_discounted_price.py
index 751db4d850..2af2f221d0 100644
--- a/saleor/graphql/product/tests/test_product_discounted_price.py
+++ b/saleor/graphql/product/tests/test_product_discounted_price.py
@@ -8,7 +8,9 @@ from ...tests.utils import get_graphql_content
@patch("saleor.graphql.product.mutations.products.update_product_discounted_price_task")
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_product_variant_delete_updates_discounted_price(
+ mocked_recalculate_orders_task,
mock_update_product_discounted_price_task,
staff_api_client,
product,
@@ -38,6 +40,7 @@ def test_product_variant_delete_updates_discounted_price(
assert data["errors"] == []
mock_update_product_discounted_price_task.delay.assert_called_once_with(product.pk)
+ assert mocked_recalculate_orders_task.called
@patch("saleor.product.utils.update_products_discounted_prices_task")
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index dbb3d18bf0..41d0988e84 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -1882,7 +1882,9 @@ DELETE_VARIANT_MUTATION = """
@patch("saleor.plugins.manager.PluginsManager.product_variant_deleted")
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_variant(
+ mocked_recalculate_orders_task,
product_variant_deleted_webhook_mock,
staff_api_client,
product,
@@ -1903,9 +1905,12 @@ def test_delete_variant(
assert data["productVariant"]["sku"] == variant.sku
with pytest.raises(variant._meta.model.DoesNotExist):
variant.refresh_from_db()
+ assert mocked_recalculate_orders_task.called
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_variant_in_draft_order(
+ mocked_recalculate_orders_task,
staff_api_client,
order_line,
permission_manage_products,
@@ -1941,7 +1946,20 @@ def test_delete_variant_in_draft_order(
quantity=quantity,
)
order_line_not_in_draft_pk = order_line_not_in_draft.pk
-
+ second_draft_order = order_list[0]
+ second_draft_order.status = OrderStatus.DRAFT
+ second_draft_order.save(update_fields=["status"])
+ OrderLine.objects.create(
+ variant=variant,
+ order=second_draft_order,
+ product_name=str(product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ is_shipping_required=variant.is_shipping_required(),
+ unit_price=unit_price,
+ total_price=unit_price * quantity,
+ quantity=quantity,
+ )
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
@@ -1953,10 +1971,17 @@ def test_delete_variant_in_draft_order(
order_line.refresh_from_db()
assert OrderLine.objects.filter(pk=order_line_not_in_draft_pk).exists()
+ mocked_recalculate_orders_task.assert_called_once_with(
+ {draft_order.id, second_draft_order.id}
+ )
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_default_variant(
- staff_api_client, product_with_two_variants, permission_manage_products
+ mocked_recalculate_orders_task,
+ staff_api_client,
+ product_with_two_variants,
+ permission_manage_products,
):
# given
query = DELETE_VARIANT_MUTATION
@@ -1987,10 +2012,15 @@ def test_delete_default_variant(
product.refresh_from_db()
assert product.default_variant.pk == second_variant.pk
+ assert mocked_recalculate_orders_task.called
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_not_default_variant_left_default_variant_unchanged(
- staff_api_client, product_with_two_variants, permission_manage_products
+ mocked_recalculate_orders_task,
+ staff_api_client,
+ product_with_two_variants,
+ permission_manage_products,
):
# given
query = DELETE_VARIANT_MUTATION
@@ -2021,10 +2051,15 @@ def test_delete_not_default_variant_left_default_variant_unchanged(
product.refresh_from_db()
assert product.default_variant.pk == default_variant.pk
+ assert mocked_recalculate_orders_task.called
+@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_default_all_product_variant_left_product_default_variant_unset(
- staff_api_client, product, permission_manage_products
+ mocked_recalculate_orders_task,
+ staff_api_client,
+ product,
+ permission_manage_products,
):
# given
query = DELETE_VARIANT_MUTATION
@@ -2053,6 +2088,7 @@ def test_delete_default_all_product_variant_left_product_default_variant_unset(
product.refresh_from_db()
assert not product.default_variant
+ assert mocked_recalculate_orders_task.called
def _fetch_all_variants(client, variables={}, permissions=None):
diff --git a/saleor/graphql/tests/fixtures.py b/saleor/graphql/tests/fixtures.py
index 422233910b..641e5f2a84 100644
--- a/saleor/graphql/tests/fixtures.py
+++ b/saleor/graphql/tests/fixtures.py
@@ -1,5 +1,6 @@
import json
import logging
+from unittest.mock import Mock
import graphene
import pytest
@@ -10,6 +11,7 @@ from django.test.client import MULTIPART_CONTENT, Client
from ...account.models import User
from ...core.jwt import create_access_token
+from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
from ..views import handled_errors_logger, unhandled_errors_logger
from .utils import assert_no_permission
@@ -143,10 +145,15 @@ def api_client():
@pytest.fixture
def schema_context():
- params = {"user": AnonymousUser()}
+ params = {"user": AnonymousUser(), "plugins": get_plugins_manager()}
return graphene.types.Context(**params)
+def info(schema_context):
+ return Mock(context=schema_context)
+
+
class LoggingHandler(logging.Handler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
diff --git a/saleor/order/tasks.py b/saleor/order/tasks.py
new file mode 100644
index 0000000000..bded7a4a35
--- /dev/null
+++ b/saleor/order/tasks.py
@@ -0,0 +1,12 @@
+from typing import List
+
+from ..celeryconf import app
+from .models import Order
+from .utils import recalculate_order
+
+
+def recalculate_orders_task(order_ids: List[int]):
+ orders = Order.objects.filter(id__in=order_ids)
+ for order in orders:
+ recalculate_order(order)
diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.py
index d6e4cb832a..d4f767878c 100644
--- a/saleor/order/tests/test_notifications.py
+++ b/saleor/order/tests/test_notifications.py
@@ -261,14 +261,18 @@ def test_send_email_order_confirmation(mocked_notify, order, site_settings):
def test_send_confirmation_emails_without_addresses_for_payment(
mocked_notify,
site_settings,
+ info,
digital_content,
payment_dummy,
):
order = payment_dummy.order
- manager = get_plugins_manager()
line = add_variant_to_draft_order(
- order, digital_content.product_variant, quantity=1, manager=manager
+ order,
+ digital_content.product_variant,
+ quantity=1,
+ user=info.context.user,
+ manager=info.context.plugins,
)
DigitalContentUrl.objects.create(content=digital_content, line=line)
@@ -277,7 +281,7 @@ def test_send_confirmation_emails_without_addresses_for_payment(
order.billing_address = None
order.save(update_fields=["shipping_address", "shipping_method", "billing_address"])
- notifications.send_payment_confirmation(order, manager)
+ notifications.send_payment_confirmation(order, info.context.plugins)
expected_payload = {
"order": get_default_order_payload(order),
@@ -300,14 +304,17 @@ def test_send_confirmation_emails_without_addresses_for_payment(
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_send_confirmation_emails_without_addresses_for_order(
- mocked_notify, order, site_settings, digital_content
+ mocked_notify, order, site_settings, digital_content, info
):
assert not order.lines.count()
- manager = get_plugins_manager()
line = add_variant_to_draft_order(
- order, digital_content.product_variant, quantity=1, manager=manager
+ order,
+ digital_content.product_variant,
+ quantity=1,
+ user=info.context.user,
+ manager=info.context.plugins,
)
DigitalContentUrl.objects.create(content=digital_content, line=line)
@@ -318,7 +325,7 @@ def test_send_confirmation_emails_without_addresses_for_order(
redirect_url = "https://www.example.com"
- notifications.send_order_confirmation(order, redirect_url, manager)
+ notifications.send_order_confirmation(order, redirect_url, info.context.plugins)
expected_payload = {
"order": get_default_order_payload(order, redirect_url),
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index dff31cd609..9b4e62f2ac 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -76,14 +76,15 @@ def test_order_get_subtotal(order_with_lines):
def test_add_variant_to_draft_order_adds_line_for_new_variant(
- order_with_lines, product, product_translation_fr, settings
+ order_with_lines, product, product_translation_fr, settings, info
):
order = order_with_lines
variant = product.variants.get()
lines_before = order.lines.count()
settings.LANGUAGE_CODE = "fr"
- manager = get_plugins_manager()
- add_variant_to_draft_order(order, variant, 1, manager)
+ add_variant_to_draft_order(
+ order, variant, 1, info.context.user, info.context.plugins
+ )
line = order.lines.last()
assert order.lines.count() == lines_before + 1
@@ -96,7 +97,7 @@ def test_add_variant_to_draft_order_adds_line_for_new_variant(
def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(
- order_with_lines, product, product_translation_fr, settings
+ order_with_lines, product, product_translation_fr, settings, info
):
order = order_with_lines
variant = product.variants.get()
@@ -106,8 +107,9 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(
lines_before = order.lines.count()
settings.LANGUAGE_CODE = "fr"
- manager = get_plugins_manager()
- add_variant_to_draft_order(order, variant, 1, manager)
+ add_variant_to_draft_order(
+ order, variant, 1, info.context.user, info.context.plugins
+ )
line = order.lines.last()
assert order.lines.count() == lines_before + 1
@@ -119,28 +121,32 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(
def test_add_variant_to_draft_order_not_allocates_stock_for_new_variant(
- order_with_lines, product
+ order_with_lines, product, info
):
variant = product.variants.get()
stock = Stock.objects.get(product_variant=variant)
stock_before = get_quantity_allocated_for_stock(stock)
- manager = get_plugins_manager()
- add_variant_to_draft_order(order_with_lines, variant, 1, manager)
+ add_variant_to_draft_order(
+ order_with_lines, variant, 1, info.context.user, info.context.plugins
+ )
stock.refresh_from_db()
assert get_quantity_allocated_for_stock(stock) == stock_before
-def test_add_variant_to_draft_order_edits_line_for_existing_variant(order_with_lines):
+def test_add_variant_to_draft_order_edits_line_for_existing_variant(
+ order_with_lines, info
+):
existing_line = order_with_lines.lines.first()
variant = existing_line.variant
lines_before = order_with_lines.lines.count()
line_quantity_before = existing_line.quantity
- manager = get_plugins_manager()
- add_variant_to_draft_order(order_with_lines, variant, 1, manager)
+ add_variant_to_draft_order(
+ order_with_lines, variant, 1, info.context.user, info.context.plugins
+ )
existing_line.refresh_from_db()
assert order_with_lines.lines.count() == lines_before
@@ -149,7 +155,7 @@ def test_add_variant_to_draft_order_edits_line_for_existing_variant(order_with_l
def test_add_variant_to_draft_order_not_allocates_stock_for_existing_variant(
- order_with_lines,
+ order_with_lines, info
):
existing_line = order_with_lines.lines.first()
variant = existing_line.variant
@@ -157,9 +163,10 @@ def test_add_variant_to_draft_order_not_allocates_stock_for_existing_variant(
stock_before = get_quantity_allocated_for_stock(stock)
quantity_before = existing_line.quantity
quantity_unfulfilled_before = existing_line.quantity_unfulfilled
- manager = get_plugins_manager()
- add_variant_to_draft_order(order_with_lines, variant, 1, manager)
+ add_variant_to_draft_order(
+ order_with_lines, variant, 1, info.context.user, info.context.plugins
+ )
stock.refresh_from_db()
existing_line.refresh_from_db()
@@ -579,20 +586,22 @@ def test_calculate_order_weight(order_with_lines):
assert calculated_weight == order_weight
-def test_order_weight_add_more_variant(order_with_lines):
+def test_order_weight_add_more_variant(order_with_lines, info):
variant = order_with_lines.lines.first().variant
- manager = get_plugins_manager()
- add_variant_to_draft_order(order_with_lines, variant, 2, manager)
+ add_variant_to_draft_order(
+ order_with_lines, variant, 2, info.context.user, info.context.plugins
+ )
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):
+def test_order_weight_add_new_variant(order_with_lines, product, info):
variant = product.variants.first()
- manager = get_plugins_manager()
- add_variant_to_draft_order(order_with_lines, variant, 2, manager)
+ add_variant_to_draft_order(
+ order_with_lines, variant, 2, info.context.user, info.context.plugins
+ )
order_with_lines.refresh_from_db()
assert order_with_lines.weight == _calculate_order_weight_from_lines(
order_with_lines
@@ -617,12 +626,13 @@ def test_order_weight_delete_line(order_with_lines):
)
-def test_get_order_weight_non_existing_product(order_with_lines, product):
+def test_get_order_weight_non_existing_product(order_with_lines, product, info):
# Removing product should not affect order's weight
order = order_with_lines
variant = product.variants.first()
- manager = get_plugins_manager()
- add_variant_to_draft_order(order, variant, 1, manager)
+ add_variant_to_draft_order(
+ order, variant, 1, info.context.user, info.context.plugins
+ )
old_weight = order.get_total_weight()
product.delete()
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index e8bf90fd9d..f1ac700ec1 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -290,15 +290,16 @@ def update_order_status(order):
@transaction.atomic
-def add_variant_to_draft_order(order, variant, quantity, manager, discounts=None):
+def add_variant_to_draft_order(order, variant, quantity, user, manager, discounts=None):
"""Add total_quantity of variant to order.
Returns an order line the variant was added to.
"""
try:
line = order.lines.get(variant=variant)
- line.quantity += quantity
- line.save(update_fields=["quantity"])
+ old_quantity = line.quantity
+ new_quantity = old_quantity + quantity
+ change_order_line_quantity(user, line, old_quantity, new_quantity)
except OrderLine.DoesNotExist:
product = variant.product
collections = product.collections.all()