Skip to content

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

Remove quantity field from checkout (#7296)

Damian Wysockiafa1c1ca1b1a
diff --git a/saleor/checkout/migrations/0034_remove_checkout_quantity.py b/saleor/checkout/migrations/0034_remove_checkout_quantity.py
new file mode 100644
index 0000000000..f080500626
--- /dev/null
+++ b/saleor/checkout/migrations/0034_remove_checkout_quantity.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.1.7 on 2021-04-28 07:01
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("checkout", "0033_checkout_language_code"),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name="checkout",
+ name="quantity",
+ ),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 18fdb27282..9d6adfe765 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -47,7 +47,6 @@ class Checkout(ModelWithMetadata):
)
email = models.EmailField()
token = models.UUIDField(primary_key=True, default=uuid4, editable=False)
- quantity = models.PositiveIntegerField(default=0)
channel = models.ForeignKey(
Channel,
related_name="checkouts",
@@ -98,9 +97,6 @@ class Checkout(ModelWithMetadata):
(CheckoutPermissions.MANAGE_CHECKOUTS.codename, "Manage checkouts"),
)
- def __repr__(self):
- return "Checkout(quantity=%s)" % (self.quantity,)
-
def __iter__(self):
return iter(self.lines.all())
diff --git a/saleor/checkout/tests/test_cart.py b/saleor/checkout/tests/test_cart.py
index edded30ed6..21fe1b17fb 100644
--- a/saleor/checkout/tests/test_cart.py
+++ b/saleor/checkout/tests/test_cart.py
@@ -7,7 +7,7 @@ from ...plugins.manager import get_plugins_manager
from ...product.models import Category
from .. import calculations, utils
from ..models import Checkout
-from ..utils import add_variant_to_checkout
+from ..utils import add_variant_to_checkout, calculate_checkout_quantity
@pytest.fixture()
@@ -35,11 +35,12 @@ def test_adding_same_variant(checkout, product):
checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
add_variant_to_checkout(checkout_info, variant, 1)
add_variant_to_checkout(checkout_info, variant, 2)
+ lines = fetch_checkout_lines(checkout)
+ checkout_quantity = calculate_checkout_quantity(lines)
assert checkout.lines.count() == 1
- assert checkout.quantity == 3
+ assert checkout_quantity == 3
subtotal = TaxedMoney(Money("30.00", "USD"), Money("30.00", "USD"))
manager = get_plugins_manager()
- lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
manager = get_plugins_manager()
assert (
@@ -58,8 +59,9 @@ def test_replacing_same_variant(checkout, product):
checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
add_variant_to_checkout(checkout_info, variant, 1, replace=True)
add_variant_to_checkout(checkout_info, variant, 2, replace=True)
+ lines = fetch_checkout_lines(checkout)
assert checkout.lines.count() == 1
- assert checkout.quantity == 2
+ assert calculate_checkout_quantity(lines) == 2
def test_adding_invalid_quantity(checkout, product):
@@ -243,14 +245,6 @@ def test_get_prices_of_discounted_specific_product_all_products(
assert prices == excepted_value
-def test_checkout_repr():
- checkout = Checkout()
- assert repr(checkout) == "Checkout(quantity=0)"
-
- checkout.quantity = 1
- assert repr(checkout) == "Checkout(quantity=1)"
-
-
def test_checkout_line_repr(product, checkout_with_single_item):
variant = product.variants.get()
line = checkout_with_single_item.lines.first()
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 6cacc4c15f..28a49b2860 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -17,10 +17,16 @@ from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
from ...shipping.models import ShippingZone
from .. import AddressType, calculations
-from ..fetch import CheckoutInfo, fetch_checkout_info, fetch_checkout_lines
+from ..fetch import (
+ CheckoutInfo,
+ CheckoutLineInfo,
+ fetch_checkout_info,
+ fetch_checkout_lines,
+)
from ..models import Checkout
from ..utils import (
add_voucher_to_checkout,
+ calculate_checkout_quantity,
cancel_active_payments,
change_billing_address_in_checkout,
change_shipping_address_in_checkout,
@@ -91,25 +97,25 @@ def test_last_change_update_foregin_key(checkout, shipping_method):
@pytest.mark.parametrize(
- "total, min_spent_amount, total_quantity, min_checkout_items_quantity, "
+ "total, min_spent_amount, min_checkout_items_quantity, "
"discount_value, discount_value_type, expected_value",
[
- (20, 20, 2, 2, 50, DiscountValueType.PERCENTAGE, 10),
- (20, None, 2, None, 50, DiscountValueType.PERCENTAGE, 10),
- (20, 20, 2, 2, 5, DiscountValueType.FIXED, 5),
- (20, None, 2, None, 5, DiscountValueType.FIXED, 5),
+ (20, 20, 2, 50, DiscountValueType.PERCENTAGE, 10),
+ (20, None, None, 50, DiscountValueType.PERCENTAGE, 10),
+ (20, 20, 2, 5, DiscountValueType.FIXED, 5),
+ (20, None, None, 5, DiscountValueType.FIXED, 5),
],
)
def test_get_discount_for_checkout_value_voucher(
total,
min_spent_amount,
- total_quantity,
min_checkout_items_quantity,
discount_value,
discount_value_type,
expected_value,
monkeypatch,
channel_USD,
+ checkout_with_items,
):
voucher = Voucher.objects.create(
code="unique",
@@ -123,7 +129,7 @@ def test_get_discount_for_checkout_value_voucher(
discount=Money(discount_value, channel_USD.currency_code),
min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
)
- checkout = Mock(spec=Checkout, quantity=total_quantity, channel=channel_USD)
+ checkout = Mock(spec=checkout_with_items, channel=channel_USD)
subtotal = TaxedMoney(Money(total, "USD"), Money(total, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
@@ -143,9 +149,20 @@ def test_get_discount_for_checkout_value_voucher(
shipping_method_channel_listings=None,
valid_shipping_methods=[],
)
+ lines = [
+ CheckoutLineInfo(
+ line=line,
+ channel_listing=line.variant.product.channel_listings.first(),
+ collections=[],
+ product=line.variant.product,
+ variant=line.variant,
+ product_type=line.variant.product.product_type,
+ )
+ for line in checkout_with_items.lines.all()
+ ]
manager = get_plugins_manager()
discount = get_voucher_discount_for_checkout(
- manager, voucher, checkout_info, [], None, []
+ manager, voucher, checkout_info, lines, None, []
)
assert discount == Money(expected_value, "USD")
@@ -156,12 +173,12 @@ def test_get_voucher_discount_for_checkout_voucher_validation(
):
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout_with_voucher)
+ quantity = calculate_checkout_quantity(lines)
checkout_info = fetch_checkout_info(checkout_with_voucher, lines, [], manager)
manager = get_plugins_manager()
address = checkout_with_voucher.shipping_address
get_voucher_discount_for_checkout(manager, voucher, checkout_info, lines, address)
subtotal = manager.calculate_checkout_subtotal(checkout_info, lines, address, [])
- quantity = checkout_with_voucher.quantity
customer_email = checkout_with_voucher.get_customer_email()
mock_validate_voucher.assert_called_once_with(
voucher, subtotal.gross, quantity, customer_email, checkout_with_voucher.channel
@@ -201,7 +218,7 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable(
discount=Money(discount_value, channel_USD.currency_code),
min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
)
- checkout = Mock(spec=Checkout, quantity=total_quantity, channel=channel_USD)
+ checkout = Mock(spec=Checkout, channel=channel_USD)
subtotal = TaxedMoney(Money(total, "USD"), Money(total, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index a065741802..8b0cad5025 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1,8 +1,10 @@
"""Checkout-related utility functions."""
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
+import graphene
from django.core.exceptions import ValidationError
-from django.db.models import Sum
+from django.db.models import Count, F, OuterRef, Subquery, Sum
+from django.db.models.functions import Coalesce
from django.utils import timezone
from prices import Money
@@ -117,10 +119,13 @@ def add_variant_to_checkout(
line.quantity = new_quantity
line.save(update_fields=["quantity"])
- checkout = update_checkout_quantity(checkout)
return checkout
+def calculate_checkout_quantity(lines: Iterable["CheckoutLineInfo"]):
+ return sum([line_info.line.quantity for line_info in lines])
+
+
def add_variants_to_checkout(checkout, variants, quantities, channel_slug):
"""Add variants to checkout.
@@ -151,19 +156,6 @@ def add_variants_to_checkout(checkout, variants, quantities, channel_slug):
CheckoutLine(checkout=checkout, variant=variant, quantity=quantity)
)
checkout.lines.bulk_create(lines)
- checkout = update_checkout_quantity(checkout)
- return checkout
-
-
-def update_checkout_quantity(checkout):
- """Update the total quantity in checkout."""
- total_lines = checkout.lines.aggregate(total_quantity=Sum("quantity"))[
- "total_quantity"
- ]
- if not total_lines:
- total_lines = 0
- checkout.quantity = total_lines
- checkout.save(update_fields=["quantity"])
return checkout
@@ -651,3 +643,28 @@ def is_shipping_required(lines: Iterable["CheckoutLineInfo"]):
return any(
line_info.product.product_type.is_shipping_required for line_info in lines
)
+
+
+def validate_variants_in_checkout_lines(lines: Iterable["CheckoutLineInfo"]):
+ variants_listings_map = {line.variant.id: line.channel_listing for line in lines}
+
+ not_available_variants = [
+ variant_id
+ for variant_id, channel_listing in variants_listings_map.items()
+ if channel_listing is None or channel_listing.price is None
+ ]
+ if not_available_variants:
+ not_available_variants_ids = {
+ graphene.Node.to_global_id("ProductVariant", pk)
+ for pk in not_available_variants
+ }
+ error_code = CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ "Cannot add lines with unavailable variants.",
+ code=error_code, # type: ignore
+ params={"variants": not_available_variants_ids},
+ )
+ }
+ )
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 23b4cc8c79..e23f788a99 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -116,7 +116,9 @@ def validate_voucher_for_checkout(
lines: Iterable["CheckoutLineInfo"],
discounts: Optional[Iterable[DiscountInfo]],
):
- checkout = checkout_info.checkout
+ from ..checkout.utils import calculate_checkout_quantity
+
+ quantity = calculate_checkout_quantity(lines)
address = checkout_info.shipping_address or checkout_info.billing_address
subtotal = calculations.checkout_subtotal(
manager=manager,
@@ -130,7 +132,7 @@ def validate_voucher_for_checkout(
validate_voucher(
voucher,
subtotal.gross,
- checkout.quantity,
+ quantity,
customer_email,
checkout_info.channel,
)
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index fbcb396736..b3362c6c51 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -24,13 +24,14 @@ from ...checkout.utils import (
add_promo_code_to_checkout,
add_variant_to_checkout,
add_variants_to_checkout,
+ calculate_checkout_quantity,
change_billing_address_in_checkout,
change_shipping_address_in_checkout,
get_user_checkout,
is_shipping_required,
recalculate_checkout_discount,
remove_promo_code_from_checkout,
- update_checkout_quantity,
+ validate_variants_in_checkout_lines,
)
from ...core import analytics
from ...core.exceptions import InsufficientStock, PermissionDenied, ProductNotPublished
@@ -92,8 +93,9 @@ def update_checkout_shipping_method_if_invalid(
checkout_info: "CheckoutInfo", lines: Iterable[CheckoutLineInfo]
):
checkout = checkout_info.checkout
+ quantity = calculate_checkout_quantity(lines)
# remove shipping method when empty checkout
- if checkout.quantity == 0 or not is_shipping_required(lines):
+ if quantity == 0 or not is_shipping_required(lines):
checkout.shipping_method = None
checkout_info.shipping_method = None
checkout_info.shipping_method_channel_listings = None
@@ -538,7 +540,6 @@ class CheckoutLineDelete(BaseMutation):
checkout, lines, info.context.discounts, manager
)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
- update_checkout_quantity(checkout)
recalculate_checkout_discount(
manager, checkout_info, lines, info.context.discounts
)
@@ -674,7 +675,6 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
discounts = info.context.discounts
manager = info.context.plugins
- lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)
country = get_user_country_context(
@@ -936,12 +936,7 @@ class CheckoutComplete(BaseMutation):
manager = info.context.plugins
lines = fetch_checkout_lines(checkout)
- variants_id = {line.variant.id for line in lines}
- validate_variants_available_in_channel(
- variants_id,
- checkout.channel,
- CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL,
- )
+ validate_variants_in_checkout_lines(lines)
checkout_info = fetch_checkout_info(
checkout, lines, info.context.discounts, manager
)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index ecedbcb492..d83431efeb 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -23,7 +23,7 @@ from ....checkout.checkout_cleaner import (
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.models import Checkout
-from ....checkout.utils import add_variant_to_checkout
+from ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity
from ....core.payments import PaymentInterface
from ....payment import TransactionKind
from ....payment.interface import GatewayResponse
@@ -183,9 +183,9 @@ def test_checkout_create_with_default_channel(
assert content["created"] is True
new_checkout = Checkout.objects.first()
-
+ lines = fetch_checkout_lines(new_checkout)
assert new_checkout.channel == channel_USD
- assert new_checkout.quantity == quantity
+ assert calculate_checkout_quantity(lines) == quantity
assert any(
[str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
@@ -1469,8 +1469,8 @@ def test_checkout_lines_add(
variant = stock.product_variant
checkout = checkout_with_item
line = checkout.lines.first()
- assert line.quantity == 3
- assert checkout.quantity == 3
+ lines = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 3
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
@@ -1484,10 +1484,11 @@ def test_checkout_lines_add(
data = content["data"]["checkoutLinesAdd"]
assert not data["errors"]
checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
line = checkout.lines.latest("pk")
assert line.variant == variant
assert line.quantity == 1
- assert checkout.quantity == 4
+ assert calculate_checkout_quantity(lines) == 4
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout)
@@ -1764,8 +1765,9 @@ def test_checkout_lines_update(
mocked_update_shipping_method, user_api_client, checkout_with_item
):
checkout = checkout_with_item
+ lines = fetch_checkout_lines(checkout)
assert checkout.lines.count() == 1
- assert checkout.quantity == 3
+ assert calculate_checkout_quantity(lines) == 3
line = checkout.lines.first()
variant = line.variant
assert line.quantity == 3
@@ -1783,11 +1785,12 @@ def test_checkout_lines_update(
data = content["data"]["checkoutLinesUpdate"]
assert not data["errors"]
checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
assert checkout.lines.count() == 1
line = checkout.lines.first()
assert line.variant == variant
assert line.quantity == 1
- assert checkout.quantity == 1
+ assert calculate_checkout_quantity(lines) == 1
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout)
@@ -1951,7 +1954,6 @@ def test_checkout_lines_update_with_chosen_shipping(
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
-
variables = {
"checkoutId": checkout_id,
"lines": [{"variantId": variant_id, "quantity": 1}],
@@ -1962,7 +1964,8 @@ def test_checkout_lines_update_with_chosen_shipping(
data = content["data"]["checkoutLinesUpdate"]
assert not data["errors"]
checkout.refresh_from_db()
- assert checkout.quantity == 1
+ lines = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 1
MUTATION_CHECKOUT_LINES_DELETE = """
@@ -1994,7 +1997,8 @@ def test_checkout_line_delete(
mocked_update_shipping_method, user_api_client, checkout_with_item
):
checkout = checkout_with_item
- assert checkout.quantity == 3
+ lines = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 3
assert checkout.lines.count() == 1
line = checkout.lines.first()
assert line.quantity == 3
@@ -2009,10 +2013,10 @@ def test_checkout_line_delete(
data = content["data"]["checkoutLineDelete"]
assert not data["errors"]
checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
assert checkout.lines.count() == 0
- assert checkout.quantity == 0
+ assert calculate_checkout_quantity(lines) == 0
manager = get_plugins_manager()
- lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index 0e03166baa..1870e65c6a 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -244,7 +244,7 @@ def test_checkout_complete(
order_confirmed_mock.assert_called_once_with(order)
-def test_checkout_complete_with_unavailable_variant(
+def test_checkout_complete_with_variant_without_price(
site_settings,
user_api_client,
checkout_with_item,
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 18e72fccfa..f3c0884951 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -174,6 +174,7 @@ class Checkout(CountableDjangoObjectType):
is_shipping_required = graphene.Boolean(
description="Returns True, if checkout requires shipping.", required=True
)
+ quantity = graphene.Int(required=True, description="The number of items purchased.")
lines = graphene.List(
CheckoutLine,
description=(
@@ -215,7 +216,6 @@ class Checkout(CountableDjangoObjectType):
"last_change",
"channel",
"note",
- "quantity",
"shipping_address",
"translated_discount_name",
"user",
@@ -273,6 +273,17 @@ class Checkout(CountableDjangoObjectType):
wrap_shipping_method_with_channel_context
)
+ @staticmethod
+ def resolve_quantity(root: models.Checkout, info):
+ checkout_info = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
+ root.token
+ )
+
+ def calculate_quantity(lines):
+ return sum([line_info.line.quantity for line_info in lines])
+
+ return checkout_info.then(calculate_quantity)
+
@staticmethod
@traced_resolver
# TODO: We should optimize it in/after PR#5819
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index db54d54e53..2c78e57247 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -99,6 +99,7 @@ class ProductBulkDelete(ModelBulkDeleteMutation):
error_type_field = "product_errors"
@classmethod
+ @transaction.atomic
def perform_mutation(cls, _root, info, ids, **data):
_, pks = resolve_global_ids_to_primary_keys(ids, Product)
product_to_variant = list(
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index 3a915a1760..4728d8a03d 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -7,6 +7,7 @@ from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.utils import IntegrityError
+from ....checkout.models import CheckoutLine
from ....core.permissions import ProductPermissions
from ....product.error_codes import CollectionErrorCode, ProductErrorCode
from ....product.models import CollectionChannelListing
@@ -235,6 +236,19 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
).exists():
product_channel_listing.delete()
+ cls.perform_checkout_lines_delete(variants, [channel.id])
+
+ @classmethod
+ def perform_checkout_lines_delete(cls, variants, channel_id):
+ lines_id_and_checkout_id = list(
+ CheckoutLine.objects.filter(
+ variant__in=variants, checkout__channel__id__in=channel_id
+ ).values("id", "checkout__pk")
+ )
+ lines_ids = {line["id"] for line in lines_id_and_checkout_id}
+
+ CheckoutLine.objects.filter(id__in=lines_ids).delete()
+
@classmethod
def remove_channels(cls, product: "ProductModel", remove_channels: List[Dict]):
ProductChannelListing.objects.filter(
@@ -243,6 +257,8 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
ProductVariantChannelListing.objects.filter(
variant__product_id=product.pk, channel_id__in=remove_channels
).delete()
+ variant_ids = product.variants.all().values_list("id", flat=True)
+ cls.perform_checkout_lines_delete(variant_ids, remove_channels)
@classmethod
@transaction.atomic()
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 051baf71d5..172ce459aa 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -5,8 +5,11 @@ import pytest
from django.utils import timezone
from prices import Money, TaxedMoney
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity
from ....order import OrderStatus
from ....order.models import OrderLine
+from ....plugins.manager import get_plugins_manager
from ....product.models import (
Category,
Collection,
@@ -443,7 +446,7 @@ def test_delete_products_with_images(
assert {
call_args.args[0] for call_args in delete_versatile_image_mock.call_args_list
} == {media1.image, media2.image}
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")
@@ -474,7 +477,41 @@ def test_delete_products_trigger_webhook(
assert content["data"]["productBulkDelete"]["count"] == 3
assert mocked_webhook_trigger.called
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
+
+
+def test_delete_products_removes_checkout_lines(
+ staff_api_client,
+ product_list,
+ checkout_with_items,
+ permission_manage_products,
+ channel_USD,
+ settings,
+):
+ # given
+ checkout = checkout_with_items
+ lines_count = checkout.lines.count()
+ lines = fetch_checkout_lines(checkout)
+ old_quantity = calculate_checkout_quantity(lines)
+
+ query = DELETE_PRODUCTS_MUTATION
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("Product", product.id)
+ for product in product_list
+ ]
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["productBulkDelete"]["count"] == 3
+
+ checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == lines_count - 3
+ assert old_quantity == calculate_checkout_quantity(lines) + 3
@patch("saleor.order.tasks.recalculate_orders_task.delay")
@@ -608,7 +645,51 @@ def test_delete_product_variants(
product_variant_deleted_webhook_mock.call_count
== content["data"]["productVariantBulkDelete"]["count"]
)
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
+
+
+def test_delete_product_variants_removes_checkout_lines(
+ staff_api_client,
+ checkout,
+ product_list,
+ permission_manage_products,
+):
+ query = PRODUCT_VARIANT_BULK_DELETE_MUTATION
+
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ variant_list = [product.variants.first() for product in product_list][:2]
+ for variant in variant_list:
+ add_variant_to_checkout(checkout_info, variant, 1)
+
+ lines_count = checkout.lines.count()
+ lines = fetch_checkout_lines(checkout)
+ old_quantity = calculate_checkout_quantity(lines)
+
+ assert ProductVariantChannelListing.objects.filter(
+ variant_id__in=[variant.id for variant in variant_list]
+ ).exists()
+
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("ProductVariant", variant.id)
+ for variant in variant_list
+ ]
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ flush_post_commit_hooks()
+
+ assert content["data"]["productVariantBulkDelete"]["count"] == 2
+ assert not ProductVariant.objects.filter(
+ id__in=[variant.id for variant in variant_list]
+ ).exists()
+ checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
+
+ assert checkout.lines.count() == lines_count - 2
+ assert old_quantity == calculate_checkout_quantity(lines) + 2
@patch("saleor.product.signals.delete_versatile_image")
@@ -660,7 +741,7 @@ def test_delete_product_variants_with_images(
product_variant_deleted_webhook_mock.call_count
== content["data"]["productVariantBulkDelete"]["count"]
)
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
delete_versatile_image_mock.assert_not_called()
@@ -808,7 +889,7 @@ def test_delete_product_variants_delete_default_variant(
product.refresh_from_db()
assert product.default_variant.pk == new_default_variant.pk
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
@patch("saleor.order.tasks.recalculate_orders_task.delay")
@@ -858,7 +939,7 @@ def test_delete_product_variants_delete_all_product_variants(
product.refresh_from_db()
assert product.default_variant is None
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
@patch("saleor.order.tasks.recalculate_orders_task.delay")
@@ -910,4 +991,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
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 3b16e858f2..b67b8da4a5 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -6100,7 +6100,7 @@ def test_delete_product(
with pytest.raises(product._meta.model.DoesNotExist):
product.refresh_from_db()
assert node_id == data["product"]["id"]
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
@patch("saleor.product.signals.delete_versatile_image")
@@ -6145,7 +6145,7 @@ def test_delete_product_with_image(
assert {
call_args.args[0] for call_args in delete_versatile_image_mock.call_args_list
} == set(images)
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")
@@ -6179,7 +6179,38 @@ def test_delete_product_trigger_webhook(
mocked_webhook_trigger.assert_called_once_with(
WebhookEventType.PRODUCT_DELETED, expected_data
)
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
+
+
+def test_delete_product_removes_checkout_lines(
+ staff_api_client,
+ checkout_with_items,
+ permission_manage_products,
+ settings,
+):
+ query = DELETE_PRODUCT_MUTATION
+ checkout = checkout_with_items
+ line = checkout.lines.first()
+ product = line.variant.product
+ node_id = graphene.Node.to_global_id("Product", product.id)
+ variables = {"id": node_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productDelete"]
+ assert data["product"]["name"] == product.name
+
+ with pytest.raises(product._meta.model.DoesNotExist):
+ product.refresh_from_db()
+
+ with pytest.raises(line._meta.model.DoesNotExist):
+ line.refresh_from_db()
+ assert checkout.lines.all().exists()
+
+ checkout.refresh_from_db()
+
+ assert node_id == data["product"]["id"]
@patch("saleor.order.tasks.recalculate_orders_task.delay")
diff --git a/saleor/graphql/product/tests/test_product_channel_listing_update.py b/saleor/graphql/product/tests/test_product_channel_listing_update.py
index 287d358d9f..cb1076e3a1 100644
--- a/saleor/graphql/product/tests/test_product_channel_listing_update.py
+++ b/saleor/graphql/product/tests/test_product_channel_listing_update.py
@@ -4,6 +4,9 @@ from unittest.mock import patch
import graphene
from freezegun import freeze_time
+from ....checkout.fetch import fetch_checkout_info
+from ....checkout.utils import add_variant_to_checkout
+from ....plugins.manager import get_plugins_manager
from ....product.error_codes import ProductErrorCode
from ....product.models import ProductVariant, ProductVariantChannelListing
from ....product.utils.costs import get_product_costs_data
@@ -929,6 +932,42 @@ def test_product_channel_listing_update_remove_channel(
assert variant.channel_listings.get() == variant_channel_listing_pln
+def test_product_channel_listing_update_remove_channel_removes_checkout_lines(
+ staff_api_client,
+ product_available_in_many_channels,
+ permission_manage_products,
+ checkout,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ product = product_available_in_many_channels
+ variant = product.variants.get()
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ add_variant_to_checkout(checkout_info, variant, 1)
+
+ assert checkout.lines.all().exists()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {"removeChannels": [channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ assert not data["errors"]
+ assert not checkout.lines.all().exists()
+
+
def test_product_channel_listing_update_remove_not_assigned_channel(
staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
):
@@ -1139,6 +1178,53 @@ def test_product_channel_listing_remove_variant_as_app(
assert len(variant.channel_listings.all()) == 1
+def test_product_channel_listing_remove_variant_removes_checkout_lines(
+ staff_api_client,
+ product,
+ permission_manage_products,
+ checkout,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ variant = product.variants.first()
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ add_variant_to_checkout(checkout_info, variant, 1)
+
+ assert checkout.lines.all().exists()
+
+ ProductVariantChannelListing.objects.create(channel=channel_PLN, variant=variant)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "updateChannels": [
+ {"channelId": channel_id, "removeVariants": [variant_id]}
+ ]
+ },
+ }
+
+ assert len(variant.channel_listings.all()) == 2
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ assert not data["errors"]
+
+ assert len(variant.channel_listings.all()) == 1
+
+ assert not checkout.lines.all().exists()
+
+
def test_product_channel_listing_add_variant_duplicated_ids_in_add_and_remove(
staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
):
diff --git a/saleor/graphql/product/tests/test_product_discounted_price.py b/saleor/graphql/product/tests/test_product_discounted_price.py
index 5885bf269e..2bfc8a4269 100644
--- a/saleor/graphql/product/tests/test_product_discounted_price.py
+++ b/saleor/graphql/product/tests/test_product_discounted_price.py
@@ -40,7 +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)
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_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 937c3e42c5..4289ff983e 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -2242,7 +2242,31 @@ def test_delete_variant(
assert data["productVariant"]["sku"] == variant.sku
with pytest.raises(variant._meta.model.DoesNotExist):
variant.refresh_from_db()
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
+
+
+def test_delete_variant_remove_checkout_lines(
+ staff_api_client,
+ checkout_with_items,
+ permission_manage_products,
+):
+ query = DELETE_VARIANT_MUTATION
+ line = checkout_with_items.lines.first()
+ variant = line.variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ flush_post_commit_hooks()
+ data = content["data"]["productVariantDelete"]
+
+ assert data["productVariant"]["sku"] == variant.sku
+ with pytest.raises(variant._meta.model.DoesNotExist):
+ variant.refresh_from_db()
+ with pytest.raises(line._meta.model.DoesNotExist):
+ line.refresh_from_db()
@patch("saleor.product.signals.delete_versatile_image")
@@ -2275,7 +2299,7 @@ def test_delete_variant_with_image(
assert data["productVariant"]["sku"] == variant.sku
with pytest.raises(variant._meta.model.DoesNotExist):
variant.refresh_from_db()
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
delete_versatile_image_mock.assert_not_called()
@@ -2384,7 +2408,7 @@ def test_delete_default_variant(
product.refresh_from_db()
assert product.default_variant.pk == second_variant.pk
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
@patch("saleor.order.tasks.recalculate_orders_task.delay")
@@ -2423,7 +2447,7 @@ def test_delete_not_default_variant_left_default_variant_unchanged(
product.refresh_from_db()
assert product.default_variant.pk == default_variant.pk
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
@patch("saleor.order.tasks.recalculate_orders_task.delay")
@@ -2460,7 +2484,7 @@ def test_delete_default_all_product_variant_left_product_default_variant_unset(
product.refresh_from_db()
assert not product.default_variant
- mocked_recalculate_orders_task.assert_not_called
+ mocked_recalculate_orders_task.assert_not_called()
def _fetch_all_variants(client, variables={}, permissions=None):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 928c5a8c6a..88dadc3906 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -887,7 +887,6 @@ type Checkout implements Node & ObjectWithMetadata {
created: DateTime!
lastChange: DateTime!
user: User
- quantity: Int!
channel: Channel!
billingAddress: Address
shippingAddress: Address
@@ -904,6 +903,7 @@ type Checkout implements Node & ObjectWithMetadata {
availablePaymentGateways: [PaymentGateway!]!
email: String!
isShippingRequired: Boolean!
+ quantity: Int!
lines: [CheckoutLine]
shippingPrice: TaxedMoney
shippingMethod: ShippingMethod