Skip to content

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

Adding to checkout now ensures the user doesn't add too many

NyanKiyoshid3b804dfc5a7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e6db082696..a910b00e82 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add bulk actions - #3955 by @dominik-zeglen
- Update file field styles with materializecss template filter - #3998 by @zodiacfireworks
- Add filtering interface for graphQL API - #3952 by @korycins
+- Ensure adding to checkout is respecting the limits set, so the user doesn't add too many - #4005 by @NyanKiyoshi
## 2.5.0
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.py
index b4317591e3..a08b6b4cfa 100644
--- a/saleor/checkout/forms.py
+++ b/saleor/checkout/forms.py
@@ -1,5 +1,6 @@
"""Checkout-related forms and fields."""
from datetime import date
+from typing import Any
from django import forms
from django.conf import settings
@@ -44,6 +45,9 @@ class AddToCheckoutForm(forms.Form):
'empty-stock': pgettext_lazy(
'Add to checkout form error',
'Sorry. This product is currently out of stock.'),
+ 'variant-too-many-in-checkout': pgettext_lazy(
+ 'Add to checkout form error',
+ 'Sorry. You can\'t add more than %d times this item.'),
'variant-does-not-exists': pgettext_lazy(
'Add to checkout form error', 'Oops. We could not find that product.'),
'insufficient-stock': npgettext_lazy(
@@ -57,6 +61,9 @@ class AddToCheckoutForm(forms.Form):
self.taxes = kwargs.pop('taxes', {})
super().__init__(*args, **kwargs)
+ def add_error_i18n(self, field, error_name, fmt: Any=tuple()):
+ self.add_error(field, self.error_messages[error_name] % fmt)
+
def clean(self):
"""Clean the form.
@@ -70,22 +77,28 @@ class AddToCheckoutForm(forms.Form):
try:
variant = self.get_variant(cleaned_data)
except ObjectDoesNotExist:
- msg = self.error_messages['variant-does-not-exists']
- self.add_error(NON_FIELD_ERRORS, msg)
+ self.add_error_i18n(NON_FIELD_ERRORS, 'variant-does-not-exists')
else:
line = self.checkout.get_line(variant)
used_quantity = line.quantity if line else 0
new_quantity = quantity + used_quantity
+
+ if new_quantity > settings.MAX_CHECKOUT_LINE_QUANTITY:
+ self.add_error_i18n(
+ 'quantity',
+ 'variant-too-many-in-checkout',
+ settings.MAX_CHECKOUT_LINE_QUANTITY)
+ return cleaned_data
+
try:
variant.check_quantity(new_quantity)
except InsufficientStock as e:
remaining = e.item.quantity_available - used_quantity
if remaining:
- msg = self.error_messages['insufficient-stock']
- self.add_error('quantity', msg % remaining)
+ self.add_error_i18n(
+ 'quantity', 'insufficient-stock', remaining)
else:
- msg = self.error_messages['empty-stock']
- self.add_error('quantity', msg)
+ self.add_error_i18n('quantity', 'empty-stock')
return cleaned_data
def save(self):
diff --git a/tests/conftest.py b/tests/conftest.py
index 10427a5a82..8790da89e2 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -141,6 +141,11 @@ def customer_user(address): # pylint: disable=W0613
return user
+def user_checkout(customer_user):
+ return Checkout.objects.get_or_create(user=customer_user)[0]
+
+
@pytest.fixture
def request_checkout(checkout, monkeypatch):
# FIXME: Fixtures should not have any side effects
diff --git a/tests/settings.py b/tests/settings.py
index baf99922fc..4d67c8e29b 100644
--- a/tests/settings.py
+++ b/tests/settings.py
@@ -34,3 +34,4 @@ CHECKOUT_PAYMENT_GATEWAYS = {
COUNTRIES_ONLY = None
MEDIA_ROOT = None
+MAX_CHECKOUT_LINE_QUANTITY = 50
diff --git a/tests/test_cart.py b/tests/test_cart.py
index 5c72e950ef..5a5d61c9d8 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -43,11 +43,6 @@ def anonymous_checkout(db):
return Checkout.objects.get_or_create(user=None)[0]
-def user_checkout(customer_user):
- return Checkout.objects.get_or_create(user=customer_user)[0]
-
-
@pytest.fixture()
def local_currency(monkeypatch):
def side_effect(price, currency):
diff --git a/tests/test_product.py b/tests/test_product.py
index 51111d2a6d..d926b17542 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -8,6 +8,7 @@ from unittest.mock import patch
import pytest
from django.core import serializers
from django.core.serializers.base import DeserializationError
+from django.http import JsonResponse
from django.urls import reverse
from freezegun import freeze_time
from prices import Money, TaxedMoney, TaxedMoneyRange
@@ -191,16 +192,44 @@ def test_view_invalid_add_to_checkout(client, product, request_checkout):
assert request_checkout.quantity == 2
-def test_view_add_to_checkout(client, product, request_checkout_with_item):
- variant = request_checkout_with_item.lines.get().variant
- response = client.post(
- reverse(
- 'product:add-to-checkout',
- kwargs={'slug': product.get_slug(),
- 'product_id': product.pk}),
- {'quantity': 1, 'variant': variant.pk})
- assert response.status_code == 302
- assert request_checkout_with_item.quantity == 1
+def test_view_add_to_checkout(authorized_client, product, user_checkout):
+ variant = product.variants.first()
+
+ # Ignore stock
+ variant.track_inventory = False
+ variant.save()
+
+ # Add the variant to the user checkout and retrieve the variant line
+ add_variant_to_checkout(user_checkout, variant)
+ checkout_line = user_checkout.lines.last()
+
+ # Retrieve the test url
+ checkout_url = reverse(
+ 'product:add-to-checkout',
+ kwargs={'slug': product.get_slug(),
+ 'product_id': product.pk})
+
+ # Attempt to set the quantity to 50
+ response = authorized_client.post(
+ checkout_url,
+ {'quantity': 49, 'variant': variant.pk},
+ HTTP_X_REQUESTED_WITH='XMLHttpRequest') # type: JsonResponse
+ assert response.status_code == 200
+
+ # Ensure the line quantity was updated to 50
+ checkout_line.refresh_from_db(fields=['quantity'])
+ assert checkout_line.quantity == 50
+
+ # Attempt to increase the quantity to a too high count
+ response = authorized_client.post(
+ checkout_url,
+ {'quantity': 1, 'variant': variant.pk},
+ HTTP_X_REQUESTED_WITH='XMLHttpRequest')
+ assert response.status_code == 400
+
+ # Ensure the line quantity was not updated to 51
+ checkout_line.refresh_from_db(fields=['quantity'])
+ assert checkout_line.quantity == 50
def test_adding_to_checkout_with_current_user_token(