Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add reservations to preorders (#8429)
Rafał Pitońe76188e9ba2e
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 1f2b3428ac..af3401aca7 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -47,6 +47,7 @@ from .utils import get_voucher_for_checkoutif TYPE_CHECKING:from ..app.models import Appfrom ..plugins.manager import PluginsManager+ from ..site.models import SiteSettingsfrom .fetch import CheckoutInfo, CheckoutLineInfo@@ -218,6 +219,7 @@ def _create_lines_for_order(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],discounts: Iterable[DiscountInfo],+ check_reservations: bool,) -> Iterable[OrderLineData]:"""Create a lines for the given order.@@ -259,6 +261,9 @@ def _create_lines_for_order(quantities,checkout_info.channel.slug,additional_warehouse_lookup,+ existing_lines=lines,+ replace=True,+ check_reservations=check_reservations,)return [@@ -280,7 +285,8 @@ def _prepare_order_data(manager: "PluginsManager",checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],- discounts+ discounts: Iterable[DiscountInfo],+ check_reservations: bool = False,) -> dict:"""Run checks and return all the data from a given checkout to create an order.@@ -327,7 +333,7 @@ def _prepare_order_data()order_data["lines"] = _create_lines_for_order(- manager, checkout_info, lines, discounts+ manager, checkout_info, lines, discounts, check_reservations)# validate checkout gift cards@@ -428,7 +434,12 @@ def _create_order(check_reservations=is_reservation_enabled(site_settings),checkout_lines=[line.line for line in checkout_lines],)- allocate_preorders(order_lines_info, checkout_info.channel.slug)+ allocate_preorders(+ order_lines_info,+ checkout_info.channel.slug,+ check_reservations=is_reservation_enabled(site_settings),+ checkout_lines=[line.line for line in checkout_lines],+ )add_gift_cards_to_order(checkout_info, order, total_price_left, user, app)@@ -523,6 +534,7 @@ def _get_order_data(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],discounts: List[DiscountInfo],+ site_settings: "SiteSettings",) -> dict:"""Prepare data that will be converted to order and its lines."""try:@@ -531,6 +543,7 @@ def _get_order_data(checkout_info=checkout_info,lines=lines,discounts=discounts,+ check_reservations=is_reservation_enabled(site_settings),)except InsufficientStock as e:error = prepare_insufficient_stock_checkout_validation_error(e)@@ -617,8 +630,13 @@ def complete_checkout(payment=payment,)+ if site_settings is None:+ site_settings = Site.objects.get_current().settings+try:- order_data = _get_order_data(manager, checkout_info, lines, discounts)+ order_data = _get_order_data(+ manager, checkout_info, lines, discounts, site_settings+ )except ValidationError as exc:gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)raise excdiff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 85f4ef2f3b..66c920d851 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -32,7 +32,7 @@ from ..warehouse.availability import (check_stock_and_preorder_quantity_bulk,)from ..warehouse.models import Warehouse-from ..warehouse.reservations import reserve_stocks+from ..warehouse.reservations import reserve_stocks_and_preordersfrom . import AddressType, calculationsfrom .error_codes import CheckoutErrorCodefrom .fetch import (@@ -66,6 +66,8 @@ def check_variant_in_stock(quantity: int = 1,replace: bool = False,check_quantity: bool = True,+ checkout_lines: Optional[List["CheckoutLine"]] = None,+ check_reservations: bool = False,) -> Tuple[int, Optional[CheckoutLine]]:"""Check if a given variant is in stock and return the new quantity + line."""line = checkout.lines.filter(variant=variant).first()@@ -80,7 +82,12 @@ def check_variant_in_stock(if new_quantity > 0 and check_quantity:check_stock_and_preorder_quantity(- variant, checkout.get_country(), channel_slug, new_quantity+ variant,+ checkout.get_country(),+ channel_slug,+ new_quantity,+ checkout_lines,+ check_reservations,)return new_quantity, line@@ -191,7 +198,7 @@ def add_variants_to_checkout(to_reserve.append(line)variants.append(line.variant)- reserve_stocks(+ reserve_stocks_and_preorders(to_reserve,variants,country_code,diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 22b750dc67..2f2698d14c 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -447,7 +447,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(52):+ with django_assert_num_queries(53):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -465,7 +465,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(52):+ with django_assert_num_queries(53):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 6548d2118e..9e1971ea5d 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -43,7 +43,7 @@ from ....plugins.tests.sample_plugins import ActiveDummyPaymentGatewayfrom ....product.models import ProductChannelListing, ProductVariantfrom ....shipping import models as shipping_modelsfrom ....shipping.utils import convert_to_shipping_method_data-from ....warehouse.models import Reservation, Stock+from ....warehouse.models import PreorderReservation, Reservation, Stockfrom ...tests.utils import assert_no_permission, get_graphql_contentfrom ..mutations import (clean_delivery_method,@@ -1924,7 +1924,7 @@ query getCheckoutStockReservationExpiration($token: UUID!) {"""-def test_checkout_reservation_date_for_single_reservation(+def test_checkout_reservation_date_for_stock_reservation(site_settings_with_reservations,api_client,checkout_line_with_one_reservation,@@ -1938,6 +1938,20 @@ def test_checkout_reservation_date_for_single_reservation(assert parse_datetime(data) == reservation.reserved_until+def test_checkout_reservation_date_for_preorder_reservation(+ site_settings_with_reservations,+ api_client,+ checkout_line_with_reserved_preorder_item,+ address,+):+ reservation = PreorderReservation.objects.order_by("reserved_until").first()+ query = GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERY+ variables = {"token": checkout_line_with_reserved_preorder_item.checkout.token}+ response = api_client.post_graphql(query, variables)+ data = get_graphql_content(response)["data"]["checkout"]["stockReservationExpires"]+ assert parse_datetime(data) == reservation.reserved_until++def test_checkout_reservation_date_for_multiple_reservations(site_settings_with_reservations,api_client,@@ -1953,15 +1967,41 @@ def test_checkout_reservation_date_for_multiple_reservations(assert parse_datetime(data) == reservation.reserved_until+def test_checkout_reservation_date_for_multiple_reservations_types(+ site_settings_with_reservations,+ api_client,+ checkout_line_with_one_reservation,+ checkout_line_with_reserved_preorder_item,+ address,+):+ Reservation.objects.update(+ reserved_until=timezone.now() + datetime.timedelta(minutes=3)+ )+ PreorderReservation.objects.update(+ reserved_until=timezone.now() + datetime.timedelta(minutes=1)+ )++ reservation = PreorderReservation.objects.order_by("reserved_until").first()+ query = GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERY+ variables = {"token": checkout_line_with_one_reservation.checkout.token}+ response = api_client.post_graphql(query, variables)+ data = get_graphql_content(response)["data"]["checkout"]["stockReservationExpires"]+ assert parse_datetime(data) == reservation.reserved_until++def test_checkout_reservation_date_for_expired_reservations(site_settings_with_reservations,api_client,checkout_line_with_one_reservation,+ checkout_line_with_reserved_preorder_item,address,):Reservation.objects.update(reserved_until=timezone.now() - datetime.timedelta(minutes=1))+ PreorderReservation.objects.update(+ reserved_until=timezone.now() - datetime.timedelta(minutes=1)+ )query = GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERYvariables = {"token": checkout_line_with_one_reservation.checkout.token}@@ -1974,9 +2014,11 @@ def test_checkout_reservation_date_for_no_reservations(site_settings_with_reservations,api_client,checkout_line_with_one_reservation,+ checkout_line_with_reserved_preorder_item,address,):Reservation.objects.all().delete()+ PreorderReservation.objects.all().delete()query = GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERYvariables = {"token": checkout_line_with_one_reservation.checkout.token}@@ -1986,7 +2028,10 @@ def test_checkout_reservation_date_for_no_reservations(def test_checkout_reservation_date_for_disabled_reservations(- api_client, checkout_line_with_one_reservation, address+ api_client,+ checkout_line_with_one_reservation,+ checkout_line_with_reserved_preorder_item,+ address,):query = GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERYvariables = {"token": checkout_line_with_one_reservation.checkout.token}diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 08e99e5523..eac6804142 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -463,7 +463,13 @@ class DraftOrderComplete(BaseMutation):info.context.site.settings),)- allocate_preorders([line_data], channel_slug)+ allocate_preorders(+ [line_data],+ channel_slug,+ check_reservations=is_reservation_enabled(+ info.context.site.settings+ ),+ )except InsufficientStock as exc:errors = prepare_insufficient_stock_order_validation_errors(exc)raise ValidationError({"lines": errors})diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.pyindex a1584cbc81..56bfaee60d 100644--- a/saleor/graphql/product/tests/test_variant_availability.py+++ b/saleor/graphql/product/tests/test_variant_availability.py@@ -6,7 +6,7 @@ from django.utils import timezonefrom django_countries import countriesfrom ....shipping.models import ShippingZone-from ....warehouse.models import Reservation+from ....warehouse.models import PreorderReservation, Reservationfrom ...tests.utils import get_graphql_contentCOUNTRY_CODE = "US"@@ -312,6 +312,57 @@ 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,+):+ variant = preorder_variant_channel_threshold+ 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"]+ channel_listing = variant.channel_listings.get()+ assert (+ variant_data["deprecatedByCountry"]+ == channel_listing.preorder_quantity_threshold+ )+ 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,+ preorder_variant_channel_threshold,+ checkout_line_with_reserved_preorder_item,+ channel_USD,+):+ variant = preorder_variant_channel_threshold+ 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"]+ channel_listing = variant.channel_listings.get()++ reservation = PreorderReservation.objects.all().first()+ available_quantity = channel_listing.preorder_quantity_threshold+ available_quantity -= reservation.quantity_reserved++ assert variant_data["deprecatedByCountry"] == available_quantity+ assert variant_data["byAddress"] == available_quantity++@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)def test_variant_quantity_available_preorder_with_global_threshold(api_client, preorder_variant_global_threshold, channel_USD@@ -329,6 +380,35 @@ 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,+):+ variant = checkout_line_with_reserved_preorder_item.variant+ variant.channel_listings.update(preorder_quantity_threshold=None)+ variant.preorder_global_threshold = 10+ variant.save()++ reservation = PreorderReservation.objects.all().first()+ available_quantity = (+ variant.preorder_global_threshold - reservation.quantity_reserved+ )++ 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"] == available_quantity+ assert variant_data["byAddress"] == available_quantity++@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)def test_variant_quantity_available_preorder_without_threshold(api_client, preorder_variant_global_threshold, settings, channel_USDdiff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 1725a80f67..eb4e55e2bd 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -26,6 +26,7 @@ from ....product.utils.availability import (get_variant_availability,)from ....product.utils.variants import get_variant_selection_attributes+from ....warehouse.reservations import is_reservation_enabledfrom ...account import types as account_typesfrom ...account.enums import CountryCodeEnumfrom ...attribute.filters import AttributeFilterInput@@ -76,6 +77,7 @@ from ...utils import get_user_or_app_from_contextfrom ...utils.filters import reporting_period_to_datefrom ...warehouse.dataloaders import (AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader,+ PreorderQuantityReservedByVariantChannelListingIdLoader,StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,)from ...warehouse.types import Stock@@ -343,6 +345,30 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):channel_listingand channel_listing.preorder_quantity_threshold is not None):+ if is_reservation_enabled(info.context.site.settings):+ quantity_reserved = (+ PreorderQuantityReservedByVariantChannelListingIdLoader(+ info.context+ ).load(channel_listing.id)+ )++ def calculate_available_channel_quantity_with_reservations(+ reserved_quantity,+ ):+ return max(+ min(+ channel_listing.preorder_quantity_threshold+ - channel_listing.preorder_quantity_allocated+ - reserved_quantity,+ settings.MAX_CHECKOUT_LINE_QUANTITY,+ ),+ 0,+ )++ return quantity_reserved.then(+ calculate_available_channel_quantity_with_reservations+ )+return min(channel_listing.preorder_quantity_threshold- channel_listing.preorder_quantity_allocated,@@ -360,6 +386,36 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):channel_listing.preorder_quantity_allocatedfor channel_listing in variant_channel_listings)++ available_quantity = variant.preorder_global_threshold+ available_quantity -= global_sold_units++ if is_reservation_enabled(info.context.site.settings):+ quantity_reserved = (+ PreorderQuantityReservedByVariantChannelListingIdLoader(+ info.context+ ).load_many(+ [listing.id for listing in variant_channel_listings]+ )+ )++ def calculate_available_global_quantity_with_reservations(+ reserved_quantities,+ ):+ return max(+ min(+ variant.preorder_global_threshold+ - global_sold_units+ - sum(reserved_quantities),+ settings.MAX_CHECKOUT_LINE_QUANTITY,+ ),+ 0,+ )++ return quantity_reserved.then(+ calculate_available_global_quantity_with_reservations+ )+return min(variant.preorder_global_threshold - global_sold_units,settings.MAX_CHECKOUT_LINE_QUANTITY,diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex 64c8210581..63b60774ba 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -3,10 +3,20 @@ from typing import DefaultDict, Iterable, List, Optional, Tuplefrom uuid import UUIDfrom django.conf import settings-from django.db.models import Exists, OuterRef+from django.db.models import Exists, OuterRef, Q+from django.db.models.aggregates import Sum+from django.db.models.functions import Coalesce+from django.utils import timezonefrom ...channel.models import Channel-from ...warehouse.models import Reservation, ShippingZone, Stock, Warehouse+from ...product.models import ProductVariantChannelListing+from ...warehouse.models import (+ PreorderReservation,+ Reservation,+ ShippingZone,+ Stock,+ Warehouse,+)from ...warehouse.reservations import is_reservation_enabledfrom ..core.dataloaders import DataLoader@@ -263,6 +273,13 @@ class ActiveReservationsByCheckoutLineIdLoader(DataLoader):queryset = Reservation.objects.filter(checkout_line_id__in=keys).not_expired() # type: ignore+ for reservation in queryset:+ reservations_by_checkout_line[reservation.checkout_line_id].append(+ reservation+ )+ queryset = PreorderReservation.objects.filter(+ checkout_line_id__in=keys+ ).not_expired() # type: ignorefor reservation in queryset:reservations_by_checkout_line[reservation.checkout_line_id].append(reservation@@ -270,6 +287,28 @@ class ActiveReservationsByCheckoutLineIdLoader(DataLoader):return [reservations_by_checkout_line[key] for key in keys]+class PreorderQuantityReservedByVariantChannelListingIdLoader(DataLoader):+ context_key = "preorder_quantity_reserved_by_variant_channel_listing_id"++ def batch_load(self, keys):+ queryset = (+ ProductVariantChannelListing.objects.filter(id__in=keys)+ .annotate(+ quantity_reserved=Coalesce(+ Sum("preorder_reservations__quantity_reserved"),+ 0,+ ),+ where=Q(preorder_reservations__reserved_until__gt=timezone.now()),+ )+ .values("id", "quantity_reserved")+ )++ reservations_by_listing_id = defaultdict(int)+ for listing in queryset:+ reservations_by_listing_id[listing["id"]] += listing["quantity_reserved"]+ return [reservations_by_listing_id[key] for key in keys]++class WarehouseByIdLoader(DataLoader):context_key = "warehouse_by_id"diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex a0d980c2ea..9547997daa 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -114,6 +114,7 @@ from ..warehouse import WarehouseClickAndCollectOptionfrom ..warehouse.models import (Allocation,PreorderAllocation,+ PreorderReservation,Reservation,Stock,Warehouse,@@ -3061,6 +3062,35 @@ def checkout_line_with_one_reservation(return checkout_line+def checkout_line_with_preorder_item(+ checkout, product, preorder_variant_channel_threshold+):+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())+ add_variant_to_checkout(checkout_info, preorder_variant_channel_threshold, 1)+ return checkout.lines.last()+++def checkout_line_with_reserved_preorder_item(+ checkout, product, preorder_variant_channel_threshold+):+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())+ add_variant_to_checkout(checkout_info, preorder_variant_channel_threshold, 2)+ checkout_line = checkout.lines.last()++ reserved_until = timezone.now() + timedelta(minutes=5)++ PreorderReservation.objects.create(+ checkout_line=checkout_line,+ product_variant_channel_listing=checkout_line.variant.channel_listings.first(),+ quantity_reserved=2,+ reserved_until=reserved_until,+ )++ return checkout_line++@pytest.fixturedef gift_card(customer_user):return GiftCard.objects.create(diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex 34ae6067e4..2103090d7b 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -6,7 +6,7 @@ from django.db.models.functions import Coalescefrom ..core.exceptions import InsufficientStock, InsufficientStockDatafrom ..product.models import ProductVariantChannelListing-from .models import Reservation, Stock, StockQuerySet+from .models import PreorderReservation, Reservation, Stock, StockQuerySetif TYPE_CHECKING:from ..checkout.fetch import CheckoutLineInfo@@ -27,7 +27,7 @@ def _get_available_quantity(quantity_allocated = results["quantity_allocated"]if check_reservations:- quantity_reserved = get_reserved_quantity(stocks, checkout_lines)+ quantity_reserved = get_reserved_stock_quantity(stocks, checkout_lines)else:quantity_reserved = 0@@ -35,7 +35,12 @@ def _get_available_quantity(def check_stock_and_preorder_quantity(- variant: "ProductVariant", country_code: str, channel_slug: str, quantity: int+ variant: "ProductVariant",+ country_code: str,+ channel_slug: str,+ quantity: int,+ checkout_lines: Optional[List["CheckoutLine"]] = None,+ check_reservations: bool = False,):"""Validate if there is stock/preorder available for given variant.@@ -43,9 +48,22 @@ 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)+ check_preorder_threshold_bulk(+ [variant],+ [quantity],+ channel_slug,+ checkout_lines,+ check_reservations,+ )else:- check_stock_quantity(variant, country_code, channel_slug, quantity)+ check_stock_quantity(+ variant,+ country_code,+ channel_slug,+ quantity,+ checkout_lines,+ check_reservations,+ )def check_stock_quantity(@@ -81,7 +99,7 @@ def check_stock_and_preorder_quantity_bulk(quantities: Iterable[int],channel_slug: str,additional_filter_lookup: Optional[Dict[str, Any]] = None,- existing_lines: Iterable = None,+ existing_lines: Optional[Iterable["CheckoutLineInfo"]] = None,replace: bool = False,check_reservations: bool = False,):@@ -109,7 +127,13 @@ def check_stock_and_preorder_quantity_bulk()if preorder_variants:check_preorder_threshold_bulk(- preorder_variants, preorder_quantities, channel_slug+ 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 []],+ check_reservations,)@@ -166,7 +190,7 @@ def check_stock_quantity_bulk(variant_stocks[stock.product_variant_id].append(stock)if check_reservations:- variant_reservations = get_reserved_quantity_bulk(+ variant_reservations = get_reserved_stock_quantity_bulk(all_variants_stocks,[line.line for line in existing_lines] if existing_lines else [],)@@ -212,6 +236,8 @@ def check_preorder_threshold_bulk(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.@@ -230,6 +256,7 @@ def check_preorder_threshold_bulk(channel_listing.variant_id: (channel_listing.available_preorder_quantity,channel_listing.preorder_quantity_threshold,+ channel_listing.id,)for channel_listing in all_variants_channel_listingsif channel_listing.channel.slug == channel_slug@@ -247,22 +274,50 @@ def check_preorder_threshold_bulk(for variant_id, channel_listings in variant_channels.items()}+ if check_reservations:+ 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"]+ else:+ listings_reservations = defaultdict(int)+insufficient_stocks: List[InsufficientStockData] = []for variant, quantity in zip(variants, quantities):if variants_channel_availability[variant.id][1] is not None:- if quantity > variants_channel_availability[variant.id][0]:+ channel_listing_id = variants_channel_availability[variant.id][2]+ available_channel_quantity = variants_channel_availability[variant.id][0]+ 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=variants_channel_availability[variant.id][0],+ available_quantity=available_channel_quantity,))if variant.preorder_global_threshold is not None:- global_availability = (- variant.preorder_global_threshold- - variants_global_allocations[variant.id]- )+ 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(@@ -301,7 +356,7 @@ def is_product_in_stock(return any(stocks.values_list("available_quantity", flat=True))-def get_reserved_quantity(+def get_reserved_stock_quantity(stocks: StockQuerySet, lines: Optional[List["CheckoutLine"]] = None) -> int:result = (@@ -318,7 +373,7 @@ def get_reserved_quantity(return result["quantity_reserved"]-def get_reserved_quantity_bulk(+def get_reserved_stock_quantity_bulk(stocks: Iterable[Stock],checkout_lines: Iterable["CheckoutLine"],) -> Dict[int, int]:diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 53195da15a..4299318e49 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -16,7 +16,14 @@ from ..core.tracing import traced_atomic_transactionfrom ..order import OrderLineDatafrom ..plugins.manager import PluginsManagerfrom ..product.models import ProductVariant, ProductVariantChannelListing-from .models import Allocation, PreorderAllocation, Reservation, Stock, Warehouse+from .models import (+ Allocation,+ PreorderAllocation,+ PreorderReservation,+ Reservation,+ Stock,+ Warehouse,+)if TYPE_CHECKING:from ..order.models import Order, OrderLine@@ -482,7 +489,12 @@ def deallocate_stock_for_order(order: "Order", manager: PluginsManager):@traced_atomic_transaction()-def allocate_preorders(order_lines_info: Iterable["OrderLineData"], channel_slug: str):+def allocate_preorders(+ order_lines_info: Iterable["OrderLineData"],+ channel_slug: str,+ check_reservations: bool = False,+ checkout_lines: Optional[Iterable["CheckoutLine"]] = None,+):"""Allocate preorder variant for given `order_lines` in given channel."""order_lines_info = get_order_lines_with_preorder(order_lines_info)if not order_lines_info:@@ -496,9 +508,9 @@ def allocate_preorders(order_lines_info: Iterable["OrderLineData"], channel_slug.select_related("channel").values("id", "channel__slug", "preorder_quantity_threshold", "variant_id"))- all_variants_channel_listings_id = (+ all_variants_channel_listings_id = [channel_listing["id"] for channel_listing in all_variants_channel_listings- )+ ]quantity_allocation_list = list(PreorderAllocation.objects.filter(@@ -523,6 +535,31 @@ def allocate_preorders(order_lines_info: Iterable["OrderLineData"], channel_slugif channel_listing["channel__slug"] == channel_slug}+ variants_channel_listings = defaultdict(list)+ for channel_listing in all_variants_channel_listings:+ variants_channel_listings[channel_listing["variant_id"]].append(+ channel_listing["id"]+ )++ if check_reservations:+ quantity_reservation_list = (+ PreorderReservation.objects.filter(+ product_variant_channel_listing_id__in=all_variants_channel_listings_id, # noqa: E501+ 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"]+ else:+ listings_reservations = defaultdict(int)+variants_global_allocations: Dict[int, int] = defaultdict(int)for channel_listing in all_variants_channel_listings:variants_global_allocations[@@ -537,7 +574,9 @@ def allocate_preorders(order_lines_info: Iterable["OrderLineData"], channel_slugline_info,variants_to_channel_listings[variant.id],variants_global_allocations[variant.id],+ variants_channel_listings[variant.id],quantity_allocation_for_channel,+ listings_reservations,)if allocation_item:allocations.append(allocation_item)@@ -566,17 +605,20 @@ def _create_preorder_allocation(line_info: "OrderLineData",variant_channel_data: Tuple[int, Optional[int]],variant_global_allocation: int,+ variants_channel_listings: List[int],quantity_allocation_for_channel: Dict[int, int],+ listings_reservations: Dict[int, int],) -> Tuple[Optional[PreorderAllocation], Optional[InsufficientStockData]]:variant = cast(ProductVariant, line_info.variant)quantity = line_info.quantitychannel_listing_id, channel_quantity_threshold = variant_channel_dataif channel_quantity_threshold is not None:- channel_availability = (- channel_quantity_threshold- - quantity_allocation_for_channel[channel_listing_id]- )+ channel_availability = channel_quantity_threshold+ channel_availability -= quantity_allocation_for_channel[channel_listing_id]+ channel_availability -= listings_reservations[channel_listing_id]+ channel_availability = max(channel_availability, 0)+if quantity > channel_availability:return None, InsufficientStockData(variant=variant,@@ -584,9 +626,12 @@ def _create_preorder_allocation()if variant.preorder_global_threshold is not None:- global_availability = (- variant.preorder_global_threshold - variant_global_allocation- )+ global_availability = variant.preorder_global_threshold+ global_availability -= variant_global_allocation+ for listing_id in variants_channel_listings:+ global_availability -= listings_reservations[listing_id]+ global_availability = max(global_availability, 0)+if quantity > global_availability:return None, InsufficientStockData(variant=variant, available_quantity=global_availabilitydiff --git a/saleor/warehouse/migrations/0019_auto_20211019_1438.py b/saleor/warehouse/migrations/0019_auto_20211019_1438.pynew file mode 100644index 0000000000..89fe2d54d5--- /dev/null+++ b/saleor/warehouse/migrations/0019_auto_20211019_1438.py@@ -0,0 +1,62 @@+# Generated by Django 3.2.8 on 2021-10-19 14:38++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("checkout", "0038_merge_20210903_1048"),+ ("product", "0153_merge_20211006_0910"),+ ("warehouse", "0018_auto_20210323_2116"),+ ]++ operations = [+ migrations.CreateModel(+ name="PreorderReservation",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("quantity_reserved", models.PositiveIntegerField(default=0)),+ ("reserved_until", models.DateTimeField()),+ (+ "checkout_line",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="preorder_reservations",+ to="checkout.checkoutline",+ ),+ ),+ (+ "product_variant_channel_listing",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="preorder_reservations",+ to="product.productvariantchannellisting",+ ),+ ),+ ],+ options={+ "ordering": ("pk",),+ },+ ),+ migrations.AddIndex(+ model_name="preorderreservation",+ index=models.Index(+ fields=["checkout_line", "reserved_until"],+ name="warehouse_p_checkou_3abf41_idx",+ ),+ ),+ migrations.AlterUniqueTogether(+ name="preorderreservation",+ unique_together={("checkout_line", "product_variant_channel_listing")},+ ),+ ]diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 86a1f4dd99..9b3ef16e2d 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -319,6 +319,34 @@ class ReservationQuerySet(models.QuerySet):return self+class PreorderReservation(models.Model):+ checkout_line = models.ForeignKey(+ CheckoutLine,+ null=False,+ blank=False,+ on_delete=models.CASCADE,+ related_name="preorder_reservations",+ )+ product_variant_channel_listing = models.ForeignKey(+ ProductVariantChannelListing,+ null=False,+ blank=False,+ on_delete=models.CASCADE,+ related_name="preorder_reservations",+ )+ quantity_reserved = models.PositiveIntegerField(default=0)+ reserved_until = models.DateTimeField()++ objects = models.Manager.from_queryset(ReservationQuerySet)()++ class Meta:+ unique_together = [["checkout_line", "product_variant_channel_listing"]]+ indexes = [+ models.Index(fields=["checkout_line", "reserved_until"]),+ ]+ ordering = ("pk",)++class Reservation(models.Model):checkout_line = models.ForeignKey(CheckoutLine,diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.pyindex 3b0285ad4b..f44fc6414f 100644--- a/saleor/warehouse/reservations.py+++ b/saleor/warehouse/reservations.py@@ -2,13 +2,14 @@ from collections import defaultdict, namedtuplefrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple-from django.db.models import Sum+from django.db.models import F, Sum+from django.db.models.functions import Coalescefrom django.utils import timezonefrom ..core.exceptions import InsufficientStock, InsufficientStockDatafrom ..core.tracing import traced_atomic_transaction-from ..product.models import ProductVariant-from .models import Allocation, Reservation, Stock+from ..product.models import ProductVariant, ProductVariantChannelListing+from .models import Allocation, PreorderReservation, Reservation, Stockif TYPE_CHECKING:from ..checkout.fetch import CheckoutLine@@ -17,6 +18,51 @@ StockData = namedtuple("StockData", ["pk", "quantity"])@traced_atomic_transaction()+def reserve_stocks_and_preorders(+ checkout_lines: Iterable["CheckoutLine"],+ variants: Iterable["ProductVariant"],+ country_code: str,+ channel_slug: str,+ length_in_minutes: int,+ *,+ replace: bool = True,+):+ stock_variants, stock_lines = [], []+ preorder_variants, preorder_lines = [], []++ for variant in variants:+ if variant.is_preorder_active():+ preorder_variants.append(variant)+ else:+ stock_variants.append(variant)++ for line in checkout_lines:+ if line.variant.is_preorder_active():+ preorder_lines.append(line)+ else:+ stock_lines.append(line)++ if stock_lines:+ reserve_stocks(+ stock_lines,+ stock_variants,+ country_code,+ channel_slug,+ length_in_minutes,+ replace=replace,+ )++ if preorder_lines:+ reserve_preorders(+ preorder_lines,+ preorder_variants,+ country_code,+ channel_slug,+ length_in_minutes,+ replace=replace,+ )++def reserve_stocks(checkout_lines: Iterable["CheckoutLine"],variants: Iterable["ProductVariant"],@@ -24,7 +70,7 @@ def reserve_stocks(channel_slug: str,length_in_minutes: int,*,- replace=True,+ replace: bool = True,):"""Reserve stocks for given `checkout_lines` in given country."""variants_ids = [line.variant_id for line in checkout_lines]@@ -86,7 +132,7 @@ def reserve_stocks(reservations: List[Reservation] = []for line in checkout_lines:stock_reservations = variant_to_stocks[line.variant_id]- insufficient_stocks, reserved_items = _create_reservations(+ insufficient_stocks, reserved_items = _create_stock_reservations(line,variants_map[line.variant_id],stock_reservations,@@ -106,7 +152,7 @@ def reserve_stocks(Reservation.objects.bulk_create(reservations)-def _create_reservations(+def _create_stock_reservations(line: "CheckoutLine",variant: "ProductVariant",stocks: List[StockData],@@ -162,6 +208,158 @@ def _create_reservations(return [], []+def reserve_preorders(+ checkout_lines: Iterable["CheckoutLine"],+ variants: Iterable["ProductVariant"],+ country_code: str,+ channel_slug: str,+ length_in_minutes: int,+ *,+ replace: bool = True,+):+ """Reserve preorders for given `checkout_lines` in given country."""+ variants_ids = [line.variant_id for line in checkout_lines]+ variants = [variant for variant in variants if variant.pk in variants_ids]+ variants_map = {variant.id: variant for variant in variants}++ reserved_until = timezone.now() + timedelta(minutes=length_in_minutes)++ all_variants_channel_listings = (+ ProductVariantChannelListing.objects.filter(variant__in=variants)+ .annotate_preorder_quantity_allocated()+ .annotate(+ available_preorder_quantity=F("preorder_quantity_threshold")+ - Coalesce(Sum("preorder_allocations__quantity"), 0),+ )+ .select_related("channel")+ )+ variants_channel_listings = {+ channel_listing.variant_id: channel_listing+ for channel_listing in all_variants_channel_listings+ if channel_listing.channel.slug == channel_slug+ }++ checkout_lines_to_reserve = []+ for line in checkout_lines:+ line_variant_channel_listing = variants_channel_listings[line.variant_id]+ if (+ line.variant.preorder_global_threshold+ or line_variant_channel_listing.preorder_quantity_threshold is not None+ ):+ checkout_lines_to_reserve.append(line)++ if not checkout_lines_to_reserve:+ return++ variant_channels: Dict[int, List[ProductVariantChannelListing]] = defaultdict(list)+ for channel_listing in all_variants_channel_listings:+ variant_channels[channel_listing.variant_id].append(channel_listing)++ variants_global_allocations = {+ variant_id: sum(+ channel_listing.preorder_quantity_allocated # type: ignore+ for channel_listing in channel_listings+ )+ 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"]++ insufficient_stocks: List[InsufficientStockData] = []+ reservations: List[Reservation] = []+ for line in checkout_lines_to_reserve:+ insufficient_stocks, reservation = _create_preorder_reservation(+ line,+ variants_map[line.variant_id],+ variants_channel_listings[line.variant_id],+ variant_channels[line.variant_id],+ variants_global_allocations[line.variant_id],+ listings_reservations,+ insufficient_stocks,+ reserved_until,+ )+ if reservation:+ reservations.append(reservation)++ if insufficient_stocks:+ raise InsufficientStock(insufficient_stocks)++ if reservation:+ if replace:+ PreorderReservation.objects.filter(+ checkout_line__in=checkout_lines_to_reserve+ ).delete()+ PreorderReservation.objects.bulk_create(reservations)+++def _create_preorder_reservation(+ line: "CheckoutLine",+ variant: "ProductVariant",+ listing: "ProductVariantChannelListing",+ all_listings: List["ProductVariantChannelListing"],+ global_allocations: int,+ listings_reservations: Dict[int, int],+ insufficient_stocks: List[InsufficientStockData],+ reserved_until: datetime,+):+ if listing.preorder_quantity_threshold is not None:+ available_channel_quantity = listing.available_preorder_quantity # type: ignore+ available_channel_quantity = max(+ available_channel_quantity - listings_reservations[listing.id], 0+ )+ if line.quantity > available_channel_quantity:+ insufficient_stocks.append(+ InsufficientStockData(+ variant=variant,+ available_quantity=available_channel_quantity,+ )+ )++ if variant.preorder_global_threshold:+ # check global reservations+ available_global_quantity = variant.preorder_global_threshold+ available_global_quantity -= global_allocations+ global_reservations = 0+ for channel_listing in all_listings:+ global_reservations += listings_reservations[channel_listing.id]++ available_global_quantity -= global_reservations+ available_global_quantity = max(available_global_quantity, 0)++ if line.quantity > available_global_quantity:+ insufficient_stocks.append(+ InsufficientStockData(+ variant=variant,+ available_quantity=available_global_quantity,+ )+ )++ if listing.preorder_quantity_threshold or variant.preorder_global_threshold:+ # create reservation+ return insufficient_stocks, PreorderReservation(+ checkout_line=line,+ product_variant_channel_listing=listing,+ quantity_reserved=line.quantity,+ reserved_until=reserved_until,+ )++ return insufficient_stocks, None++def get_checkout_lines_to_reserve(lines: Iterable["CheckoutLine"],variants_map: Dict[int, "ProductVariant"],diff --git a/saleor/warehouse/tasks.py b/saleor/warehouse/tasks.pyindex 76e4de0047..bd75ef3a20 100644--- a/saleor/warehouse/tasks.py+++ b/saleor/warehouse/tasks.py@@ -2,7 +2,7 @@ from celery.utils.log import get_task_loggerfrom django.utils import timezonefrom ..celeryconf import app-from .models import Allocation, Reservation+from .models import Allocation, PreorderReservation, Reservationtask_logger = get_task_logger(__name__)@@ -16,6 +16,16 @@ def delete_empty_allocations_task():@app.taskdef delete_expired_reservations_task():- count, _ = Reservation.objects.filter(reserved_until__lt=timezone.now()).delete()- if count:- task_logger.debug("Removed %s reservations", count)+ stock_reservations, _ = Reservation.objects.filter(+ reserved_until__lt=timezone.now()+ ).delete()+ preorder_reservations, _ = PreorderReservation.objects.filter(+ reserved_until__lt=timezone.now()+ ).delete()++ if stock_reservations or preorder_reservations:+ task_logger.debug(+ "Removed %s stock reservations and %s preorder reservations",+ stock_reservations,+ preorder_reservations,+ )diff --git a/saleor/warehouse/tests/test_preorder_availability.py b/saleor/warehouse/tests/test_preorder_availability.pyindex f2585c0b6d..0e9072774c 100644--- a/saleor/warehouse/tests/test_preorder_availability.py+++ b/saleor/warehouse/tests/test_preorder_availability.py@@ -4,6 +4,7 @@ from unittest.mock import patchimport pytestfrom django.db.models import F, Sumfrom django.db.models.functions import Coalesce+from django.utils import timezonefrom freezegun import freeze_timefrom ...core.exceptions import InsufficientStock@@ -12,6 +13,7 @@ from ..availability import (check_stock_and_preorder_quantity,check_stock_and_preorder_quantity_bulk,)+from ..models import PreorderReservation@patch("saleor.warehouse.availability.check_preorder_threshold_bulk")@@ -83,7 +85,6 @@ def test_check_stock_and_preorder_quantity_bulk(def test_check_preorder_threshold_bulk_channel_threshold(preorder_variant_channel_threshold, channel_USD):-variant = preorder_variant_channel_threshold# test it doesn't raise an error for available preorder variantchannel_listings = variant.channel_listings.all()@@ -105,6 +106,108 @@ def test_check_preorder_threshold_bulk_channel_threshold()+def test_check_preorder_reserved_threshold_bulk_channel_threshold(+ checkout_line_with_reserved_preorder_item, channel_PLN, channel_USD+):+ variant = checkout_line_with_reserved_preorder_item.variant++ # test it doesn't raise an error for available preorder variant+ assert (+ check_preorder_threshold_bulk(+ [variant],+ [5],+ channel_USD.slug,+ checkout_lines=[],+ check_reservations=True,+ )+ is None+ )++ # test if it raises error for exceeded quantity+ with pytest.raises(InsufficientStock):+ check_preorder_threshold_bulk(+ [variant],+ [9],+ channel_USD.slug,+ checkout_lines=[],+ check_reservations=True,+ )++ # Check excludes given checkout lines reservations+ check_preorder_threshold_bulk(+ [variant],+ [9],+ channel_USD.slug,+ checkout_lines=[checkout_line_with_reserved_preorder_item],+ check_reservations=True,+ )++ # Check excludes expired reservations+ PreorderReservation.objects.update(+ reserved_until=timezone.now() - timedelta(minutes=1)+ )++ check_preorder_threshold_bulk(+ [variant],+ [9],+ channel_USD.slug,+ checkout_lines=[],+ check_reservations=True,+ )+++def test_check_preorder_reserved_threshold_bulk_global_threshold(+ checkout_line_with_reserved_preorder_item, channel_PLN, channel_USD+):+ variant = checkout_line_with_reserved_preorder_item.variant+ variant.preorder_global_threshold = 3+ variant.save()++ # test it doesn't raise an error for available preorder variant+ assert (+ check_preorder_threshold_bulk(+ [variant],+ [1],+ channel_USD.slug,+ checkout_lines=[],+ check_reservations=True,+ )+ is None+ )++ # test if it raises error for exceeded quantity+ with pytest.raises(InsufficientStock):+ check_preorder_threshold_bulk(+ [variant],+ [2],+ channel_USD.slug,+ checkout_lines=[],+ check_reservations=True,+ )++ # Check excludes given checkout lines reservations+ check_preorder_threshold_bulk(+ [variant],+ [3],+ channel_USD.slug,+ checkout_lines=[checkout_line_with_reserved_preorder_item],+ check_reservations=True,+ )++ # Check excludes expired reservations+ PreorderReservation.objects.update(+ reserved_until=timezone.now() - timedelta(minutes=1)+ )++ check_preorder_threshold_bulk(+ [variant],+ [3],+ channel_USD.slug,+ checkout_lines=[],+ check_reservations=True,+ )++def test_check_preorder_threshold_bulk_global_threshold(preorder_variant_global_threshold, channel_USD):diff --git a/saleor/warehouse/tests/test_preorder_reservations_management.py b/saleor/warehouse/tests/test_preorder_reservations_management.pynew file mode 100644index 0000000000..f685cac667--- /dev/null+++ b/saleor/warehouse/tests/test_preorder_reservations_management.py@@ -0,0 +1,279 @@+from datetime import timedelta+from decimal import Decimal++import pytest+from django.utils import timezone++from ...checkout.models import Checkout+from ...core.exceptions import InsufficientStock+from ...product.models import ProductVariantChannelListing+from ..models import PreorderAllocation, PreorderReservation+from ..reservations import reserve_preorders++COUNTRY_CODE = "US"+RESERVATION_LENGTH = 5+++def test_reserve_preorders(checkout_line_with_preorder_item, channel_USD):+ checkout_line = checkout_line_with_preorder_item+ checkout_line.quantity = 5+ checkout_line.save()++ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ )++ reservation = PreorderReservation.objects.get(checkout_line=checkout_line)+ assert reservation.quantity_reserved == 5+ assert reservation.reserved_until > timezone.now() + timedelta(minutes=1)+++def test_preorder_reservation_skips_prev_reservation_delete_if_replace_is_disabled(+ checkout_line_with_preorder_item, assert_num_queries, channel_USD+):+ checkout_line = checkout_line_with_preorder_item++ with assert_num_queries(3):+ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ replace=False,+ )++ with assert_num_queries(4):+ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ )+++def test_preorder_reservation_removes_previous_reservations_for_checkout(+ checkout_line_with_preorder_item, channel_USD+):+ checkout_line = checkout_line_with_preorder_item+ checkout_line.quantity = 5+ checkout_line.save()++ previous_reservation = PreorderReservation.objects.create(+ checkout_line=checkout_line,+ product_variant_channel_listing=checkout_line.variant.channel_listings.first(),+ quantity_reserved=5,+ reserved_until=timezone.now() + timedelta(hours=1),+ )++ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ )++ with pytest.raises(PreorderReservation.DoesNotExist):+ previous_reservation.refresh_from_db()+++def test_preorder_reservation_fails_if_there_is_not_enough_channel_threshold_available(+ checkout_line_with_preorder_item, channel_USD+):+ checkout_line = checkout_line_with_preorder_item+ checkout_line.quantity = 5+ checkout_line.save()++ channel_listing = checkout_line.variant.channel_listings.first()+ channel_listing.preorder_quantity_threshold = 2+ channel_listing.save()++ with pytest.raises(InsufficientStock):+ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ )+++def test_preorder_reservation_fails_if_channel_threshold_was_allocated(+ order_line,+ preorder_variant_channel_threshold,+ checkout_line_with_preorder_item,+ channel_USD,+):+ checkout_line = checkout_line_with_preorder_item+ checkout_line.quantity = 5+ checkout_line.save()++ channel_listing = checkout_line.variant.channel_listings.first()+ channel_listing.preorder_quantity_threshold = 7+ channel_listing.save()++ variant = preorder_variant_channel_threshold+ product_variant_channel_listing = variant.channel_listings.get(channel=channel_USD)+ PreorderAllocation.objects.create(+ order_line=order_line,+ product_variant_channel_listing=product_variant_channel_listing,+ quantity=order_line.quantity,+ )++ with pytest.raises(InsufficientStock):+ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ )+++def test_preorder_reservation_fails_if_channel_threshold_was_reserved(+ order_line,+ preorder_variant_channel_threshold,+ checkout_line_with_preorder_item,+ channel_USD,+):+ checkout_line = checkout_line_with_preorder_item+ checkout_line.quantity = 5+ checkout_line.save()++ variant = preorder_variant_channel_threshold+ variant.preorder_global_threshold = 7+ variant.save()++ other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")+ other_checkout_line = other_checkout.lines.create(+ variant=variant,+ quantity=3,+ )+ product_variant_channel_listing = variant.channel_listings.get(channel=channel_USD)+ PreorderReservation.objects.create(+ checkout_line=other_checkout_line,+ product_variant_channel_listing=product_variant_channel_listing,+ quantity_reserved=other_checkout_line.quantity,+ reserved_until=timezone.now() + timedelta(minutes=5),+ )++ with pytest.raises(InsufficientStock):+ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ )+++def test_preorder_reservation_fails_if_global_threshold_was_allocated(+ order_line,+ preorder_variant_channel_threshold,+ checkout_line_with_preorder_item,+ channel_PLN,+ channel_USD,+):+ checkout_line = checkout_line_with_preorder_item+ checkout_line.quantity = 5+ checkout_line.save()++ variant = preorder_variant_channel_threshold+ variant.preorder_global_threshold = 7+ variant.save()++ product_variant_channel_listing = ProductVariantChannelListing.objects.create(+ variant=variant,+ channel=channel_PLN,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=channel_PLN.currency_code,+ preorder_quantity_threshold=10,+ )++ PreorderAllocation.objects.create(+ order_line=order_line,+ product_variant_channel_listing=product_variant_channel_listing,+ quantity=order_line.quantity,+ )++ with pytest.raises(InsufficientStock):+ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ )+++def test_preorder_reservation_fails_if_global_threshold_was_reserved(+ order_line,+ preorder_variant_channel_threshold,+ checkout_line_with_preorder_item,+ channel_PLN,+ channel_USD,+):+ checkout_line = checkout_line_with_preorder_item+ checkout_line.quantity = 5+ checkout_line.save()++ variant = preorder_variant_channel_threshold+ variant.preorder_global_threshold = 7+ variant.save()++ product_variant_channel_listing = ProductVariantChannelListing.objects.create(+ variant=variant,+ channel=channel_PLN,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=channel_PLN.currency_code,+ preorder_quantity_threshold=10,+ )++ other_checkout = Checkout.objects.create(channel=channel_PLN, currency="PLN")+ other_checkout_line = other_checkout.lines.create(+ variant=variant,+ quantity=3,+ )+ PreorderReservation.objects.create(+ checkout_line=other_checkout_line,+ product_variant_channel_listing=product_variant_channel_listing,+ quantity_reserved=other_checkout_line.quantity,+ reserved_until=timezone.now() + timedelta(minutes=5),+ )++ with pytest.raises(InsufficientStock):+ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ )+++def test_preorder_reservation_fails_if_there_is_not_enough_global_threshold_available(+ checkout_line_with_preorder_item, channel_USD+):+ checkout_line = checkout_line_with_preorder_item+ checkout_line.quantity = 5+ checkout_line.save()++ checkout_line.variant.preorder_global_threshold = 3+ checkout_line.variant.save()++ with pytest.raises(InsufficientStock):+ reserve_preorders(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD.slug,+ RESERVATION_LENGTH,+ )diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.pyindex e76aed269a..1bfb715686 100644--- a/saleor/warehouse/tests/test_stock_management.py+++ b/saleor/warehouse/tests/test_stock_management.py@@ -863,3 +863,56 @@ def test_allocate_preorders_insufficient_stocks_global_threshold(order_line=order_line,product_variant_channel_listing__in=channel_listings,).exists()+++def test_allocate_preorders_with_channel_reservations(+ order_line, checkout_line_with_reserved_preorder_item, channel_USD+):+ variant = checkout_line_with_reserved_preorder_item.variant+ channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)+ channel_listing.preorder_quantity_threshold = 5+ channel_listing.save(update_fields=["preorder_quantity_threshold"])++ line_data = OrderLineData(line=order_line, variant=variant, quantity=5)++ with pytest.raises(InsufficientStock):+ allocate_preorders(+ [line_data],+ channel_USD.slug,+ check_reservations=True,+ checkout_lines=[],+ )++ # Allocation passes when checkout line is passed+ allocate_preorders(+ [line_data],+ channel_USD.slug,+ check_reservations=True,+ checkout_lines=[checkout_line_with_reserved_preorder_item],+ )+++def test_allocate_preorders_with_global_reservations(+ order_line, checkout_line_with_reserved_preorder_item, channel_USD+):+ variant = checkout_line_with_reserved_preorder_item.variant+ variant.preorder_global_threshold = 5+ variant.save()++ line_data = OrderLineData(line=order_line, variant=variant, quantity=5)++ with pytest.raises(InsufficientStock):+ allocate_preorders(+ [line_data],+ channel_USD.slug,+ check_reservations=True,+ checkout_lines=[],+ )++ # Allocation passes when checkout line is passed+ allocate_preorders(+ [line_data],+ channel_USD.slug,+ check_reservations=True,+ checkout_lines=[checkout_line_with_reserved_preorder_item],+ )diff --git a/saleor/warehouse/tests/test_reservations_management.py b/saleor/warehouse/tests/test_stock_reservations_management.pysimilarity index 98%rename from saleor/warehouse/tests/test_reservations_management.pyrename to saleor/warehouse/tests/test_stock_reservations_management.pyindex 2fc8d21f64..614968e87b 100644--- a/saleor/warehouse/tests/test_reservations_management.py+++ b/saleor/warehouse/tests/test_stock_reservations_management.py@@ -35,7 +35,7 @@ def test_reserve_stocks(checkout_line, channel_USD):assert reservation.reserved_until > timezone.now() + timedelta(minutes=1)-def test_stocks_reservation_skips_prev_stocks_delete_if_replace_is_disabled(+def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabled(checkout_line, assert_num_queries, channel_USD):with assert_num_queries(3):diff --git a/saleor/warehouse/tests/test_tasks.py b/saleor/warehouse/tests/test_tasks.pyindex 3d1cc8dc38..b59177df89 100644--- a/saleor/warehouse/tests/test_tasks.py+++ b/saleor/warehouse/tests/test_tasks.py@@ -2,11 +2,11 @@ from datetime import timedeltafrom django.utils import timezone-from ..models import Reservation+from ..models import PreorderReservation, Reservationfrom ..tasks import delete_expired_reservations_task-def test_delete_expired_reservations_task_deletes_expired_reservations(+def test_delete_expired_reservations_task_deletes_expired_stock_reservations(checkout_line_with_reservation_in_many_stocks,):Reservation.objects.update(reserved_until=timezone.now() - timedelta(seconds=1))@@ -14,10 +14,31 @@ def test_delete_expired_reservations_task_deletes_expired_reservations(assert not Reservation.objects.exists()-def test_delete_expired_reservations_task_skips_active_reservations(+def test_delete_expired_reservations_task_skips_active_stock_reservations(checkout_line_with_reservation_in_many_stocks,):reservations_count = Reservation.objects.count()Reservation.objects.update(reserved_until=timezone.now() + timedelta(seconds=1))delete_expired_reservations_task()assert Reservation.objects.count() == reservations_count+++def test_delete_expired_reservations_task_deletes_expired_preorder_reservations(+ checkout_line_with_reserved_preorder_item,+):+ PreorderReservation.objects.update(+ reserved_until=timezone.now() - timedelta(seconds=1)+ )+ delete_expired_reservations_task()+ assert not PreorderReservation.objects.exists()+++def test_delete_expired_reservations_task_skips_active_preorder_reservations(+ checkout_line_with_reserved_preorder_item,+):+ reservations_count = PreorderReservation.objects.count()+ PreorderReservation.objects.update(+ reserved_until=timezone.now() + timedelta(seconds=1)+ )+ delete_expired_reservations_task()+ assert PreorderReservation.objects.count() == reservations_count