Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add quantity_limit_per_customer field to ProductVariant (#8405)
Paweł Kucharski7d17f979dd56
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ab0ace775f..3cc2a08df0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,7 @@ All notable, unreleased changes to this project will be documented in this file.- Reserve stocks for checkouts - #7589 by @rafalp- Add `variant_selection` to `ProductAttributeAssign` operations - #8235 by @kuchichan- Add query complexity limit to GraphQL API - #8526 by rafalp+- Add `quantity_limit_per_customer` field to ProductVariant #8405 by @kuchichan# 3.0.0 [Unreleased]diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 0865a39667..5d1226dbb4 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -261,7 +261,8 @@ def _create_lines_for_order(country_code,quantities,checkout_info.channel.slug,- additional_warehouse_lookup,+ global_quantity_limit=None,+ additional_filter_lookup=additional_warehouse_lookup,existing_lines=lines,replace=True,check_reservations=check_reservations,diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 66c920d851..4d301e290d 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -163,6 +163,7 @@ def add_variants_to_checkout(Otherwise, quantity will be added or replaced (if replace argument is True)."""country_code = checkout.get_country()+checkout_lines = checkout.lines.select_related("variant")variant_ids_in_lines = {line.variant_id: line for line in checkout_lines}to_create = []diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex d1fd6c88d9..003b45ffc8 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -1,6 +1,7 @@import datetimeimport uuid-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union+from collections import defaultdict+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Unionimport graphenefrom django.conf import settings@@ -140,6 +141,7 @@ def check_lines_quantity(quantities,country,channel_slug,+ global_quantity_limit,allow_zero_quantity=False,existing_lines=None,replace=False,@@ -173,23 +175,13 @@ def check_lines_quantity()})-- if quantity > settings.MAX_CHECKOUT_LINE_QUANTITY:- raise ValidationError(- {- "quantity": ValidationError(- "Cannot add more than %d times this item."- "" % settings.MAX_CHECKOUT_LINE_QUANTITY,- code=CheckoutErrorCode.QUANTITY_GREATER_THAN_LIMIT,- )- }- )try:check_stock_and_preorder_quantity_bulk(variants,country,quantities,channel_slug,+ global_quantity_limit,existing_lines=existing_lines,replace=replace,check_reservations=check_reservations,@@ -273,6 +265,15 @@ def get_checkout_by_token(token: uuid.UUID, prefetch_lookups: Iterable[str] = []return checkout+def group_quantity_by_variants(lines: List[Dict[str, Any]]) -> List[int]:+ variant_quantity_map: Dict[str, int] = defaultdict(int)++ for quantity, variant_id in (line.values() for line in lines):+ variant_quantity_map[variant_id] += quantity++ return list(variant_quantity_map.values())++class CheckoutLineInput(graphene.InputObjectType):quantity = graphene.Int(required=True, description="The number of items purchased.")variant_id = graphene.ID(required=True, description="ID of the product variant.")@@ -341,7 +342,8 @@ class CheckoutCreate(ModelMutation, I18nMixin):),)- quantities = [line["quantity"] for line in lines]+ quantities = group_quantity_by_variants(lines)+variant_db_ids = {variant.id for variant in variants}validate_variants_available_for_purchase(variant_db_ids, channel.id)validate_variants_available_in_channel(@@ -353,6 +355,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):quantities,country,channel.slug,+ info.context.site.settings.limit_quantity_per_checkout,check_reservations=is_reservation_enabled(info.context.site.settings),)return variants, quantities@@ -429,7 +432,6 @@ class CheckoutCreate(ModelMutation, I18nMixin):# Set checkout countrycountry = cleaned_input["country"]instance.set_country(country)-# Create checkout lineschannel = cleaned_input["channel"]variants = cleaned_input.get("variants")@@ -440,6 +442,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):variants,quantities,channel.slug,+ info.context.site.settings.limit_quantity_per_checkout,reservation_length=get_reservation_length(info.context),)@@ -506,13 +509,20 @@ class CheckoutLinesAdd(BaseMutation):@classmethoddef validate_checkout_lines(- cls, info, variants, quantities, country, channel_slug, lines=None+ cls,+ info,+ variants,+ quantities,+ country,+ channel_slug,+ lines=None,):check_lines_quantity(variants,quantities,country,channel_slug,+ info.context.site.settings.limit_quantity_per_checkout,existing_lines=lines,check_reservations=is_reservation_enabled(info.context.site.settings),)@@ -607,7 +617,7 @@ class CheckoutLinesAdd(BaseMutation):variant_ids = [line.get("variant_id") for line in lines]variants = cls.get_nodes_or_error(variant_ids, "variant_id", ProductVariant)- quantities = [line.get("quantity") for line in lines]+ input_quantities = group_quantity_by_variants(lines)checkout_info = fetch_checkout_info(checkout, [], discounts, manager)@@ -616,7 +626,7 @@ class CheckoutLinesAdd(BaseMutation):info,checkout,variants,- quantities,+ input_quantities,checkout_info,lines,manager,@@ -666,6 +676,7 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):quantities,country,channel_slug,+ info.context.site.settings.limit_quantity_per_checkout,allow_zero_quantity=True,existing_lines=lines,replace=True,@@ -949,6 +960,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):quantities,country,channel_slug,+ info.context.site.settings.limit_quantity_per_checkout,# Set replace=True to avoid existing_lines and quantities from# being counted twice by the check_stock_quantity_bulkreplace=True,diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 7adf29deba..914f00c961 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -785,7 +785,7 @@ def test_checkout_create_with_variant_without_inventory_tracking(),(51,- "Cannot add more than 50 times this item.",+ "Cannot add more than 50 times this item: SKU_A.",CheckoutErrorCode.QUANTITY_GREATER_THAN_LIMIT,),),@@ -1233,6 +1233,130 @@ def test_checkout_create_check_lines_quantity(assert data["errors"][0]["field"] == "quantity"[email protected]("is_preorder", [True, False])+def test_checkout_create_check_lines_quantity_when_limit_per_variant_is_set_raise_err(+ user_api_client, stock, graphql_address_data, channel_USD, is_preorder+):+ limit_per_customer = 5+ variant = stock.product_variant+ variant.quantity_limit_per_customer = limit_per_customer+ variant.is_preorder = is_preorder+ variant.preorder_end_date = timezone.now() + datetime.timedelta(days=1)+ variant.save(+ update_fields=[+ "quantity_limit_per_customer",+ "is_preorder",+ "preorder_end_date",+ ]+ )+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ shipping_address = graphql_address_data+ test_email = "[email protected]"+ variables = {+ "checkoutInput": {+ "lines": [{"quantity": 6, "variantId": variant_id}],+ "email": test_email,+ "shippingAddress": shipping_address,+ "channel": channel_USD.slug,+ }+ }+ assert not Checkout.objects.exists()++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutCreate"]++ assert data["errors"][0]["message"] == (+ f"Cannot add more than {limit_per_customer} times this item: {variant}."+ )+ assert data["errors"][0]["field"] == "quantity"++[email protected]("is_preorder", [True, False])+def test_checkout_create_check_lines_quantity_respects_site_settings(+ user_api_client,+ stock,+ graphql_address_data,+ channel_USD,+ site_settings,+ is_preorder,+):+ global_limit = 5+ variant = stock.product_variant+ variant.is_preorder = is_preorder+ variant.preorder_end_date = timezone.now() + datetime.timedelta(days=1)+ variant.save(+ update_fields=[+ "is_preorder",+ "preorder_end_date",+ ]+ )+ site_settings.limit_quantity_per_checkout = global_limit+ site_settings.save(update_fields=["limit_quantity_per_checkout"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ shipping_address = graphql_address_data+ test_email = "[email protected]"+ variables = {+ "checkoutInput": {+ "lines": [{"quantity": 6, "variantId": variant_id}],+ "email": test_email,+ "shippingAddress": shipping_address,+ "channel": channel_USD.slug,+ }+ }+ assert not Checkout.objects.exists()++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutCreate"]++ assert data["errors"][0]["message"] == (+ f"Cannot add more than {global_limit} times this item: {variant}."+ )+ assert data["errors"][0]["field"] == "quantity"++[email protected]("is_preorder", [True, False])+def test_checkout_create_check_lines_quantity_site_settings_no_limit(+ user_api_client,+ stock,+ graphql_address_data,+ channel_USD,+ site_settings,+ is_preorder,+):+ variant = stock.product_variant+ variant.is_preorder = is_preorder+ variant.preorder_end_date = timezone.now() + datetime.timedelta(days=1)+ variant.save(+ update_fields=[+ "is_preorder",+ "preorder_end_date",+ ]+ )+ site_settings.limit_quantity_per_checkout = None+ site_settings.save(update_fields=["limit_quantity_per_checkout"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ shipping_address = graphql_address_data+ test_email = "[email protected]"+ variables = {+ "checkoutInput": {+ "lines": [{"quantity": 15, "variantId": variant_id}],+ "email": test_email,+ "shippingAddress": shipping_address,+ "channel": channel_USD.slug,+ }+ }+ assert not Checkout.objects.exists()++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutCreate"]++ assert not data["errors"]+ assert Checkout.objects.first()++def test_checkout_create_check_lines_quantity_against_reservations(site_settings_with_reservations,user_api_client,diff --git a/saleor/graphql/checkout/tests/test_checkout_lines.py b/saleor/graphql/checkout/tests/test_checkout_lines.pyindex bf2dc178f4..1d640dafb9 100644--- a/saleor/graphql/checkout/tests/test_checkout_lines.py+++ b/saleor/graphql/checkout/tests/test_checkout_lines.py@@ -17,7 +17,10 @@ from ....warehouse import WarehouseClickAndCollectOptionfrom ....warehouse.models import Reservation, Stockfrom ....warehouse.tests.utils import get_available_quantity_for_stockfrom ...tests.utils import get_graphql_content-from ..mutations import update_checkout_shipping_method_if_invalid+from ..mutations import (+ group_quantity_by_variants,+ update_checkout_shipping_method_if_invalid,+)MUTATION_CHECKOUT_LINES_ADD = """mutation checkoutLinesAdd(@@ -498,7 +501,42 @@ def test_checkout_lines_add_too_many(user_api_client, checkout_with_item, stock)assert content["errors"] == [{"field": "quantity",- "message": "Cannot add more than 50 times this item.",+ "message": "Cannot add more than 50 times this item: SKU_A.",+ "code": "QUANTITY_GREATER_THAN_LIMIT",+ "variants": None,+ }+ ]++[email protected]("is_preorder", [True, False])+def test_checkout_lines_add_too_many_after_two_trials(+ user_api_client, checkout_with_item, stock, is_preorder+):+ variant = stock.product_variant+ variant.is_preorder = is_preorder+ variant.preorder_end_date = timezone.now() + datetime.timedelta(days=1)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stock.quantity = 200+ stock.save(update_fields=["quantity"])+ variant.save(update_fields=["is_preorder", "preorder_end_date"])++ variables = {+ "token": checkout_with_item.token,+ "lines": [{"variantId": variant_id, "quantity": 26}],+ "channelSlug": checkout_with_item.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)["data"]["checkoutLinesAdd"]++ assert not content["errors"]++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)["data"]["checkoutLinesAdd"]++ assert content["errors"] == [+ {+ "field": "quantity",+ "message": "Cannot add more than 50 times this item: SKU_A.","code": "QUANTITY_GREATER_THAN_LIMIT","variants": None,}@@ -1223,3 +1261,48 @@ def tests_checkout_lines_delete_invalid_lines_ids(user_api_client, checkout_withassert errors["code"] == CheckoutErrorCode.INVALID.nameassert errors["lines"] == lines_list[1:]assert errors["field"] == "lineId"+++ "lines, expected",+ [+ (+ [+ {"quantity": 6, "variantId": "abc"},+ {"quantity": 6, "variantId": "abc"},+ {"quantity": 1, "variantId": "def"},+ {"quantity": 1, "variantId": "def"},+ ],+ [12, 2],+ ),+ (+ [+ {"quantity": 8, "variantId": "ghi"},+ {"quantity": 2, "variantId": "ghi"},+ {"quantity": 6, "variantId": "abc"},+ {"quantity": 1, "variantId": "def"},+ {"quantity": 6, "variantId": "abc"},+ {"quantity": 1, "variantId": "def"},+ {"quantity": 8, "variantId": "ghi"},+ {"quantity": 2, "variantId": "ghi"},+ {"quantity": 922, "variantId": "xyz"},+ {"quantity": 6, "variantId": "abc"},+ {"quantity": 1, "variantId": "def"},+ {"quantity": 6, "variantId": "abc"},+ {"quantity": 1, "variantId": "def"},+ {"quantity": 1000, "variantId": "jkl"},+ {"quantity": 999, "variantId": "zzz"},+ ],+ [20, 24, 4, 922, 1000, 999],+ ),+ (+ [+ {"quantity": 100, "variantId": name}+ for name in (l1 + l2 for l1 in "abcdef" for l2 in "ghijkl")+ ],+ [100] * 36,+ ),+ ],+)+def test_group_by_variants(lines, expected):+ assert expected == group_quantity_by_variants(lines)diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex cf24cf0ce8..5f073bc640 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -776,6 +776,13 @@ class ProductVariantInput(graphene.InputObjectType):preorder = PreorderSettingsInput(description=f"{ADDED_IN_31} Determines if variant is in preorder.")+ quantity_limit_per_customer = graphene.Int(+ required=False,+ description=(+ f"{ADDED_IN_31} Determines maximum quantity of `ProductVariant`,"+ "that can be bought in a single checkout."+ ),+ )class ProductVariantCreateInput(ProductVariantInput):@@ -861,6 +868,20 @@ class ProductVariantCreate(ModelMutation):})+ quantity_limit_per_customer = cleaned_input.get("quantity_limit_per_customer")+ if quantity_limit_per_customer is not None and quantity_limit_per_customer < 1:+ raise ValidationError(+ {+ "quantity_limit_per_customer": ValidationError(+ (+ "Product variant can't have "+ "quantity_limit_per_customer lower than 1."+ ),+ code=ProductErrorCode.INVALID.value,+ )+ }+ )+stocks = cleaned_input.get("stocks")if stocks:cls.check_for_duplicates_in_stocks(stocks)diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex 59ffaf3134..a6f946d9a7 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -1912,6 +1912,7 @@ def test_update_product_variant(mutation updateVariant ($id: ID!,$sku: String!,+ $quantityLimitPerCustomer: Int!$trackInventory: Boolean!,$attributes: [AttributeValueInput!]) {productVariantUpdate(@@ -1920,10 +1921,12 @@ def test_update_product_variant(sku: $sku,trackInventory: $trackInventory,attributes: $attributes,+ quantityLimitPerCustomer: $quantityLimitPerCustomer,}) {productVariant {namesku+ quantityLimitPerCustomerchannelListings {channel {slug@@ -1938,11 +1941,13 @@ def test_update_product_variant(variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)sku = "test sku"+ quantity_limit_per_customer = 5variables = {"id": variant_id,"sku": sku,"trackInventory": True,+ "quantityLimitPerCustomer": quantity_limit_per_customer,"attributes": [{"id": attribute_id, "values": ["S"]}],}@@ -1956,6 +1961,7 @@ def test_update_product_variant(assert data["name"] == variant.nameassert data["sku"] == sku+ assert data["quantityLimitPerCustomer"] == quantity_limit_per_customerproduct_variant_updated_webhook_mock.assert_called_once_with(product.variants.last())@@ -2001,6 +2007,43 @@ def test_update_product_variant_with_negative_weight(assert error["code"] == ProductErrorCode.INVALID.name[email protected]("quantity_value", [0, -10])+def test_update_product_variant_limit_per_customer_lower_than_1(+ staff_api_client, product, permission_manage_products, quantity_value+):+ query = """+ mutation updateVariant (+ $id: ID!,+ $quantityLimitPerCustomer: Int+ ) {+ productVariantUpdate(+ id: $id,+ input: {+ quantityLimitPerCustomer: $quantityLimitPerCustomer,+ }+ ){+ errors {+ field+ message+ code+ }+ }+ }+ """+ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {"id": variant_id, "quantityLimitPerCustomer": quantity_value}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ variant.refresh_from_db()+ content = get_graphql_content(response)+ data = content["data"]["productVariantUpdate"]+ error = data["errors"][0]+ assert error["field"] == "quantityLimitPerCustomer"+ assert error["code"] == ProductErrorCode.INVALID.name++QUERY_UPDATE_VARIANT_SKU = """mutation updateVariant ($id: ID!,diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.pyindex 56bfaee60d..943def2eb6 100644--- a/saleor/graphql/product/tests/test_variant_availability.py+++ b/saleor/graphql/product/tests/test_variant_availability.py@@ -1,7 +1,7 @@from datetime import timedeltaimport graphene-from django.test import override_settings+import pytestfrom django.utils import timezonefrom django_countries import countries@@ -142,10 +142,11 @@ def test_variant_quantity_available_with_null_as_country_code(assert variant_data["byAddress"] == 7-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)def test_variant_quantity_available_with_max(- api_client, variant_with_many_stocks, settings, channel_USD+ api_client, variant_with_many_stocks, site_settings, channel_USD):+ site_settings.limit_quantity_per_checkout = 15+ site_settings.save(update_fields=["limit_quantity_per_checkout"])stock = variant_with_many_stocks.stocks.first()stock.quantity = 16stock.save(update_fields=["quantity"])@@ -157,8 +158,10 @@ def test_variant_quantity_available_with_max(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["deprecatedByCountry"] == settings.MAX_CHECKOUT_LINE_QUANTITY- assert variant_data["byAddress"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert (+ variant_data["deprecatedByCountry"] == site_settings.limit_quantity_per_checkout+ )+ assert variant_data["byAddress"] == site_settings.limit_quantity_per_checkoutdef test_variant_quantity_available_without_stocks(@@ -253,10 +256,11 @@ def test_variant_quantity_available_with_disabled_reservations(assert variant_data["byAddress"] == 7-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)def test_variant_quantity_available_without_inventory_tracking(- api_client, variant_with_many_stocks, settings, channel_USD+ api_client, variant_with_many_stocks, site_settings, channel_USD):+ site_settings.limit_quantity_per_checkout = 15+ site_settings.save(update_fields=["limit_quantity_per_checkout"])variant_with_many_stocks.track_inventory = Falsevariant_with_many_stocks.save(update_fields=["track_inventory"])variables = {@@ -267,14 +271,57 @@ def test_variant_quantity_available_without_inventory_tracking(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["deprecatedByCountry"] == settings.MAX_CHECKOUT_LINE_QUANTITY- assert variant_data["byAddress"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert (+ variant_data["deprecatedByCountry"] == site_settings.limit_quantity_per_checkout+ )+ assert variant_data["byAddress"] == site_settings.limit_quantity_per_checkout+++def test_variant_quantity_available_without_inventory_tracking_no_global_limit(+ api_client, variant_with_many_stocks, site_settings, channel_USD+):+ site_settings.limit_quantity_per_checkout = None+ site_settings.save(update_fields=["limit_quantity_per_checkout"])+ variant_with_many_stocks.track_inventory = False+ variant_with_many_stocks.save(update_fields=["track_inventory"])+ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),+ "country": COUNTRY_CODE,+ "channel": channel_USD.slug,+ }+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)+ content = get_graphql_content(response)+ variant_data = content["data"]["productVariant"]+ assert variant_data["deprecatedByCountry"] is None+ assert variant_data["byAddress"] is None-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)def test_variant_quantity_available_without_inventory_tracking_and_stocks(- api_client, variant, settings, channel_USD+ api_client, variant, site_settings, channel_USD+):+ site_settings.limit_quantity_per_checkout = 15+ site_settings.save(update_fields=["limit_quantity_per_checkout"])+ variant.track_inventory = False+ variant.save(update_fields=["track_inventory"])+ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "country": COUNTRY_CODE,+ "channel": channel_USD.slug,+ }+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)+ content = get_graphql_content(response)+ variant_data = content["data"]["productVariant"]+ assert (+ variant_data["deprecatedByCountry"] == site_settings.limit_quantity_per_checkout+ )+ assert variant_data["byAddress"] == site_settings.limit_quantity_per_checkout+++def test_variant_qty_available_without_inventory_tracking_and_stocks_no_global_limit(+ api_client, variant, site_settings, channel_USD):+ site_settings.limit_quantity_per_checkout = None+ site_settings.save(update_fields=["limit_quantity_per_checkout"])variant.track_inventory = Falsevariant.save(update_fields=["track_inventory"])variables = {@@ -285,16 +332,21 @@ def test_variant_quantity_available_without_inventory_tracking_and_stocks(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["deprecatedByCountry"] == settings.MAX_CHECKOUT_LINE_QUANTITY- assert variant_data["byAddress"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert variant_data["deprecatedByCountry"] is None+ assert variant_data["byAddress"] is None-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)[email protected]("global_limit", [15, None])def test_variant_quantity_available_preorder_with_channel_threshold(api_client,+ site_settings,preorder_variant_channel_threshold,channel_USD,+ global_limit,):+ site_settings.limit_quantity_per_checkout = global_limit+ site_settings.save(update_fields=["limit_quantity_per_checkout"])+variant = preorder_variant_channel_thresholdvariables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk),@@ -312,13 +364,15 @@ def test_variant_quantity_available_preorder_with_channel_threshold(assert variant_data["byAddress"] == channel_listing.preorder_quantity_threshold-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)def test_variant_quantity_available_preorder_without_reservations(site_settings_with_reservations,api_client,preorder_variant_channel_threshold,channel_USD,):+ site_settings_with_reservations.limit_quantity_per_checkout = 15+ site_settings_with_reservations.save(update_fields=["limit_quantity_per_checkout"])+variant = preorder_variant_channel_thresholdvariables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk),@@ -336,7 +390,6 @@ def test_variant_quantity_available_preorder_without_reservations(assert variant_data["byAddress"] == channel_listing.preorder_quantity_threshold-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)def test_variant_quantity_available_preorder_with_channel_threshold_and_reservation(site_settings_with_reservations,api_client,@@ -344,6 +397,9 @@ def test_variant_quantity_available_preorder_with_channel_threshold_and_reservatcheckout_line_with_reserved_preorder_item,channel_USD,):+ site_settings_with_reservations.limit_quantity_per_checkout = 15+ site_settings_with_reservations.save(update_fields=["limit_quantity_per_checkout"])+variant = preorder_variant_channel_thresholdvariables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk),@@ -363,10 +419,16 @@ def test_variant_quantity_available_preorder_with_channel_threshold_and_reservatassert variant_data["byAddress"] == available_quantity-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)[email protected]("global_limit", [15, None])def test_variant_quantity_available_preorder_with_global_threshold(- api_client, preorder_variant_global_threshold, channel_USD+ api_client,+ site_settings,+ preorder_variant_global_threshold,+ channel_USD,+ global_limit,):+ site_settings.limit_quantity_per_checkout = global_limit+ site_settings.save(update_fields=["limit_quantity_per_checkout"])variant = preorder_variant_global_thresholdvariables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk),@@ -380,13 +442,15 @@ def test_variant_quantity_available_preorder_with_global_threshold(assert variant_data["byAddress"] == variant.preorder_global_threshold-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)def test_variant_quantity_available_preorder_with_global_threshold_and_reservations(site_settings_with_reservations,api_client,checkout_line_with_reserved_preorder_item,channel_USD,):+ site_settings_with_reservations.limit_quantity_per_checkout = 15+ site_settings_with_reservations.save(update_fields=["limit_quantity_per_checkout"])+variant = checkout_line_with_reserved_preorder_item.variantvariant.channel_listings.update(preorder_quantity_threshold=None)variant.preorder_global_threshold = 10@@ -409,10 +473,17 @@ def test_variant_quantity_available_preorder_with_global_threshold_and_reservatiassert variant_data["byAddress"] == available_quantity-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)[email protected]("global_limit", [15, None])def test_variant_quantity_available_preorder_without_threshold(- api_client, preorder_variant_global_threshold, settings, channel_USD+ api_client,+ preorder_variant_global_threshold,+ site_settings,+ channel_USD,+ global_limit,):+ site_settings.limit_quantity_per_checkout = global_limit+ site_settings.save(update_fields=["limit_quantity_per_checkout"])+variant = preorder_variant_global_thresholdvariant.preorder_global_threshold = Nonevariant.save(update_fields=["preorder_global_threshold"])@@ -424,16 +495,21 @@ def test_variant_quantity_available_preorder_without_threshold(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["deprecatedByCountry"] == settings.MAX_CHECKOUT_LINE_QUANTITY- assert variant_data["byAddress"] == settings.MAX_CHECKOUT_LINE_QUANTITY++ assert (+ variant_data["deprecatedByCountry"] == site_settings.limit_quantity_per_checkout+ )+ assert variant_data["byAddress"] == site_settings.limit_quantity_per_checkout-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)def test_variant_quantity_available_preorder_without_channel(api_client,+ site_settings,preorder_variant_global_threshold,channel_USD,):+ site_settings.limit_quantity_per_checkout = 15+ site_settings.save(update_fields=["limit_quantity_per_checkout"])variant = preorder_variant_global_thresholdvariant.channel_listings.all().delete()variables = {diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex eb4e55e2bd..54ec5c4eca 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -1,9 +1,9 @@+import sysfrom collections import defaultdictfrom dataclasses import asdictfrom typing import List, Optionalimport graphene-from django.conf import settingsfrom django_countries.fields import Countryfrom graphene import relayfrom graphene_federation import key@@ -275,8 +275,13 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):),)quantity_available = graphene.Int(- required=True,- description="Quantity of a product available for sale in one checkout.",+ required=False,+ description=(+ "Quantity of a product available for sale in one checkout. "+ "Field value will be `null` when "+ "no `limitQuantityPerCheckout` in global settings has been set, and "+ "`productVariant` stocks are not tracked."+ ),address=destination_address_argument,country_code=graphene.Argument(CountryCodeEnum,@@ -300,7 +305,15 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):description = ("Represents a version of a product such as different size or color.")- only_fields = ["id", "name", "product", "sku", "track_inventory", "weight"]+ only_fields = [+ "id",+ "name",+ "product",+ "sku",+ "track_inventory",+ "weight",+ "quantity_limit_per_customer",+ ]interfaces = [relay.Node, ObjectWithMetadata]model = models.ProductVariant@@ -334,6 +347,10 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):if address is not None:country_code = address.country+ global_quantity_limit_per_checkout = (+ info.context.site.settings.limit_quantity_per_checkout+ )+if root.node.is_preorder_active():variant = root.nodechannel_listing = VariantChannelListingByVariantIdAndChannelSlugLoader(@@ -360,7 +377,7 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):channel_listing.preorder_quantity_threshold- channel_listing.preorder_quantity_allocated- reserved_quantity,- settings.MAX_CHECKOUT_LINE_QUANTITY,+ global_quantity_limit_per_checkout or sys.maxsize,),0,)@@ -372,7 +389,7 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):return min(channel_listing.preorder_quantity_threshold- channel_listing.preorder_quantity_allocated,- settings.MAX_CHECKOUT_LINE_QUANTITY,+ global_quantity_limit_per_checkout or sys.maxsize,)if variant.preorder_global_threshold is not None:variant_channel_listings = VariantChannelListingByVariantIdLoader(@@ -381,7 +398,7 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):def calculate_available_global(variant_channel_listings):if not variant_channel_listings:- return settings.MAX_CHECKOUT_LINE_QUANTITY+ return global_quantity_limit_per_checkoutglobal_sold_units = sum(channel_listing.preorder_quantity_allocatedfor channel_listing in variant_channel_listings@@ -407,7 +424,8 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):variant.preorder_global_threshold- global_sold_units- sum(reserved_quantities),- settings.MAX_CHECKOUT_LINE_QUANTITY,+ global_quantity_limit_per_checkout+ or sys.maxsize,),0,)@@ -418,17 +436,17 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):return min(variant.preorder_global_threshold - global_sold_units,- settings.MAX_CHECKOUT_LINE_QUANTITY,+ global_quantity_limit_per_checkout or sys.maxsize,)return variant_channel_listings.then(calculate_available_global)- return settings.MAX_CHECKOUT_LINE_QUANTITY+ return global_quantity_limit_per_checkoutreturn channel_listing.then(calculate_available_per_channel)if not root.node.track_inventory:- return settings.MAX_CHECKOUT_LINE_QUANTITY+ return global_quantity_limit_per_checkoutreturn AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(info.contextdiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex d5195db8dd..b165705d11 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -5709,6 +5709,7 @@ type ProductVariant implements Node & ObjectWithMetadata {sku: Stringproduct: Product!trackInventory: Boolean!+ quantityLimitPerCustomer: Intweight: WeightprivateMetadata: [MetadataItem]!metadata: [MetadataItem]!@@ -5724,7 +5725,7 @@ type ProductVariant implements Node & ObjectWithMetadata {translation(languageCode: LanguageCodeEnum!): ProductVariantTranslationdigitalContent: DigitalContentstocks(address: AddressInput, countryCode: CountryCode): [Stock]- quantityAvailable(address: AddressInput, countryCode: CountryCode): Int!+ quantityAvailable(address: AddressInput, countryCode: CountryCode): Intpreorder: PreorderData}@@ -5741,6 +5742,7 @@ input ProductVariantBulkCreateInput {trackInventory: Booleanweight: WeightScalarpreorder: PreorderSettingsInput+ quantityLimitPerCustomer: Intstocks: [StockInput!]channelListings: [ProductVariantChannelListingAddInput!]}@@ -5796,6 +5798,7 @@ input ProductVariantCreateInput {trackInventory: Booleanweight: WeightScalarpreorder: PreorderSettingsInput+ quantityLimitPerCustomer: Intproduct: ID!stocks: [StockInput!]}@@ -5819,6 +5822,7 @@ input ProductVariantInput {trackInventory: Booleanweight: WeightScalarpreorder: PreorderSettingsInput+ quantityLimitPerCustomer: Int}type ProductVariantPreorderDeactivate {@@ -6438,6 +6442,7 @@ type Shop {automaticFulfillmentDigitalProducts: BooleanreserveStockDurationAnonymousUser: IntreserveStockDurationAuthenticatedUser: Int+ limitQuantityPerCheckout: IntdefaultDigitalMaxDownloads: IntdefaultDigitalUrlValidDays: IntcompanyAddress: Address@@ -6499,6 +6504,7 @@ input ShopSettingsInput {customerSetPasswordUrl: StringreserveStockDurationAnonymousUser: IntreserveStockDurationAuthenticatedUser: Int+ limitQuantityPerCheckout: Int}type ShopSettingsTranslate {diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.pyindex 1baf8b2e8b..6cfe33a93d 100644--- a/saleor/graphql/shop/mutations.py+++ b/saleor/graphql/shop/mutations.py@@ -7,6 +7,7 @@ from ...core.permissions import GiftcardPermissions, OrderPermissions, SitePermifrom ...core.utils.url import validate_storefront_urlfrom ...site import GiftCardSettingsExpiryTypefrom ...site.error_codes import GiftCardSettingsErrorCode+from ...site.models import DEFAULT_LIMIT_QUANTITY_PER_CHECKOUTfrom ..account.i18n import I18nMixinfrom ..account.types import AddressInputfrom ..core.descriptions import ADDED_IN_31@@ -72,6 +73,13 @@ class ShopSettingsInput(graphene.InputObjectType):"authenticated checkout. Enter 0 or null to disable."))+ limit_quantity_per_checkout = graphene.Int(+ description=(+ f"{ADDED_IN_31} Default number of maximum line quantity "+ "in single checkout. Minimum possible value is 1, default "+ f"value is {DEFAULT_LIMIT_QUANTITY_PER_CHECKOUT}."+ )+ )class SiteDomainInput(graphene.InputObjectType):@@ -111,6 +119,19 @@ class ShopSettingsUpdate(BaseMutation):new_value = data["reserve_stock_duration_authenticated_user"]if not new_value or new_value < 1:data["reserve_stock_duration_authenticated_user"] = None+ if "limit_quantity_per_checkout" in data:+ new_value = data["limit_quantity_per_checkout"]+ if new_value is not None and new_value < 1:+ raise ValidationError(+ {+ "limit_quantity_per_checkout": ValidationError(+ "Quantity limit cannot be lower than 1.",+ code=ShopErrorCode.INVALID.value,+ )+ }+ )+ if not new_value:+ data["limit_quantity_per_checkout"] = Nonereturn datadiff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.pyindex 78f6ae9199..7340ffb830 100644--- a/saleor/graphql/shop/tests/test_shop.py+++ b/saleor/graphql/shop/tests/test_shop.py@@ -464,6 +464,69 @@ def test_shop_reservation_set_negative_settings_mutation(assert site_settings.reserve_stock_duration_authenticated_user is None[email protected]("quantity_value", [25, 1, None])+def test_limit_quantity_per_checkout_mutation(+ staff_api_client, site_settings, permission_manage_settings, quantity_value+):+ query = """+ mutation updateSettings($input: ShopSettingsInput!) {+ shopSettingsUpdate(input: $input) {+ shop {+ limitQuantityPerCheckout+ }+ errors {+ field,+ message+ }+ }+ }+ """+ variables = {"input": {"limitQuantityPerCheckout": quantity_value}}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_settings]+ )+ content = get_graphql_content(response)+ data = content["data"]["shopSettingsUpdate"]["shop"]+ site_settings.refresh_from_db()++ assert data["limitQuantityPerCheckout"] == quantity_value+ assert site_settings.limit_quantity_per_checkout == quantity_value++[email protected]("quantity_value", [0, -25])+def test_limit_quantity_per_checkout_neg_or_zero_value(+ staff_api_client, site_settings, permission_manage_settings, quantity_value+):+ query = """+ mutation updateSettings($input: ShopSettingsInput!) {+ shopSettingsUpdate(input: $input) {+ shop {+ limitQuantityPerCheckout+ }+ errors {+ field,+ message+ }+ }+ }+ """+ variables = {"input": {"limitQuantityPerCheckout": quantity_value}}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_settings]+ )+ content = get_graphql_content(response)+ errors = content["data"]["shopSettingsUpdate"]["errors"]+ site_settings.refresh_from_db()++ assert len(errors) == 1+ assert errors.pop() == {+ "field": "limitQuantityPerCheckout",+ "message": "Quantity limit cannot be lower than 1.",+ }++ assert site_settings.limit_quantity_per_checkout == 50 # default++MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS = """mutation updateDefaultSenderSettings($input: ShopSettingsInput!) {shopSettingsUpdate(input: $input) {diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex 8a8ecfdd28..942e7c9013 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -230,6 +230,13 @@ class Shop(graphene.ObjectType):))+ limit_quantity_per_checkout = graphene.Int(+ description=(+ f"{ADDED_IN_31} Default number of maximum line quantity in single checkout "+ "(per single checkout line)."+ )+ )+default_digital_max_downloads = graphene.Int(description="Default number of max downloads per digital content URL.")@@ -420,6 +427,12 @@ class Shop(graphene.ObjectType):site_settings = info.context.site.settingsreturn site_settings.reserve_stock_duration_authenticated_user+ @staticmethod+ @permission_required(SitePermissions.MANAGE_SETTINGS)+ def resolve_limit_quantity_per_checkout(_, info):+ site_settings = info.context.site.settings+ return site_settings.limit_quantity_per_checkout+@staticmethod@permission_required(SitePermissions.MANAGE_SETTINGS)def resolve_default_digital_max_downloads(_, info):diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex 63b60774ba..3d2bf94f8e 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -1,8 +1,8 @@+import sysfrom collections import defaultdictfrom typing import DefaultDict, Iterable, List, Optional, Tuplefrom uuid import UUID-from django.conf import settingsfrom django.db.models import Exists, OuterRef, Qfrom django.db.models.aggregates import Sumfrom django.db.models.functions import Coalesce@@ -41,7 +41,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(# a handful of unique countries but may access thousands of product variants# so it's cheaper to execute one query per country.variants_by_country_and_channel: DefaultDict[- CountryCode, List[int]+ Tuple[CountryCode, str], List[int]] = defaultdict(list)for variant_id, country_code, channel_slug in keys:variants_by_country_and_channel[(country_code, channel_slug)].append(@@ -153,10 +153,13 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(# Return the quantities after capping them at the maximum quantity allowed in# checkout. This prevent users from tracking the store's precise stock levels.+ global_quantity_limit = (+ self.context.site.settings.limit_quantity_per_checkout # type: ignore+ )return [(variant_id,- min(quantity_map[variant_id], settings.MAX_CHECKOUT_LINE_QUANTITY),+ min(quantity_map[variant_id], global_quantity_limit or sys.maxsize),)for variant_id in variant_ids]diff --git a/saleor/product/migrations/0154_productvariant_quantity_limit_per_customer.py b/saleor/product/migrations/0154_productvariant_quantity_limit_per_customer.pynew file mode 100644index 0000000000..7a2ec25b2b--- /dev/null+++ b/saleor/product/migrations/0154_productvariant_quantity_limit_per_customer.py@@ -0,0 +1,23 @@+# Generated by Django 3.2.7 on 2021-10-20 07:13++import django.core.validators+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0153_merge_20211006_0910"),+ ]++ operations = [+ migrations.AddField(+ model_name="productvariant",+ name="quantity_limit_per_customer",+ field=models.IntegerField(+ blank=True,+ null=True,+ validators=[django.core.validators.MinValueValidator(1)],+ ),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 038715f198..b13451b56a 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -7,6 +7,7 @@ from django.conf import settingsfrom django.contrib.postgres.aggregates import StringAggfrom django.contrib.postgres.indexes import GinIndexfrom django.contrib.postgres.search import SearchVectorField+from django.core.validators import MinValueValidatorfrom django.db import modelsfrom django.db.models import JSONField # type: ignorefrom django.db.models import (@@ -567,6 +568,9 @@ class ProductVariant(SortableModel, ModelWithMetadata):is_preorder = models.BooleanField(default=False)preorder_end_date = models.DateTimeField(null=True, blank=True)preorder_global_threshold = models.IntegerField(blank=True, null=True)+ quantity_limit_per_customer = models.IntegerField(+ blank=True, null=True, validators=[MinValueValidator(1)]+ )weight = MeasurementField(measurement=Weight,diff --git a/saleor/settings.py b/saleor/settings.pyindex 9a3ae9aa66..9c7d62c279 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -380,8 +380,6 @@ PAYMENT_HOST = get_hostPAYMENT_MODEL = "order.Payment"-MAX_CHECKOUT_LINE_QUANTITY = int(os.environ.get("MAX_CHECKOUT_LINE_QUANTITY", 50))-TEST_RUNNER = "saleor.tests.runner.PytestTestRunner"diff --git a/saleor/site/migrations/0034_sitesettings_limit_quantity_per_checkout.py b/saleor/site/migrations/0034_sitesettings_limit_quantity_per_checkout.pynew file mode 100644index 0000000000..4119bb8900--- /dev/null+++ b/saleor/site/migrations/0034_sitesettings_limit_quantity_per_checkout.py@@ -0,0 +1,24 @@+# Generated by Django 3.2.7 on 2021-10-21 14:44++import django.core.validators+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("site", "0033_sitesettings_reserve_stock_duration_minutes"),+ ]++ operations = [+ migrations.AddField(+ model_name="sitesettings",+ name="limit_quantity_per_checkout",+ field=models.IntegerField(+ blank=True,+ default=50,+ null=True,+ validators=[django.core.validators.MinValueValidator(1)],+ ),+ ),+ ]diff --git a/saleor/site/models.py b/saleor/site/models.pyindex 43f088ac5a..6699ad4430 100644--- a/saleor/site/models.py+++ b/saleor/site/models.py@@ -1,11 +1,11 @@from email.headerregistry import Addressfrom email.utils import parseaddr-from typing import Optional+from typing import Final, Optionalfrom django.conf import settingsfrom django.contrib.sites.models import Sitefrom django.core.exceptions import ImproperlyConfigured-from django.core.validators import MaxLengthValidator, RegexValidator+from django.core.validators import MaxLengthValidator, MinValueValidator, RegexValidatorfrom django.db import modelsfrom ..core import TimePeriodType@@ -18,6 +18,8 @@ from .patch_sites import patch_contrib_sitespatch_contrib_sites()+DEFAULT_LIMIT_QUANTITY_PER_CHECKOUT: Final[int] = 50+def email_sender_name_validators():return [@@ -76,6 +78,13 @@ class SiteSettings(models.Model):blank=True, null=True)+ limit_quantity_per_checkout = models.IntegerField(+ blank=True,+ null=True,+ default=DEFAULT_LIMIT_QUANTITY_PER_CHECKOUT,+ validators=[MinValueValidator(1)],+ )+# gift card settingsgift_card_expiry_type = models.CharField(max_length=32,diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex 2103090d7b..f47168f28e 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -1,12 +1,25 @@from collections import defaultdict-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple--from django.db.models import F, Sum+from typing import (+ TYPE_CHECKING,+ Any,+ Dict,+ Iterable,+ List,+ NamedTuple,+ NoReturn,+ Optional,+ Tuple,+)++from django.core.exceptions import ValidationError+from django.db.models import F, QuerySet, Sumfrom django.db.models.functions import Coalesce+from ..checkout.error_codes import CheckoutErrorCodefrom ..core.exceptions import InsufficientStock, InsufficientStockDatafrom ..product.models import ProductVariantChannelListing-from .models import PreorderReservation, Reservation, Stock, StockQuerySet+from .models import Reservation, Stock, StockQuerySet+from .reservations import get_listings_reservationsif TYPE_CHECKING:from ..checkout.fetch import CheckoutLineInfo@@ -14,6 +27,19 @@ if TYPE_CHECKING:from ..product.models import Product, ProductVariant+class ChannelListingPreorderAvailbilityInfo(NamedTuple):+ preorder_quantity: int+ preorder_quantity_threshold: int+ listing_id: int+++class VariantsChannelAvailbilityInfo(NamedTuple):+ variants_channel_availability: Dict[int, ChannelListingPreorderAvailbilityInfo]+ variants_global_allocations: Dict[int, int]+ all_variants_channel_listings: QuerySet[ProductVariantChannelListing]+ variant_channels: Dict[int, List[ProductVariantChannelListing]]++def _get_available_quantity(stocks: StockQuerySet,checkout_lines: Optional[List["CheckoutLine"]] = None,@@ -48,12 +74,8 @@ def check_stock_and_preorder_quantity(or there is not enough available preorder items for a variant."""if variant.is_preorder_active():- check_preorder_threshold_bulk(- [variant],- [quantity],- channel_slug,- checkout_lines,- check_reservations,+ check_preorder_threshold_in_orders(+ variant, quantity, channel_slug, checkout_lines, check_reservations)else:check_stock_quantity(@@ -98,6 +120,7 @@ def check_stock_and_preorder_quantity_bulk(country_code: str,quantities: Iterable[int],channel_slug: str,+ global_quantity_limit: Optional[int],additional_filter_lookup: Optional[Dict[str, Any]] = None,existing_lines: Optional[Iterable["CheckoutLineInfo"]] = None,replace: bool = False,@@ -120,6 +143,7 @@ def check_stock_and_preorder_quantity_bulk(country_code,stock_quantities,channel_slug,+ global_quantity_limit,additional_filter_lookup,existing_lines,replace,@@ -130,9 +154,9 @@ def check_stock_and_preorder_quantity_bulk(preorder_variants,preorder_quantities,channel_slug,- # Unpack lines from LineInfo objects- # This is for compat with check_stock_and_preorder_quantity- [line.line for line in existing_lines or []],+ global_quantity_limit,+ existing_lines,+ replace,check_reservations,)@@ -161,11 +185,32 @@ def _split_lines_for_trackable_and_preorder()+def _check_quantity_limits(+ variant: "ProductVariant", quantity: int, global_quantity_limit: Optional[int]+) -> Optional[NoReturn]:+ quantity_limit = variant.quantity_limit_per_customer or global_quantity_limit++ if quantity_limit is not None and quantity > quantity_limit:+ raise ValidationError(+ {+ "quantity": ValidationError(+ (+ f"Cannot add more than {quantity_limit} "+ f"times this item: {variant}."+ ),+ code=CheckoutErrorCode.QUANTITY_GREATER_THAN_LIMIT.value,+ )+ }+ )+ return None++def check_stock_quantity_bulk(variants: Iterable["ProductVariant"],country_code: str,quantities: Iterable[int],channel_slug: str,+ global_quantity_limit: Optional[int],additional_filter_lookup: Optional[Dict[str, Any]] = None,existing_lines: Iterable["CheckoutLineInfo"] = None,replace=False,@@ -202,6 +247,7 @@ def check_stock_quantity_bulk(line.variant.pk: line.line.quantity for line in existing_lines or []}for variant, quantity in zip(variants, quantities):+if not replace:quantity += variants_quantities.get(variant.pk, 0)@@ -214,6 +260,8 @@ def check_stock_quantity_bulk()if quantity > 0:+ _check_quantity_limits(variant, quantity, global_quantity_limit)+if not stocks:insufficient_stocks.append(InsufficientStockData(@@ -232,17 +280,10 @@ def check_stock_quantity_bulk(raise InsufficientStock(insufficient_stocks)-def check_preorder_threshold_bulk(+def _get_variants_channel_availbility_info(variants: Iterable["ProductVariant"],- quantities: Iterable[int],channel_slug: str,- checkout_lines: Optional[List["CheckoutLine"]] = None,- check_reservations: bool = False,-):- """Validate if there is enough preordered variants according to thresholds.-- :raises InsufficientStock: when there is not enough available items for a variant.- """+) -> VariantsChannelAvailbilityInfo:all_variants_channel_listings = (ProductVariantChannelListing.objects.filter(variant__in=variants).annotate_preorder_quantity_allocated()@@ -253,7 +294,7 @@ def check_preorder_threshold_bulk(.select_related("channel"))variants_channel_availability = {- channel_listing.variant_id: (+ channel_listing.variant_id: ChannelListingPreorderAvailbilityInfo(channel_listing.available_preorder_quantity,channel_listing.preorder_quantity_threshold,channel_listing.id,@@ -273,34 +314,131 @@ def check_preorder_threshold_bulk()for variant_id, channel_listings in variant_channels.items()}+ return VariantsChannelAvailbilityInfo(+ variants_channel_availability,+ variants_global_allocations,+ all_variants_channel_listings,+ variant_channels,+ )+++def check_preorder_threshold_in_orders(+ variant: "ProductVariant",+ quantity: int,+ channel_slug: str,+ checkout_lines: Optional[Iterable["CheckoutLine"]],+ check_reservations: bool,+):+ """Validate if there is preorder available for given variants in given country.++ It is used in orders, since it does not need additional logic related to limits.+ :raises InsufficientStock: when there is not enough items in stock for a variant.+ """+ (+ variants_channel_availability,+ variants_global_allocations,+ all_variants_channel_listings,+ variant_channels,+ ) = _get_variants_channel_availbility_info([variant], channel_slug)if check_reservations:- quantity_reservation_list = (- PreorderReservation.objects.filter(- product_variant_channel_listing__in=all_variants_channel_listings,- quantity_reserved__gt=0,+ listings_reservations = get_listings_reservations(+ checkout_lines, all_variants_channel_listings+ )+ else:+ listings_reservations = defaultdict(int)++ insufficient_stocks: List[InsufficientStockData] = []++ if (+ variants_channel_availability[variant.id].preorder_quantity_threshold+ is not None+ ):+ channel_listing_id = variants_channel_availability[variant.id].listing_id+ available_channel_quantity = variants_channel_availability[+ variant.id+ ].preorder_quantity+ available_channel_quantity -= listings_reservations[channel_listing_id]+ available_channel_quantity = max(available_channel_quantity, 0)++ if quantity > available_channel_quantity:+ insufficient_stocks.append(+ InsufficientStockData(+ variant=variant, available_quantity=available_channel_quantity+ ))- .not_expired()- .exclude_checkout_lines(checkout_lines)- .values("product_variant_channel_listing")- .annotate(quantity_reserved_sum=Sum("quantity_reserved"))- ) # type: ignore- listings_reservations: Dict = defaultdict(int)- for reservation in quantity_reservation_list:- listings_reservations[- reservation["product_variant_channel_listing"]- ] += reservation["quantity_reserved_sum"]++ if variant.preorder_global_threshold is not None:+ global_availability = variant.preorder_global_threshold+ global_availability -= variants_global_allocations[variant.id]++ for channel_listing in variant_channels[variant.id]:+ global_availability -= listings_reservations[channel_listing.id]++ global_availability = max(global_availability, 0)++ if quantity > global_availability:+ insufficient_stocks.append(+ InsufficientStockData(+ variant=variant,+ available_quantity=global_availability,+ )+ )++ if insufficient_stocks:+ raise InsufficientStock(insufficient_stocks)+++def check_preorder_threshold_bulk(+ variants: Iterable["ProductVariant"],+ quantities: Iterable[int],+ channel_slug: str,+ global_quantity_limit: Optional[int],+ existing_lines: Optional[Iterable["CheckoutLineInfo"]] = None,+ replace: bool = False,+ check_reservations: bool = False,+):+ """Validate if there is enough preordered variants according to thresholds.++ :raises InsufficientStock: when there is not enough available items for a variant.+ """+ (+ variants_channel_availability,+ variants_global_allocations,+ all_variants_channel_listings,+ variant_channels,+ ) = _get_variants_channel_availbility_info(variants, channel_slug)++ if check_reservations:+ listings_reservations = get_listings_reservations(+ [line.line for line in existing_lines or []], all_variants_channel_listings+ )else:listings_reservations = defaultdict(int)insufficient_stocks: List[InsufficientStockData] = []+ variants_quantities = {+ line.variant.pk: line.line.quantity for line in existing_lines or []+ }for variant, quantity in zip(variants, quantities):- if variants_channel_availability[variant.id][1] is not None:- channel_listing_id = variants_channel_availability[variant.id][2]- available_channel_quantity = variants_channel_availability[variant.id][0]++ cumulative_quantity = quantity+ if not replace:+ cumulative_quantity = quantity + variants_quantities.get(variant.pk, 0)++ if quantity > 0:+ _check_quantity_limits(variant, cumulative_quantity, global_quantity_limit)++ if (+ variants_channel_availability[variant.id].preorder_quantity_threshold+ is not None+ ):+ channel_listing_id = variants_channel_availability[variant.id].listing_id+ available_channel_quantity = variants_channel_availability[+ variant.id+ ].preorder_quantityavailable_channel_quantity -= listings_reservations[channel_listing_id]available_channel_quantity = max(available_channel_quantity, 0)-if quantity > available_channel_quantity:insufficient_stocks.append(InsufficientStockData(diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.pyindex f44fc6414f..a3eed33ae3 100644--- a/saleor/warehouse/reservations.py+++ b/saleor/warehouse/reservations.py@@ -263,21 +263,9 @@ def reserve_preorders(for variant_id, channel_listings in variant_channels.items()}- quantity_reservation = (- PreorderReservation.objects.filter(- product_variant_channel_listing__in=all_variants_channel_listings,- quantity_reserved__gt=0,- )- .not_expired()- .exclude_checkout_lines(checkout_lines_to_reserve)- .values("product_variant_channel_listing")- .annotate(quantity_reserved_sum=Sum("quantity_reserved"))- ) # type: ignore- listings_reservations: Dict = defaultdict(int)- for reservation in quantity_reservation:- listings_reservations[- reservation["product_variant_channel_listing"]- ] += reservation["quantity_reserved_sum"]+ listings_reservations: Dict = get_listings_reservations(+ checkout_lines, all_variants_channel_listings+ )insufficient_stocks: List[InsufficientStockData] = []reservations: List[Reservation] = []@@ -387,3 +375,27 @@ def get_reservation_length(request) -> Optional[int]:if request.user.is_authenticated:return request.site.settings.reserve_stock_duration_authenticated_userreturn request.site.settings.reserve_stock_duration_anonymous_user+++def get_listings_reservations(+ checkout_lines: Optional[Iterable["CheckoutLine"]],+ all_variants_channel_listings,+) -> Dict[int, int]:+ quantity_reservation_list = (+ PreorderReservation.objects.filter(+ product_variant_channel_listing__in=all_variants_channel_listings,+ quantity_reserved__gt=0,+ )+ .not_expired()+ .exclude_checkout_lines(checkout_lines)+ .values("product_variant_channel_listing")+ .annotate(quantity_reserved_sum=Sum("quantity_reserved"))+ ) # type: ignore+ listings_reservations: Dict = defaultdict(int)++ for reservation in quantity_reservation_list:+ listings_reservations[+ reservation["product_variant_channel_listing"]+ ] += reservation["quantity_reserved_sum"]++ return listings_reservationsdiff --git a/saleor/warehouse/tests/test_preorder_availability.py b/saleor/warehouse/tests/test_preorder_availability.pyindex 0e9072774c..470a2650b3 100644--- a/saleor/warehouse/tests/test_preorder_availability.py+++ b/saleor/warehouse/tests/test_preorder_availability.py@@ -7,6 +7,7 @@ from django.db.models.functions import Coalescefrom django.utils import timezonefrom freezegun import freeze_time+from ...checkout.fetch import CheckoutLineInfofrom ...core.exceptions import InsufficientStockfrom ..availability import (check_preorder_threshold_bulk,@@ -16,11 +17,11 @@ from ..availability import (from ..models import PreorderReservation-@patch("saleor.warehouse.availability.check_preorder_threshold_bulk")+@patch("saleor.warehouse.availability.check_preorder_threshold_in_orders")@patch("saleor.warehouse.availability.check_stock_quantity")def test_check_stock_and_preorder_quantity(mock_check_stock_quantity,- mock_check_preorder_threshold_bulk,+ mock_check_preorder_threshold,variant,preorder_variant_channel_threshold,channel_USD,@@ -31,11 +32,13 @@ def test_check_stock_and_preorder_quantity(check_stock_and_preorder_quantity(preorder_variant_channel_threshold, "US", channel_USD.slug, 1)- mock_check_preorder_threshold_bulk.assert_called_once()- assert mock_check_preorder_threshold_bulk.call_args[0][0] == [- preorder_variant_channel_threshold- ]- assert mock_check_preorder_threshold_bulk.call_args[0][1] == [1]+ mock_check_preorder_threshold.assert_called_once()+ assert (+ mock_check_preorder_threshold.call_args[0][0]+ == preorder_variant_channel_threshold+ )++ assert mock_check_preorder_threshold.call_args[0][1] == 1@patch("saleor.warehouse.availability.check_preorder_threshold_bulk")@@ -50,6 +53,7 @@ def test_check_stock_and_preorder_quantity_bulk():stock_variant_quantity = 2preorder_quantity = 1+ global_quantity_limit = 50with freeze_time(preorder_variant_with_end_date.preorder_end_date + timedelta(days=3)@@ -63,6 +67,7 @@ def test_check_stock_and_preorder_quantity_bulk("US",[stock_variant_quantity, preorder_quantity, stock_variant_quantity],channel_USD.slug,+ global_quantity_limit=global_quantity_limit,)mock_check_stock_quantity_bulk.assert_called_once()@@ -86,6 +91,7 @@ def test_check_preorder_threshold_bulk_channel_threshold(preorder_variant_channel_threshold, channel_USD):variant = preorder_variant_channel_threshold+ global_quantity_limit = 30# test it doesn't raise an error for available preorder variantchannel_listings = variant.channel_listings.all()available_preorder_quantity = channel_listings.annotate(@@ -94,7 +100,10 @@ def test_check_preorder_threshold_bulk_channel_threshold()[0].available_preorder_quantityassert (check_preorder_threshold_bulk(- [variant], [available_preorder_quantity], channel_USD.slug+ [variant],+ [available_preorder_quantity],+ channel_USD.slug,+ global_quantity_limit,)is None)@@ -102,7 +111,10 @@ def test_check_preorder_threshold_bulk_channel_threshold(# test if it raises error for exceeded quantitywith pytest.raises(InsufficientStock):check_preorder_threshold_bulk(- [variant], [available_preorder_quantity + 1], channel_USD.slug+ [variant],+ [available_preorder_quantity + 1],+ channel_USD.slug,+ global_quantity_limit,)@@ -117,8 +129,9 @@ def test_check_preorder_reserved_threshold_bulk_channel_threshold([variant],[5],channel_USD.slug,- checkout_lines=[],+ existing_lines=[],check_reservations=True,+ global_quantity_limit=None,)is None)@@ -129,17 +142,29 @@ def test_check_preorder_reserved_threshold_bulk_channel_threshold([variant],[9],channel_USD.slug,- checkout_lines=[],+ existing_lines=[],check_reservations=True,+ global_quantity_limit=None,)# Check excludes given checkout lines reservations+ line = checkout_line_with_reserved_preorder_itemcheck_preorder_threshold_bulk([variant],[9],channel_USD.slug,- checkout_lines=[checkout_line_with_reserved_preorder_item],+ existing_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,+ )+ ],check_reservations=True,+ global_quantity_limit=None,)# Check excludes expired reservations@@ -151,8 +176,9 @@ def test_check_preorder_reserved_threshold_bulk_channel_threshold([variant],[9],channel_USD.slug,- checkout_lines=[],+ existing_lines=[],check_reservations=True,+ global_quantity_limit=None,)@@ -169,8 +195,9 @@ def test_check_preorder_reserved_threshold_bulk_global_threshold([variant],[1],channel_USD.slug,- checkout_lines=[],+ existing_lines=[],check_reservations=True,+ global_quantity_limit=None,)is None)@@ -181,17 +208,30 @@ def test_check_preorder_reserved_threshold_bulk_global_threshold([variant],[2],channel_USD.slug,- checkout_lines=[],+ existing_lines=[],check_reservations=True,+ global_quantity_limit=None,)# Check excludes given checkout lines reservations+ line = checkout_line_with_reserved_preorder_item+check_preorder_threshold_bulk([variant],[3],channel_USD.slug,- checkout_lines=[checkout_line_with_reserved_preorder_item],+ existing_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,+ )+ ],check_reservations=True,+ global_quantity_limit=None,)# Check excludes expired reservations@@ -203,8 +243,9 @@ def test_check_preorder_reserved_threshold_bulk_global_threshold([variant],[3],channel_USD.slug,- checkout_lines=[],+ existing_lines=[],check_reservations=True,+ global_quantity_limit=None,)@@ -212,6 +253,7 @@ def test_check_preorder_threshold_bulk_global_threshold(preorder_variant_global_threshold, channel_USD):variant = preorder_variant_global_threshold+ global_quantity_limit = 30channel_listings = variant.channel_listings.all()global_allocation = sum(channel_listings.annotate(@@ -225,7 +267,10 @@ def test_check_preorder_threshold_bulk_global_threshold(# test it doesn't raise an error for available preorder variantassert (check_preorder_threshold_bulk(- [variant], [available_preorder_quantity], channel_USD.slug+ [variant],+ [available_preorder_quantity],+ channel_USD.slug,+ global_quantity_limit,)is None)@@ -233,7 +278,10 @@ def test_check_preorder_threshold_bulk_global_threshold(# test if it raises error for exceeded quantitywith pytest.raises(InsufficientStock):check_preorder_threshold_bulk(- [variant], [available_preorder_quantity + 1], channel_USD.slug+ [variant],+ [available_preorder_quantity + 1],+ channel_USD.slug,+ global_quantity_limit,)@@ -244,6 +292,7 @@ def test_check_preorder_threshold_bulk_global_and_channel_threshold(channel_PLN,):variant = preorder_variant_global_and_channel_threshold+ global_quantity_limit = 30channel_listings = variant.channel_listings.all()channel_listings = channel_listings.annotate_preorder_quantity_allocated()@@ -269,7 +318,7 @@ def test_check_preorder_threshold_bulk_global_and_channel_threshold(# test it doesn't raise any error if global limit is not exceededassert (check_preorder_threshold_bulk(- [variant], [global_availability], channel_USD.slug+ [variant], [global_availability], channel_USD.slug, global_quantity_limit)is None)@@ -281,4 +330,5 @@ def test_check_preorder_threshold_bulk_global_and_channel_threshold([variant],[channel_listing_USD_availability],channel_USD.slug,+ global_quantity_limit,)diff --git a/saleor/warehouse/tests/test_stock_availability.py b/saleor/warehouse/tests/test_stock_availability.pyindex a4471d1643..6c762495b8 100644--- a/saleor/warehouse/tests/test_stock_availability.py+++ b/saleor/warehouse/tests/test_stock_availability.py@@ -198,6 +198,7 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):variant = variant_with_many_stockscountry_code = "US"available_quantity = _get_available_quantity(variant.stocks.all())+ global_quantity_limit = 50# test that it doesn't raise error for available quantityassert (@@ -206,6 +207,7 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):country_code,[available_quantity],channel_USD.slug,+ global_quantity_limit,)is None)@@ -217,6 +219,7 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):country_code,[available_quantity + 1],channel_USD,+ global_quantity_limit,)# test that it raises an error if no stocks are found@@ -227,6 +230,7 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):country_code,[available_quantity],channel_USD.slug,+ global_quantity_limit,)@@ -236,6 +240,8 @@ def test_check_stock_quantity_bulk_no_channel_shipping_zones(variant = variant_with_many_stockscountry_code = "US"available_quantity = _get_available_quantity(variant.stocks.all())+ global_quantity_limit = 50+channel_USD.shipping_zones.clear()with pytest.raises(InsufficientStock):@@ -244,6 +250,7 @@ def test_check_stock_quantity_bulk_no_channel_shipping_zones(country_code,[available_quantity],channel_USD.slug,+ global_quantity_limit,)@@ -261,6 +268,7 @@ def test_check_stock_quantity_bulk_with_reservations(channel_USD.slug,check_reservations=True,)+ global_quantity_limit = 50# test that it doesn't raise error for available quantityassert (@@ -269,6 +277,7 @@ def test_check_stock_quantity_bulk_with_reservations(country_code,[available_quantity],channel_USD.slug,+ global_quantity_limit,check_reservations=True,)is None@@ -281,6 +290,7 @@ def test_check_stock_quantity_bulk_with_reservations(country_code,[available_quantity + 1],channel_USD.slug,+ global_quantity_limit,check_reservations=True,)@@ -292,6 +302,7 @@ def test_check_stock_quantity_bulk_with_reservations(country_code,[available_quantity + 1],channel_USD.slug,+ global_quantity_limit,existing_lines=checkout_lines,check_reservations=True,)