Skip to content

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

Reserve stock for checkout (#7589)

Rafał Pitońddb68c6e64c5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7bd5428dfd..108f562e7e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Introduce sales / vouchers per product variant - #8064 by @kuchichan
- Introduce sales webhooks - #8157 @kuchichan
- Batch loads in queries for Apollo Federation - #8273 by @rafalp
+- Reserve stocks for checkouts - #7589 by @rafalp
# 3.0.0 [Unreleased]
@@ -167,7 +168,6 @@ All notable, unreleased changes to this project will be documented in this file.
- Handle `SameSite` cookie attribute in jwt refresh token middleware - #8209 by @jakubkuc
-
### Breaking
- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki
- Drop deprecated meta mutations - #6422 by @maarcingebala
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index b64f589601..c1c67f1645 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -38,6 +38,7 @@ from ..payment.utils import fetch_customer_id, store_customer_id
from ..product.models import ProductTranslation, ProductVariantTranslation
from ..warehouse.availability import check_stock_and_preorder_quantity_bulk
from ..warehouse.management import allocate_preorders, allocate_stocks
+from ..warehouse.reservations import is_reservation_enabled
from . import AddressType
from .checkout_cleaner import clean_checkout_payment, clean_checkout_shipping
from .models import Checkout
@@ -353,6 +354,7 @@ def _prepare_order_data(
def _create_order(
*,
checkout_info: "CheckoutInfo",
+ checkout_lines: Iterable["CheckoutLineInfo"],
order_data: dict,
user: User,
app: Optional["App"],
@@ -427,6 +429,8 @@ def _create_order(
checkout_info.channel.slug,
manager,
additional_warehouse_lookup,
+ 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)
@@ -648,6 +652,7 @@ def complete_checkout(
try:
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=order_data,
user=user, # type: ignore
app=app,
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index fe63a42980..1a5723f0e6 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -55,6 +55,7 @@ def test_create_order_captured_payment_creates_expected_events(
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -203,6 +204,7 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -346,6 +348,7 @@ def test_create_order_preauth_payment_creates_expected_events(
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -457,6 +460,7 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -574,6 +578,7 @@ def test_create_order_doesnt_duplicate_order(
order_1 = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=order_data,
user=customer_user,
app=None,
@@ -583,6 +588,7 @@ def test_create_order_doesnt_duplicate_order(
order_2 = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=order_data,
user=customer_user,
app=None,
@@ -628,6 +634,7 @@ def test_create_order_with_gift_card(
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -677,6 +684,7 @@ def test_create_order_with_gift_card_partial_use(
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -739,6 +747,7 @@ def test_create_order_with_many_gift_cards(
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -807,6 +816,7 @@ def test_create_order_gift_card_bought(
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -883,6 +893,7 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -941,6 +952,7 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -967,6 +979,7 @@ def test_note_in_created_order(checkout_with_item, address, customer_user):
checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
order = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=_prepare_order_data(
manager=manager,
checkout_info=checkout_info,
@@ -1001,6 +1014,7 @@ def test_create_order_with_variant_tracking_false(
order_1 = _create_order(
checkout_info=checkout_info,
+ checkout_lines=lines,
order_data=order_data,
user=customer_user,
app=None,
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index ff603c6c08..96901e6cc7 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -32,6 +32,7 @@ from ..warehouse.availability import (
check_stock_and_preorder_quantity_bulk,
)
from ..warehouse.models import Warehouse
+from ..warehouse.reservations import reserve_stocks
from . import AddressType, calculations
from .error_codes import CheckoutErrorCode
from .fetch import (
@@ -92,8 +93,12 @@ def add_variant_to_checkout(
If `replace` is truthy then any previous quantity is discarded instead
of added to.
+
+ This function is not used outside of test suite.
"""
checkout = checkout_info.checkout
+ channel_slug = checkout_info.channel.slug
+
product_channel_listing = product_models.ProductChannelListing.objects.filter(
channel_id=checkout.channel_id, product_id=variant.product_id
).first()
@@ -103,7 +108,7 @@ def add_variant_to_checkout(
new_quantity, line = check_variant_in_stock(
checkout,
variant,
- checkout_info.channel.slug,
+ channel_slug,
quantity=quantity,
replace=replace,
check_quantity=check_quantity,
@@ -115,8 +120,11 @@ def add_variant_to_checkout(
if new_quantity == 0:
if line is not None:
line.delete()
+ line = None
elif line is None:
- checkout.lines.create(checkout=checkout, variant=variant, quantity=new_quantity)
+ line = checkout.lines.create(
+ checkout=checkout, variant=variant, quantity=new_quantity
+ )
elif new_quantity > 0:
line.quantity = new_quantity
line.save(update_fields=["quantity"])
@@ -129,7 +137,14 @@ def calculate_checkout_quantity(lines: Iterable["CheckoutLineInfo"]):
def add_variants_to_checkout(
- checkout, variants, quantities, channel_slug, skip_stock_check=False, replace=False
+ checkout,
+ variants,
+ quantities,
+ channel_slug,
+ skip_stock_check=False,
+ replace=False,
+ replace_reservations=False,
+ reservation_length: Optional[int] = None,
):
"""Add variants to checkout.
@@ -137,12 +152,15 @@ def add_variants_to_checkout(
If quantity is set to 0, checkout line will be deleted.
Otherwise, quantity will be added or replaced (if replace argument is True).
"""
-
# check quantities
country_code = checkout.get_country()
if not skip_stock_check:
check_stock_and_preorder_quantity_bulk(
- variants, country_code, quantities, channel_slug
+ variants,
+ country_code,
+ quantities,
+ channel_slug,
+ check_reservations=bool(reservation_length),
)
channel_listings = product_models.ProductChannelListing.objects.filter(
@@ -157,7 +175,8 @@ def add_variants_to_checkout(
if not product_channel_listing or not product_channel_listing.is_published:
raise ProductNotPublished()
- variant_ids_in_lines = {line.variant_id: line for line in checkout.lines.all()}
+ checkout_lines = checkout.lines.select_related("variant")
+ variant_ids_in_lines = {line.variant_id: line for line in checkout_lines}
to_create = []
to_update = []
to_delete = []
@@ -182,6 +201,24 @@ def add_variants_to_checkout(
CheckoutLine.objects.bulk_update(to_update, ["quantity"])
if to_create:
CheckoutLine.objects.bulk_create(to_create)
+
+ to_reserve = to_create + to_update
+ if reservation_length and to_reserve:
+ updated_lines_ids = [line.pk for line in to_reserve + to_delete]
+ for line in checkout_lines:
+ if line.pk not in updated_lines_ids:
+ to_reserve.append(line)
+ variants.append(line.variant)
+
+ reserve_stocks(
+ to_reserve,
+ variants,
+ country_code,
+ channel_slug,
+ reservation_length,
+ replace=replace_reservations,
+ )
+
return checkout
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.py
index d64db527ad..6128c9f39c 100644
--- a/saleor/core/exceptions.py
+++ b/saleor/core/exceptions.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, List, Optional, Union
from ..checkout.error_codes import CheckoutErrorCode
if TYPE_CHECKING:
+ from ..checkout.models import CheckoutLine
from ..order.models import OrderLine
from ..product.models import ProductVariant
@@ -11,6 +12,7 @@ if TYPE_CHECKING:
@dataclass
class InsufficientStockData:
variant: "ProductVariant"
+ checkout_line: Optional["CheckoutLine"] = None
order_line: Optional["OrderLine"] = None
warehouse_pk: Union[str, int, None] = None
available_quantity: Optional[int] = None
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 6bba22d962..9dbc0d7a70 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -41,6 +41,7 @@ from ...product.models import ProductChannelListing
from ...shipping import models as shipping_models
from ...warehouse import models as warehouse_models
from ...warehouse.availability import check_stock_and_preorder_quantity_bulk
+from ...warehouse.reservations import get_reservation_length, is_reservation_enabled
from ..account.i18n import I18nMixin
from ..account.types import AddressInput
from ..channel.utils import clean_channel
@@ -128,6 +129,7 @@ def check_lines_quantity(
allow_zero_quantity=False,
existing_lines=None,
replace=False,
+ check_reservations=False,
):
"""Clean quantities and check if stock is sufficient for each checkout line.
@@ -176,6 +178,7 @@ def check_lines_quantity(
channel_slug,
existing_lines=existing_lines,
replace=replace,
+ check_reservations=check_reservations,
)
except InsufficientStock as e:
errors = [
@@ -290,7 +293,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
@classmethod
def clean_checkout_lines(
- cls, lines, country, channel
+ cls, info, lines, country, channel
) -> Tuple[List[product_models.ProductVariant], List[int]]:
variant_ids = [line["variant_id"] for line in lines]
variants = cls.get_nodes_or_error(
@@ -308,7 +311,13 @@ class CheckoutCreate(ModelMutation, I18nMixin):
validate_variants_available_in_channel(
variant_db_ids, channel.id, CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL
)
- check_lines_quantity(variants, quantities, country, channel.slug)
+ check_lines_quantity(
+ variants,
+ quantities,
+ country,
+ channel.slug,
+ check_reservations=is_reservation_enabled(info.context.site.settings),
+ )
return variants, quantities
@classmethod
@@ -354,7 +363,12 @@ class CheckoutCreate(ModelMutation, I18nMixin):
(
cleaned_input["variants"],
cleaned_input["quantities"],
- ) = cls.clean_checkout_lines(lines, country, cleaned_input["channel"])
+ ) = cls.clean_checkout_lines(
+ info,
+ lines,
+ country,
+ cleaned_input["channel"],
+ )
# Use authenticated user's email as default email
if user.is_authenticated:
@@ -385,7 +399,13 @@ class CheckoutCreate(ModelMutation, I18nMixin):
quantities = cleaned_input.get("quantities")
if variants and quantities:
try:
- add_variants_to_checkout(instance, variants, quantities, channel.slug)
+ add_variants_to_checkout(
+ instance,
+ variants,
+ quantities,
+ channel.slug,
+ reservation_length=get_reservation_length(info.context),
+ )
except InsufficientStock as exc:
error = prepare_insufficient_stock_checkout_validation_error(exc)
raise ValidationError({"lines": error})
@@ -458,15 +478,21 @@ class CheckoutLinesAdd(BaseMutation):
@classmethod
def validate_checkout_lines(
- cls, variants, quantities, country, channel_slug, lines=None
+ cls, info, variants, quantities, country, channel_slug, lines=None
):
check_lines_quantity(
- variants, quantities, country, channel_slug, existing_lines=lines
+ variants,
+ quantities,
+ country,
+ channel_slug,
+ existing_lines=lines,
+ check_reservations=is_reservation_enabled(info.context.site.settings),
)
@classmethod
def clean_input(
cls,
+ info,
checkout,
variants,
quantities,
@@ -477,8 +503,14 @@ class CheckoutLinesAdd(BaseMutation):
replace,
):
channel_slug = checkout_info.channel.slug
+
cls.validate_checkout_lines(
- variants, quantities, checkout.get_country(), channel_slug, lines=lines
+ info,
+ variants,
+ quantities,
+ checkout.get_country(),
+ channel_slug,
+ lines=lines,
)
variants_db_ids = {variant.id for variant in variants}
validate_variants_available_for_purchase(variants_db_ids, checkout.channel_id)
@@ -497,6 +529,8 @@ class CheckoutLinesAdd(BaseMutation):
channel_slug,
skip_stock_check=True, # already checked by validate_checkout_lines
replace=replace,
+ replace_reservations=True,
+ reservation_length=get_reservation_length(info.context),
)
except ProductNotPublished as exc:
raise ValidationError(
@@ -545,6 +579,7 @@ class CheckoutLinesAdd(BaseMutation):
lines = fetch_checkout_lines(checkout)
lines = cls.clean_input(
+ info,
checkout,
variants,
quantities,
@@ -584,7 +619,13 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):
@classmethod
def validate_checkout_lines(
- cls, variants, quantities, country, channel_slug, lines=None
+ cls,
+ info,
+ variants,
+ quantities,
+ country,
+ channel_slug,
+ lines=None,
):
check_lines_quantity(
variants,
@@ -594,6 +635,7 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):
allow_zero_quantity=True,
existing_lines=lines,
replace=True,
+ check_reservations=is_reservation_enabled(info.context.site.settings),
)
@classmethod
@@ -794,7 +836,11 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
@classmethod
def process_checkout_lines(
- cls, lines: Iterable["CheckoutLineInfo"], country: str, channel_slug: str
+ cls,
+ info,
+ lines: Iterable["CheckoutLineInfo"],
+ country: str,
+ channel_slug: str,
) -> None:
variant_ids = [line_info.variant.id for line_info in lines]
variants = list(
@@ -803,7 +849,17 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
).prefetch_related("product__product_type")
) # FIXME: is this prefetch needed?
quantities = [line_info.line.quantity for line_info in lines]
- check_lines_quantity(variants, quantities, country, channel_slug)
+ check_lines_quantity(
+ variants,
+ quantities,
+ country,
+ channel_slug,
+ # Set replace=True to avoid existing_lines and quantities from
+ # being counted twice by the check_stock_quantity_bulk
+ replace=True,
+ existing_lines=lines,
+ check_reservations=is_reservation_enabled(info.context.site.settings),
+ )
@classmethod
def perform_mutation(
@@ -864,7 +920,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
# Resolve and process the lines, validating variants quantities
if lines:
- cls.process_checkout_lines(lines, country, checkout_info.channel.slug)
+ cls.process_checkout_lines(info, lines, country, checkout_info.channel.slug)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index ec84f8f655..671c6b206a 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -1,12 +1,16 @@
+from decimal import Decimal
from unittest.mock import patch
+import graphene
import pytest
from graphene import Node
from .....checkout import calculations
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
+from .....checkout.utils import add_variants_to_checkout
from .....plugins.manager import get_plugins_manager
+from .....product.models import ProductVariant, ProductVariantChannelListing
from .....warehouse.models import Stock
from ....tests.utils import get_graphql_content
@@ -156,6 +160,7 @@ FRAGMENT_CHECKOUT = (
lines {
...CheckoutLine
}
+ stockReservationExpires
isShippingRequired
discount {
currency
@@ -232,6 +237,24 @@ FRAGMENT_CHECKOUT_FOR_CC = (
)
+MUTATION_CHECKOUT_CREATE = (
+ FRAGMENT_CHECKOUT
+ + """
+ mutation CreateCheckout($checkoutInput: CheckoutCreateInput!) {
+ checkoutCreate(input: $checkoutInput) {
+ errors {
+ field
+ message
+ }
+ checkout {
+ ...Checkout
+ }
+ }
+ }
+ """
+)
+
+
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_create_checkout(
@@ -244,22 +267,6 @@ def test_create_checkout(
product_with_two_variants,
count_queries,
):
- query = (
- FRAGMENT_CHECKOUT
- + """
- mutation CreateCheckout($checkoutInput: CheckoutCreateInput!) {
- checkoutCreate(input: $checkoutInput) {
- errors {
- field
- message
- }
- checkout {
- ...Checkout
- }
- }
- }
- """
- )
checkout_counts = Checkout.objects.count()
variables = {
"checkoutInput": {
@@ -304,7 +311,7 @@ def test_create_checkout(
],
}
}
- get_graphql_content(api_client.post_graphql(query, variables))
+ get_graphql_content(api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables))
assert checkout_counts + 1 == Checkout.objects.count()
@@ -368,6 +375,102 @@ def test_create_checkout_for_cc(
assert checkout_counts + 1 == Checkout.objects.count()
[email protected]_queries(autouse=False)
+def test_create_checkout_with_reservations(
+ site_settings_with_reservations,
+ api_client,
+ product,
+ stock,
+ warehouse,
+ graphql_address_data,
+ channel_USD,
+ django_assert_num_queries,
+ count_queries,
+):
+ # TODO: replace this with MUTATION_CHECKOUT_CREATE when query number stabilizes
+ query = (
+ FRAGMENT_CHECKOUT_LINE
+ + """
+ mutation CreateCheckout($checkoutInput: CheckoutCreateInput!) {
+ checkoutCreate(input: $checkoutInput) {
+ errors {
+ field
+ message
+ }
+ checkout {
+ lines {
+ ...CheckoutLine
+ }
+ stockReservationExpires
+ }
+ }
+ }
+ """
+ )
+
+ variants = ProductVariant.objects.bulk_create(
+ [ProductVariant(product=product, sku=f"SKU_A_{i}") for i in range(10)]
+ )
+ ProductVariantChannelListing.objects.bulk_create(
+ [
+ ProductVariantChannelListing(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
+ )
+ for variant in variants
+ ]
+ )
+ Stock.objects.bulk_create(
+ [
+ Stock(product_variant=variant, warehouse=warehouse, quantity=15)
+ for variant in variants
+ ]
+ )
+
+ new_lines = []
+ for variant in variants:
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ new_lines.append({"quantity": 2, "variantId": variant_id})
+
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [new_lines[0]],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ with django_assert_num_queries(54):
+ response = api_client.post_graphql(query, variables)
+ assert get_graphql_content(response)["data"]["checkoutCreate"]
+ assert Checkout.objects.first().lines.count() == 1
+
+ Checkout.objects.all().delete()
+
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": new_lines,
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ with django_assert_num_queries(54):
+ response = api_client.post_graphql(query, variables)
+ assert get_graphql_content(response)["data"]["checkoutCreate"]
+ assert Checkout.objects.first().lines.count() == 10
+
+
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_add_shipping_to_checkout(
@@ -473,6 +576,34 @@ def test_add_billing_address_to_checkout(
assert not response["data"]["checkoutBillingAddressUpdate"]["errors"]
+MUTATION_CHECKOUT_LINES_UPDATE = (
+ FRAGMENT_CHECKOUT_LINE
+ + """
+ mutation updateCheckoutLine($token: UUID, $lines: [CheckoutLineInput]!){
+ checkoutLinesUpdate(token: $token, lines: $lines) {
+ checkout {
+ id
+ lines {
+ ...CheckoutLine
+ }
+ totalPrice {
+ ...Price
+ }
+ subtotalPrice {
+ ...Price
+ }
+ isShippingRequired
+ }
+ errors {
+ field
+ message
+ }
+ }
+ }
+ """
+)
+
+
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_update_checkout_lines(
@@ -484,32 +615,6 @@ def test_update_checkout_lines(
product_with_two_variants,
count_queries,
):
- query = (
- FRAGMENT_CHECKOUT_LINE
- + """
- mutation updateCheckoutLine($token: UUID, $lines: [CheckoutLineInput]!){
- checkoutLinesUpdate(token: $token, lines: $lines) {
- checkout {
- id
- lines {
- ...CheckoutLine
- }
- totalPrice {
- ...Price
- }
- subtotalPrice {
- ...Price
- }
- isShippingRequired
- }
- errors {
- field
- message
- }
- }
- }
- """
- )
variables = {
"token": checkout_with_items.token,
"lines": [
@@ -549,10 +654,111 @@ def test_update_checkout_lines(
},
],
}
- response = get_graphql_content(api_client.post_graphql(query, variables))
+ response = get_graphql_content(
+ api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+ )
assert not response["data"]["checkoutLinesUpdate"]["errors"]
[email protected]_queries(autouse=False)
+def test_update_checkout_lines_with_reservations(
+ site_settings_with_reservations,
+ user_api_client,
+ channel_USD,
+ checkout_with_item,
+ product,
+ stock,
+ warehouse,
+ django_assert_num_queries,
+ count_queries,
+):
+ checkout = checkout_with_item
+
+ variants = ProductVariant.objects.bulk_create(
+ [ProductVariant(product=product, sku=f"SKU_A_{i}") for i in range(10)]
+ )
+ ProductVariantChannelListing.objects.bulk_create(
+ [
+ ProductVariantChannelListing(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
+ )
+ for variant in variants
+ ]
+ )
+ Stock.objects.bulk_create(
+ [
+ Stock(product_variant=variant, warehouse=warehouse, quantity=15)
+ for variant in variants
+ ]
+ )
+
+ add_variants_to_checkout(
+ checkout,
+ variants,
+ [2] * 10,
+ channel_USD.slug,
+ replace_reservations=True,
+ reservation_length=5,
+ )
+
+ with django_assert_num_queries(59):
+ variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
+ variables = {
+ "token": checkout.token,
+ "lines": [{"quantity": 3, "variantId": variant_id}],
+ }
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_UPDATE, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+
+ # Updating multiple lines in checkout has same query count as updating one
+ with django_assert_num_queries(59):
+ variables = {
+ "token": checkout.token,
+ "lines": [],
+ }
+
+ for variant in variants:
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables["lines"].append({"quantity": 4, "variantId": variant_id})
+
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_UPDATE, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+
+
+MUTATION_CHECKOUT_LINES_ADD = (
+ FRAGMENT_CHECKOUT_LINE
+ + """
+ mutation addCheckoutLines($checkoutId: ID!, $lines: [CheckoutLineInput]!){
+ checkoutLinesAdd(checkoutId: $checkoutId, lines: $lines) {
+ checkout {
+ id
+ lines {
+ ...CheckoutLine
+ }
+ }
+ errors {
+ field
+ message
+ }
+ }
+ }
+ """
+)
+
+
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_add_checkout_lines(
@@ -564,25 +770,6 @@ def test_add_checkout_lines(
product_with_two_variants,
count_queries,
):
- query = (
- FRAGMENT_CHECKOUT_LINE
- + """
- mutation addCheckoutLines($checkoutId: ID!, $lines: [CheckoutLineInput]!){
- checkoutLinesAdd(checkoutId: $checkoutId, lines: $lines) {
- checkout {
- id
- lines {
- ...CheckoutLine
- }
- }
- errors {
- field
- message
- }
- }
- }
- """
- )
variables = {
"checkoutId": Node.to_global_id("Checkout", checkout_with_single_item.pk),
"lines": [
@@ -622,10 +809,81 @@ def test_add_checkout_lines(
},
],
}
- response = get_graphql_content(api_client.post_graphql(query, variables))
+ response = get_graphql_content(
+ api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ )
assert not response["data"]["checkoutLinesAdd"]["errors"]
[email protected]_queries(autouse=False)
+def test_add_checkout_lines_with_reservations(
+ site_settings_with_reservations,
+ user_api_client,
+ channel_USD,
+ checkout_with_item,
+ product,
+ stock,
+ warehouse,
+ django_assert_num_queries,
+ count_queries,
+):
+ checkout = checkout_with_item
+ line = checkout.lines.first()
+
+ variants = ProductVariant.objects.bulk_create(
+ [ProductVariant(product=product, sku=f"SKU_A_{i}") for i in range(10)]
+ )
+ ProductVariantChannelListing.objects.bulk_create(
+ [
+ ProductVariantChannelListing(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
+ )
+ for variant in variants
+ ]
+ )
+ Stock.objects.bulk_create(
+ [
+ Stock(product_variant=variant, warehouse=warehouse, quantity=15)
+ for variant in variants
+ ]
+ )
+
+ new_lines = []
+ for variant in variants:
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ new_lines.append({"quantity": 2, "variantId": variant_id})
+
+ # Adding multiple lines to checkout has same query count as adding one
+ with django_assert_num_queries(58):
+ variables = {
+ "checkoutId": Node.to_global_id("Checkout", checkout.pk),
+ "lines": [new_lines[0]],
+ "channelSlug": checkout.channel.slug,
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+
+ checkout.lines.exclude(id=line.id).delete()
+
+ with django_assert_num_queries(58):
+ variables = {
+ "checkoutId": Node.to_global_id("Checkout", checkout.pk),
+ "lines": new_lines,
+ "channelSlug": checkout.channel.slug,
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+
+
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_checkout_shipping_address_update(
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 9ac37e5dbe..3be5508b1e 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -10,6 +10,8 @@ import pytest
from django.core.exceptions import ValidationError
from django.db.models import Sum
from django.test import override_settings
+from django.utils import timezone
+from django.utils.dateparse import parse_datetime
from django_countries.fields import Country
from measurement.measures import Weight
from prices import Money, TaxedMoney
@@ -36,7 +38,7 @@ from ....plugins.manager import PluginsManager, get_plugins_manager
from ....plugins.tests.sample_plugins import ActiveDummyPaymentGateway
from ....product.models import ProductChannelListing, ProductVariant
from ....shipping import models as shipping_models
-from ....warehouse.models import Stock
+from ....warehouse.models import Reservation, Stock
from ...tests.utils import assert_no_permission, get_graphql_content
from ..mutations import (
clean_delivery_method,
@@ -585,6 +587,7 @@ def test_checkout_create(api_client, stock, graphql_address_data, channel_USD):
assert new_checkout.shipping_address.postal_code == shipping_address["postalCode"]
assert new_checkout.shipping_address.country == shipping_address["country"]
assert new_checkout.shipping_address.city == shipping_address["city"].upper()
+ assert not Reservation.objects.exists()
def test_checkout_create_with_invalid_channel_slug(
@@ -669,6 +672,40 @@ def test_checkout_create_multiple_warehouse(
assert checkout_line.quantity == 4
+def test_checkout_create_with_reservation(
+ site_settings_with_reservations,
+ api_client,
+ variant_with_many_stocks,
+ graphql_address_data,
+ channel_USD,
+):
+ variant = variant_with_many_stocks
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [{"quantity": 4, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ assert not Checkout.objects.exists()
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ get_graphql_content(response)["data"]["checkoutCreate"]
+
+ new_checkout = Checkout.objects.first()
+ assert new_checkout.lines.count() == 1
+ checkout_line = new_checkout.lines.first()
+ assert checkout_line
+ reservation = checkout_line.reservations.first()
+ assert reservation
+ assert reservation.checkout_line == checkout_line
+ assert reservation.quantity_reserved == checkout_line.quantity
+ assert reservation.reserved_until > timezone.now()
+
+
def test_checkout_create_with_null_as_addresses(api_client, stock, channel_USD):
"""Create checkout object using GraphQL API."""
variant = stock.product_variant
@@ -1189,6 +1226,47 @@ def test_checkout_create_check_lines_quantity(
assert data["errors"][0]["field"] == "quantity"
+def test_checkout_create_check_lines_quantity_against_reservations(
+ site_settings_with_reservations,
+ user_api_client,
+ stock,
+ graphql_address_data,
+ channel_USD,
+ checkout,
+):
+ variant = stock.product_variant
+ checkout_line = checkout.lines.create(
+ variant=variant,
+ quantity=3,
+ )
+ Reservation.objects.create(
+ checkout_line=checkout_line,
+ stock=stock,
+ quantity_reserved=3,
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 15, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
+ }
+ }
+ assert Checkout.objects.count() == 1
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutCreate"]
+ assert data["errors"][0]["message"] == (
+ "Could not add items SKU_A. Only 12 remaining in stock."
+ )
+ assert data["errors"][0]["field"] == "quantity"
+
+
def test_checkout_create_unavailable_for_purchase_product(
user_api_client, stock, graphql_address_data, channel_USD
):
@@ -1831,6 +1909,86 @@ def test_checkout_customer_attach_user_to_checkout_with_user(
assert_no_permission(response)
+GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERY = """
+query getCheckoutStockReservationExpiration($token: UUID!) {
+ checkout(token: $token) {
+ stockReservationExpires
+ }
+}
+"""
+
+
+def test_checkout_reservation_date_for_single_reservation(
+ site_settings_with_reservations,
+ api_client,
+ checkout_line_with_one_reservation,
+ address,
+):
+ reservation = Reservation.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_multiple_reservations(
+ site_settings_with_reservations,
+ api_client,
+ checkout_line_with_one_reservation,
+ checkout_line_with_reservation_in_many_stocks,
+ address,
+):
+ reservation = Reservation.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,
+ address,
+):
+ Reservation.objects.update(
+ reserved_until=timezone.now() - datetime.timedelta(minutes=1)
+ )
+
+ query = GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERY
+ variables = {"token": checkout_line_with_one_reservation.checkout.token}
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["checkout"]["stockReservationExpires"] is None
+
+
+def test_checkout_reservation_date_for_no_reservations(
+ site_settings_with_reservations,
+ api_client,
+ checkout_line_with_one_reservation,
+ address,
+):
+ Reservation.objects.all().delete()
+
+ query = GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERY
+ variables = {"token": checkout_line_with_one_reservation.checkout.token}
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["checkout"]["stockReservationExpires"] is None
+
+
+def test_checkout_reservation_date_for_disabled_reservations(
+ api_client, checkout_line_with_one_reservation, address
+):
+ query = GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERY
+ variables = {"token": checkout_line_with_one_reservation.checkout.token}
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["checkout"]["stockReservationExpires"] is None
+
+
MUTATION_CHECKOUT_CUSTOMER_DETACH = """
mutation checkoutCustomerDetach($token: UUID) {
checkoutCustomerDetach(token: $token) {
@@ -2058,6 +2216,106 @@ def test_checkout_shipping_address_update_insufficient_stocks(
assert errors[0]["field"] == "quantity"
+ "saleor.graphql.checkout.mutations.update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+@override_settings(DEFAULT_COUNTRY="DE")
+def test_checkout_shipping_address_update_with_reserved_stocks(
+ mocked_update_shipping_method,
+ site_settings_with_reservations,
+ channel_USD,
+ user_api_client,
+ variant_with_many_stocks_different_shipping_zones,
+ graphql_address_data,
+):
+ variant = variant_with_many_stocks_different_shipping_zones
+ checkout = Checkout.objects.create(channel=channel_USD, currency="USD")
+ checkout.set_country("PL", commit=True)
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ add_variant_to_checkout(checkout_info, variant, 2)
+ assert checkout.shipping_address is None
+
+ shipping_address = graphql_address_data
+ shipping_address["country"] = "US"
+ shipping_address["countryArea"] = "New York"
+ shipping_address["postalCode"] = "10001"
+ variables = {"token": checkout.token, "shippingAddress": shipping_address}
+ other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")
+ other_checkout_line = other_checkout.lines.create(
+ variant=variant,
+ quantity=1,
+ )
+ Reservation.objects.create(
+ checkout_line=other_checkout_line,
+ stock=variant.stocks.filter(
+ warehouse__shipping_zones__countries__contains="US"
+ ).first(),
+ quantity_reserved=1,
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
+ )
+
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+
+
+ "saleor.graphql.checkout.mutations.update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+@override_settings(DEFAULT_COUNTRY="DE")
+def test_checkout_shipping_address_update_against_reserved_stocks(
+ mocked_update_shipping_method,
+ site_settings_with_reservations,
+ channel_USD,
+ user_api_client,
+ variant_with_many_stocks_different_shipping_zones,
+ graphql_address_data,
+):
+ variant = variant_with_many_stocks_different_shipping_zones
+ checkout = Checkout.objects.create(channel=channel_USD, currency="USD")
+ checkout.set_country("PL", commit=True)
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ add_variant_to_checkout(checkout_info, variant, 2)
+ Stock.objects.filter(
+ warehouse__shipping_zones__countries__contains="US", product_variant=variant
+ ).update(quantity=2)
+ assert checkout.shipping_address is None
+
+ shipping_address = graphql_address_data
+ shipping_address["country"] = "US"
+ shipping_address["countryArea"] = "New York"
+ shipping_address["postalCode"] = "10001"
+ variables = {"token": checkout.token, "shippingAddress": shipping_address}
+
+ other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")
+ other_checkout_line = other_checkout.lines.create(
+ variant=variant,
+ quantity=3,
+ )
+ Reservation.objects.create(
+ checkout_line=other_checkout_line,
+ stock=variant.stocks.filter(
+ warehouse__shipping_zones__countries__contains="US"
+ ).first(),
+ quantity_reserved=3,
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
+ )
+
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ errors = data["errors"]
+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name
+ assert errors[0]["field"] == "quantity"
+
+
def test_checkout_shipping_address_update_channel_without_shipping_zones(
user_api_client,
checkout_with_item,
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index e2beb96e13..405aecc0b0 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -1,4 +1,5 @@
import uuid
+from datetime import timedelta
from decimal import Decimal
from unittest.mock import ANY, patch
@@ -6,6 +7,7 @@ import graphene
import pytest
from django.contrib.auth.models import AnonymousUser
from django.db.models.aggregates import Sum
+from django.utils import timezone
from ....checkout import calculations
from ....checkout.error_codes import CheckoutErrorCode
@@ -21,7 +23,7 @@ from ....payment import ChargeStatus, PaymentError, TransactionKind
from ....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPING
from ....payment.interface import GatewayResponse
from ....plugins.manager import PluginsManager, get_plugins_manager
-from ....warehouse.models import Stock, WarehouseClickAndCollectOption
+from ....warehouse.models import Reservation, Stock, WarehouseClickAndCollectOption
from ....warehouse.tests.utils import get_available_quantity_for_stock
from ...tests.utils import get_graphql_content
@@ -1158,6 +1160,130 @@ def test_checkout_complete_insufficient_stock_payment_voided(
)
+def test_checkout_complete_insufficient_stock_reserved_by_other_user(
+ site_settings_with_reservations,
+ user_api_client,
+ checkout_with_item,
+ address,
+ payment_dummy,
+ shipping_method,
+ channel_USD,
+):
+ checkout = checkout_with_item
+ checkout_line = checkout.lines.first()
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ quantity_available = get_available_quantity_for_stock(stock)
+
+ other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")
+ other_checkout_line = other_checkout.lines.create(
+ variant=checkout_line.variant,
+ quantity=quantity_available,
+ )
+ Reservation.objects.create(
+ checkout_line=other_checkout_line,
+ stock=stock,
+ quantity_reserved=quantity_available,
+ reserved_until=timezone.now() + timedelta(minutes=5),
+ )
+
+ checkout_line.quantity = 1
+ checkout_line.save()
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ manager = get_plugins_manager()
+ lines = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.checkout_total(
+ manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ )
+
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ variables = {"token": checkout.token, "redirectUrl": "https://www.example.com"}
+ orders_count = Order.objects.count()
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert data["errors"][0]["message"] == "Insufficient product stock: 123"
+ assert orders_count == Order.objects.count()
+
+
+def test_checkout_complete_own_reservation(
+ site_settings_with_reservations,
+ user_api_client,
+ checkout_with_item,
+ address,
+ payment_dummy,
+ shipping_method,
+ channel_USD,
+):
+ checkout = checkout_with_item
+ checkout_line = checkout.lines.first()
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ quantity_available = get_available_quantity_for_stock(stock)
+
+ checkout_line.quantity = quantity_available
+ checkout_line.save()
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ reservation = Reservation.objects.create(
+ checkout_line=checkout_line,
+ stock=stock,
+ quantity_reserved=quantity_available,
+ reserved_until=timezone.now() + timedelta(minutes=5),
+ )
+
+ manager = get_plugins_manager()
+ lines = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.checkout_total(
+ manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ )
+
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+
+ variables = {"token": checkout.token, "redirectUrl": "https://www.example.com"}
+ orders_count = Order.objects.count()
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.first()
+ assert order.token == order_token
+
+ order_line = order.lines.first()
+ assert order_line.quantity == quantity_available
+ assert order_line.variant == checkout_line.variant
+
+ assert not Checkout.objects.filter(
+ pk=checkout.pk
+ ).exists(), "Checkout should have been deleted"
+
+ # Reservation associated with checkout has been deleted
+ with pytest.raises(Reservation.DoesNotExist):
+ reservation.refresh_from_db()
+
+
def test_checkout_complete_without_redirect_url(
user_api_client,
checkout_with_gift_card,
diff --git a/saleor/graphql/checkout/tests/test_checkout_lines.py b/saleor/graphql/checkout/tests/test_checkout_lines.py
index 2949350df1..307408342f 100644
--- a/saleor/graphql/checkout/tests/test_checkout_lines.py
+++ b/saleor/graphql/checkout/tests/test_checkout_lines.py
@@ -1,16 +1,21 @@
import datetime
import uuid
+from decimal import Decimal
from unittest import mock
import graphene
import pytest
+from django.utils import timezone
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ....checkout.utils import calculate_checkout_quantity
+from ....checkout.models import Checkout
+from ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity
from ....plugins.manager import get_plugins_manager
from ....product.models import ProductChannelListing
from ....warehouse import WarehouseClickAndCollectOption
+from ....warehouse.models import Reservation, Stock
+from ....warehouse.tests.utils import get_available_quantity_for_stock
from ...tests.utils import get_graphql_content
from ..mutations import update_checkout_shipping_method_if_invalid
@@ -67,6 +72,7 @@ def test_checkout_lines_add(
assert line.variant == variant
assert line.quantity == 1
assert calculate_checkout_quantity(lines) == 4
+ assert not Reservation.objects.exists()
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout)
@@ -74,6 +80,134 @@ def test_checkout_lines_add(
mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+def test_checkout_lines_add_with_reservations(
+ site_settings_with_reservations, user_api_client, checkout_with_item, stock
+):
+ variant = stock.product_variant
+ checkout = checkout_with_item
+ line = checkout.lines.first()
+ lines = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 3
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "token": checkout.token,
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ "channelSlug": checkout.channel.slug,
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
+ line = checkout.lines.latest("pk")
+ assert line.variant == variant
+ assert line.quantity == 1
+ assert calculate_checkout_quantity(lines) == 4
+
+ reservation = line.reservations.get()
+ assert reservation
+ assert reservation.checkout_line == line
+ assert reservation.quantity_reserved == line.quantity
+
+
+def test_checkout_lines_add_updates_reservation(
+ site_settings_with_reservations,
+ user_api_client,
+ checkout_line_with_one_reservation,
+ stock,
+):
+ variant = checkout_line_with_one_reservation.variant
+ checkout = checkout_line_with_one_reservation.checkout
+ line = checkout_line_with_one_reservation
+ lines = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 2
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "token": checkout.token,
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ "channelSlug": checkout.channel.slug,
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
+ line = checkout.lines.latest("pk")
+ assert line.variant == variant
+ assert line.quantity == 3
+ assert calculate_checkout_quantity(lines) == 3
+
+ reservation = line.reservations.get()
+ assert reservation
+ assert reservation.checkout_line == line
+ assert reservation.quantity_reserved == line.quantity
+
+
+def test_checkout_lines_add_new_variant_updates_other_lines_reservations_expirations(
+ site_settings_with_reservations,
+ user_api_client,
+ checkout_line_with_one_reservation,
+ product,
+ warehouse,
+):
+ variant = checkout_line_with_one_reservation.variant
+ checkout = checkout_line_with_one_reservation.checkout
+ line = checkout_line_with_one_reservation
+ reservation = line.reservations.get()
+ lines = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 2
+
+ variant_other = product.variants.create(sku="SKU_B")
+ variant_other.channel_listings.create(
+ channel=checkout.channel,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=checkout.channel.currency_code,
+ )
+ Stock.objects.create(
+ product_variant=variant_other, warehouse=warehouse, quantity=15
+ )
+ variant_other_id = graphene.Node.to_global_id("ProductVariant", variant_other.pk)
+
+ variables = {
+ "token": checkout.token,
+ "lines": [{"variantId": variant_other_id, "quantity": 3}],
+ "channelSlug": checkout.channel.slug,
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
+ line.refresh_from_db()
+ assert line.variant == variant
+ assert line.quantity == 2
+ new_line = checkout.lines.get(variant=variant_other)
+ assert new_line.variant == variant_other
+ assert new_line.quantity == 3
+ assert calculate_checkout_quantity(lines) == 5
+
+ updated_reservation = Reservation.objects.get(checkout_line__variant=variant)
+ assert updated_reservation.checkout_line == line
+ assert updated_reservation.quantity_reserved == line.quantity
+ assert updated_reservation.reserved_until > reservation.reserved_until
+
+ other_reservation = Reservation.objects.get(checkout_line__variant=variant_other)
+ assert other_reservation.checkout_line == new_line
+ assert other_reservation.quantity_reserved == new_line.quantity
+ assert other_reservation.reserved_until > reservation.reserved_until
+
+ assert updated_reservation.reserved_until == other_reservation.reserved_until
+
+ with pytest.raises(Reservation.DoesNotExist):
+ reservation.refresh_from_db()
+
+
def test_checkout_lines_add_existing_variant(user_api_client, checkout_with_item):
checkout = checkout_with_item
line = checkout.lines.first()
@@ -156,6 +290,42 @@ def test_checkout_lines_add_with_insufficient_stock(
assert errors[0]["field"] == "quantity"
+def test_checkout_lines_add_with_reserved_insufficient_stock(
+ site_settings_with_reservations,
+ user_api_client,
+ checkout_with_item,
+ stock,
+ channel_USD,
+):
+ variant = stock.product_variant
+ checkout = checkout_with_item
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ quantity_available = get_available_quantity_for_stock(stock)
+
+ other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")
+ other_checkout_line = other_checkout.lines.create(
+ variant=variant,
+ quantity=quantity_available - 1,
+ )
+ Reservation.objects.create(
+ checkout_line=other_checkout_line,
+ stock=stock,
+ quantity_reserved=quantity_available - 1,
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
+ )
+
+ variables = {
+ "token": checkout.token,
+ "lines": [{"variantId": variant_id, "quantity": 2}],
+ "channelSlug": checkout.channel.slug,
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ content = get_graphql_content(response)
+ errors = content["data"]["checkoutLinesAdd"]["errors"]
+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name
+ assert errors[0]["field"] == "quantity"
+
+
@pytest.mark.parametrize(
"cc_option",
[
@@ -475,6 +645,164 @@ def test_checkout_lines_update(
mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+def test_checkout_lines_update_with_new_reservations(
+ site_settings_with_reservations,
+ user_api_client,
+ checkout_line_with_reservation_in_many_stocks,
+):
+ assert Reservation.objects.count() == 2
+ checkout = checkout_line_with_reservation_in_many_stocks.checkout
+ lines = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ assert calculate_checkout_quantity(lines) == 3
+ line = checkout.lines.first()
+ variant = line.variant
+ assert line.quantity == 3
+
+ Stock.objects.filter(
+ warehouse__shipping_zones__countries__contains="US", product_variant=variant
+ ).update(quantity=3)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "token": checkout.token,
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ line = checkout.lines.first()
+ assert line.variant == variant
+ assert line.quantity == 1
+ assert calculate_checkout_quantity(lines) == 1
+
+ reservation = checkout_line_with_reservation_in_many_stocks.reservations.first()
+ assert reservation.quantity_reserved == line.quantity
+
+ assert Reservation.objects.count() == 1
+
+
+def test_checkout_lines_update_against_reserved_stock(
+ site_settings_with_reservations,
+ user_api_client,
+ checkout_line,
+ stock,
+ channel_USD,
+):
+ assert Reservation.objects.count() == 0
+ checkout = checkout_line.checkout
+ lines = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ assert calculate_checkout_quantity(lines) == 3
+ variant = checkout_line.variant
+ assert checkout_line.quantity == 3
+
+ other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")
+ other_checkout_line = other_checkout.lines.create(
+ variant=variant,
+ quantity=7,
+ )
+ reservation = Reservation.objects.create(
+ checkout_line=other_checkout_line,
+ stock=variant.stocks.first(),
+ quantity_reserved=7,
+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "token": checkout.token,
+ "lines": [{"variantId": variant_id, "quantity": 5}],
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesUpdate"]
+ assert data["errors"]
+ assert data["errors"][0]["message"] == (
+ "Could not add items 123. Only 3 remaining in stock."
+ )
+ assert data["errors"][0]["field"] == "quantity"
+
+ checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ line = checkout.lines.first()
+ assert line.variant == variant
+ assert line.quantity == 3
+ assert calculate_checkout_quantity(lines) == 3
+ reservation.refresh_from_db()
+ assert Reservation.objects.count() == 1
+
+
+def test_checkout_lines_update_other_lines_reservations_expirations(
+ site_settings_with_reservations,
+ user_api_client,
+ checkout_line_with_one_reservation,
+ product,
+ warehouse,
+):
+ variant = checkout_line_with_one_reservation.variant
+ checkout = checkout_line_with_one_reservation.checkout
+ line = checkout_line_with_one_reservation
+ reservation = line.reservations.get()
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ lines = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 2
+
+ variant_other = product.variants.create(sku="SKU_B")
+ variant_other.channel_listings.create(
+ channel=checkout.channel,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=checkout.channel.currency_code,
+ )
+ Stock.objects.create(
+ product_variant=variant_other, warehouse=warehouse, quantity=15
+ )
+ add_variant_to_checkout(checkout_info, variant_other, 2)
+ variant_other_id = graphene.Node.to_global_id("ProductVariant", variant_other.pk)
+
+ variables = {
+ "token": checkout.token,
+ "lines": [{"variantId": variant_other_id, "quantity": 3}],
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines = fetch_checkout_lines(checkout)
+ line.refresh_from_db()
+ assert line.variant == variant
+ assert line.quantity == 2
+ new_line = checkout.lines.get(variant=variant_other)
+ assert new_line.variant == variant_other
+ assert new_line.quantity == 3
+ assert calculate_checkout_quantity(lines) == 5
+
+ updated_reservation = Reservation.objects.get(checkout_line__variant=variant)
+ assert updated_reservation.checkout_line == line
+ assert updated_reservation.quantity_reserved == line.quantity
+ assert updated_reservation.reserved_until > reservation.reserved_until
+
+ other_reservation = Reservation.objects.get(checkout_line__variant=variant_other)
+ assert other_reservation.checkout_line == new_line
+ assert other_reservation.quantity_reserved == new_line.quantity
+
+ assert updated_reservation.reserved_until == other_reservation.reserved_until
+
+ with pytest.raises(Reservation.DoesNotExist):
+ reservation.refresh_from_db()
+
+
def test_checkout_lines_update_with_unavailable_variant(
user_api_client, checkout_with_item
):
@@ -739,9 +1067,12 @@ MUTATION_CHECKOUT_LINES_DELETE = """
wraps=update_checkout_shipping_method_if_invalid,
)
def test_checkout_line_delete(
- mocked_update_shipping_method, user_api_client, checkout_with_item
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_line_with_reservation_in_many_stocks,
):
- checkout = checkout_with_item
+ assert Reservation.objects.count() == 2
+ checkout = checkout_line_with_reservation_in_many_stocks.checkout
lines = fetch_checkout_lines(checkout)
assert calculate_checkout_quantity(lines) == 3
assert checkout.lines.count() == 1
@@ -760,6 +1091,7 @@ def test_checkout_line_delete(
lines = fetch_checkout_lines(checkout)
assert checkout.lines.count() == 0
assert calculate_checkout_quantity(lines) == 0
+ assert Reservation.objects.count() == 0
manager = get_plugins_manager()
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index f62771f6ed..2bba7df4e1 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -10,6 +10,7 @@ from ...core.exceptions import PermissionDenied
from ...core.permissions import AccountPermissions
from ...core.taxes import zero_taxed_money
from ...core.tracing import traced_resolver
+from ...warehouse.reservations import is_reservation_enabled
from ..account.dataloaders import AddressByIdLoader
from ..account.utils import requestor_has_access
from ..channel import ChannelContext
@@ -34,7 +35,10 @@ from ..shipping.dataloaders import (
)
from ..shipping.types import ShippingMethod
from ..utils import get_user_or_app_from_context
-from ..warehouse.dataloaders import WarehouseByIdLoader
+from ..warehouse.dataloaders import (
+ StocksReservationsByCheckoutTokenLoader,
+ WarehouseByIdLoader,
+)
from ..warehouse.types import Warehouse
from .dataloaders import (
CheckoutByTokenLoader,
@@ -200,6 +204,12 @@ class Checkout(CountableDjangoObjectType):
description="Returns True, if checkout requires shipping.", required=True
)
quantity = graphene.Int(required=True, description="The number of items purchased.")
+ stock_reservation_expires = graphene.DateTime(
+ description=(
+ f"{ADDED_IN_31} Date when oldest stock reservation for this checkout "
+ " expires or null if no stock is reserved."
+ ),
+ )
lines = graphene.List(
CheckoutLine,
description=(
@@ -547,3 +557,21 @@ class Checkout(CountableDjangoObjectType):
@staticmethod
def resolve_language_code(root, _info, **_kwargs):
return LanguageCodeEnum[str_to_enum(root.language_code)]
+
+ @staticmethod
+ @traced_resolver
+ def resolve_stock_reservation_expires(root: models.Checkout, info):
+ if not is_reservation_enabled(info.context.site.settings):
+ return None
+
+ def get_oldest_stock_reservation_expiration_date(reservations):
+ if not reservations:
+ return None
+
+ return min(reservation.reserved_until for reservation in reservations)
+
+ return (
+ StocksReservationsByCheckoutTokenLoader(info.context)
+ .load(root.token)
+ .then(get_oldest_stock_reservation_expiration_date)
+ )
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 7e78d58e4f..09d012e286 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -20,6 +20,7 @@ from ....order.utils import (
update_order_prices,
)
from ....warehouse.management import allocate_preorders, allocate_stocks
+from ....warehouse.reservations import is_reservation_enabled
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...channel.types import Channel
@@ -447,7 +448,15 @@ class DraftOrderComplete(BaseMutation):
channel_slug = order.channel.slug
try:
with traced_atomic_transaction():
- allocate_stocks([line_data], country, channel_slug, manager)
+ allocate_stocks(
+ [line_data],
+ country,
+ channel_slug,
+ manager,
+ check_reservations=is_reservation_enabled(
+ info.context.site.settings
+ ),
+ )
allocate_preorders([line_data], channel_slug)
except InsufficientStock as exc:
errors = prepare_insufficient_stock_order_validation_errors(exc)
diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.py
index f40ffa3cc9..a1584cbc81 100644
--- a/saleor/graphql/product/tests/test_variant_availability.py
+++ b/saleor/graphql/product/tests/test_variant_availability.py
@@ -1,8 +1,12 @@
+from datetime import timedelta
+
import graphene
from django.test import override_settings
+from django.utils import timezone
from django_countries import countries
from ....shipping.models import ShippingZone
+from ....warehouse.models import Reservation
from ...tests.utils import get_graphql_content
COUNTRY_CODE = "US"
@@ -192,6 +196,63 @@ def test_variant_quantity_available_with_allocations(
assert variant_data["byAddress"] == 3
+def test_variant_quantity_available_with_enabled_reservations(
+ site_settings_with_reservations,
+ api_client,
+ checkout_line_with_reservation_in_many_stocks,
+ channel_USD,
+):
+ variant = checkout_line_with_reservation_in_many_stocks.variant
+ 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"] == 4
+ assert variant_data["byAddress"] == 4
+
+
+def test_variant_quantity_available_with_enabled_expired_reservations(
+ site_settings_with_reservations,
+ api_client,
+ checkout_line_with_reservation_in_many_stocks,
+ channel_USD,
+):
+ Reservation.objects.update(reserved_until=timezone.now() - timedelta(minutes=2))
+ variant = checkout_line_with_reservation_in_many_stocks.variant
+ 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"] == 7
+ assert variant_data["byAddress"] == 7
+
+
+def test_variant_quantity_available_with_disabled_reservations(
+ api_client,
+ checkout_line_with_reservation_in_many_stocks,
+ channel_USD,
+):
+ variant = checkout_line_with_reservation_in_many_stocks.variant
+ 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"] == 7
+ 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
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 99c21b0b00..f8cebcc2ba 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1017,6 +1017,7 @@ type Checkout implements Node & ObjectWithMetadata {
email: String!
isShippingRequired: Boolean!
quantity: Int!
+ stockReservationExpires: DateTime
lines: [CheckoutLine]
shippingPrice: TaxedMoney
shippingMethod: ShippingMethod @deprecated(reason: "This field will be removed in Saleor 4.0. Use `deliveryMethod` instead.")
@@ -6360,6 +6361,8 @@ type Shop {
defaultWeightUnit: WeightUnitsEnum
translation(languageCode: LanguageCodeEnum!): ShopTranslation
automaticFulfillmentDigitalProducts: Boolean
+ reserveStockDurationAnonymousUser: Int
+ reserveStockDurationAuthenticatedUser: Int
defaultDigitalMaxDownloads: Int
defaultDigitalUrlValidDays: Int
companyAddress: Address
@@ -6419,6 +6422,8 @@ input ShopSettingsInput {
defaultMailSenderName: String
defaultMailSenderAddress: String
customerSetPasswordUrl: String
+ reserveStockDurationAnonymousUser: Int
+ reserveStockDurationAuthenticatedUser: Int
}
type ShopSettingsTranslate {
@@ -6551,6 +6556,7 @@ type Stock implements Node {
quantity: Int!
id: ID!
quantityAllocated: Int!
+ quantityReserved: Int!
}
enum StockAvailability {
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index 68e22888f5..1baf8b2e8b 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -60,6 +60,18 @@ class ShopSettingsInput(graphene.InputObjectType):
customer_set_password_url = graphene.String(
description="URL of a view where customers can set their password."
)
+ reserve_stock_duration_anonymous_user = graphene.Int(
+ description=(
+ f"{ADDED_IN_31} Default number of minutes stock will be reserved for "
+ "anonymous checkout. Enter 0 or null to disable."
+ )
+ )
+ reserve_stock_duration_authenticated_user = graphene.Int(
+ description=(
+ f"{ADDED_IN_31} Default number of minutes stock will be reserved for "
+ "authenticated checkout. Enter 0 or null to disable."
+ )
+ )
class SiteDomainInput(graphene.InputObjectType):
@@ -90,6 +102,16 @@ class ShopSettingsUpdate(BaseMutation):
raise ValidationError(
{"customer_set_password_url": error}, code=ShopErrorCode.INVALID
)
+
+ if "reserve_stock_duration_anonymous_user" in data:
+ new_value = data["reserve_stock_duration_anonymous_user"]
+ if not new_value or new_value < 1:
+ data["reserve_stock_duration_anonymous_user"] = None
+ if "reserve_stock_duration_authenticated_user" in data:
+ new_value = data["reserve_stock_duration_authenticated_user"]
+ if not new_value or new_value < 1:
+ data["reserve_stock_duration_authenticated_user"] = None
+
return data
@classmethod
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index 25b1be688f..d7211e1607 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -359,6 +359,111 @@ def test_shop_settings_mutation(
assert site_settings.charge_taxes_on_shipping == new_charge_taxes_on_shipping
+def test_shop_reservation_settings_mutation(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ query = """
+ mutation updateSettings($input: ShopSettingsInput!) {
+ shopSettingsUpdate(input: $input) {
+ shop {
+ reserveStockDurationAnonymousUser
+ reserveStockDurationAuthenticatedUser
+ }
+ errors {
+ field,
+ message
+ }
+ }
+ }
+ """
+ variables = {
+ "input": {
+ "reserveStockDurationAnonymousUser": 42,
+ "reserveStockDurationAuthenticatedUser": 24,
+ }
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+ assert data["reserveStockDurationAnonymousUser"] == 42
+ assert data["reserveStockDurationAuthenticatedUser"] == 24
+ site_settings.refresh_from_db()
+ assert site_settings.reserve_stock_duration_anonymous_user == 42
+ assert site_settings.reserve_stock_duration_authenticated_user == 24
+
+
+def test_shop_reservation_disable_settings_mutation(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ query = """
+ mutation updateSettings($input: ShopSettingsInput!) {
+ shopSettingsUpdate(input: $input) {
+ shop {
+ reserveStockDurationAnonymousUser
+ reserveStockDurationAuthenticatedUser
+ }
+ errors {
+ field,
+ message
+ }
+ }
+ }
+ """
+ variables = {
+ "input": {
+ "reserveStockDurationAnonymousUser": None,
+ "reserveStockDurationAuthenticatedUser": None,
+ }
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+ assert data["reserveStockDurationAnonymousUser"] is None
+ assert data["reserveStockDurationAuthenticatedUser"] is None
+ site_settings.refresh_from_db()
+ assert site_settings.reserve_stock_duration_anonymous_user is None
+ assert site_settings.reserve_stock_duration_authenticated_user is None
+
+
+def test_shop_reservation_set_negative_settings_mutation(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ query = """
+ mutation updateSettings($input: ShopSettingsInput!) {
+ shopSettingsUpdate(input: $input) {
+ shop {
+ reserveStockDurationAnonymousUser
+ reserveStockDurationAuthenticatedUser
+ }
+ errors {
+ field,
+ message
+ }
+ }
+ }
+ """
+ variables = {
+ "input": {
+ "reserveStockDurationAnonymousUser": -14,
+ "reserveStockDurationAuthenticatedUser": -6,
+ }
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_settings]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shopSettingsUpdate"]["shop"]
+ assert data["reserveStockDurationAnonymousUser"] is None
+ assert data["reserveStockDurationAuthenticatedUser"] is None
+ site_settings.refresh_from_db()
+ assert site_settings.reserve_stock_duration_anonymous_user is None
+ assert site_settings.reserve_stock_duration_authenticated_user is None
+
+
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.py
index 95912f8f26..8a8ecfdd28 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -217,6 +217,19 @@ class Shop(graphene.ObjectType):
description="Enable automatic fulfillment for all digital products."
)
+ reserve_stock_duration_anonymous_user = graphene.Int(
+ description=(
+ f"{ADDED_IN_31} Default number of minutes stock will be reserved for "
+ "anonymous checkout or null when stock reservation is disabled."
+ )
+ )
+ reserve_stock_duration_authenticated_user = graphene.Int(
+ description=(
+ f"{ADDED_IN_31} Default number of minutes stock will be reserved for "
+ "authenticated checkout or null when stock reservation is disabled."
+ )
+ )
+
default_digital_max_downloads = graphene.Int(
description="Default number of max downloads per digital content URL."
)
@@ -395,6 +408,18 @@ class Shop(graphene.ObjectType):
site_settings = info.context.site.settings
return site_settings.automatic_fulfillment_digital_products
+ @staticmethod
+ @permission_required(SitePermissions.MANAGE_SETTINGS)
+ def resolve_reserve_stock_duration_anonymous_user(_, info):
+ site_settings = info.context.site.settings
+ return site_settings.reserve_stock_duration_anonymous_user
+
+ @staticmethod
+ @permission_required(SitePermissions.MANAGE_SETTINGS)
+ def resolve_reserve_stock_duration_authenticated_user(_, info):
+ site_settings = info.context.site.settings
+ return site_settings.reserve_stock_duration_authenticated_user
+
@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.py
index b8f47d9688..64c8210581 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -6,7 +6,8 @@ from django.conf import settings
from django.db.models import Exists, OuterRef
from ...channel.models import Channel
-from ...warehouse.models import ShippingZone, Stock, Warehouse
+from ...warehouse.models import Reservation, ShippingZone, Stock, Warehouse
+from ...warehouse.reservations import is_reservation_enabled
from ..core.dataloaders import DataLoader
CountryCode = Optional[str]
@@ -96,6 +97,19 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
stocks = stocks.filter(warehouse_id__in=warehouse_shipping_zones_map.keys())
stocks = stocks.annotate_available_quantity()
+ stocks_reservations = defaultdict(int)
+ if is_reservation_enabled(self.context.site.settings): # type: ignore
+ # Can't do second annotation on same queryset because it made
+ # available_quantity annotated value incorrect thanks to how
+ # Django's ORM builds SQLs with annotations
+ reservations_qs = (
+ Stock.objects.filter(product_variant_id__in=variant_ids)
+ .annotate_reserved_quantity()
+ .values_list("id", "reserved_quantity")
+ )
+ for stock_id, quantity_reserved in reservations_qs:
+ stocks_reservations[stock_id] = quantity_reserved
+
# A single country code (or a missing country code) can return results from
# multiple shipping zones. We want to combine all quantities within a single
# zone and then find out which zone contains the highest total.
@@ -103,7 +117,8 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
int, DefaultDict[int, int]
] = defaultdict(lambda: defaultdict(int))
for stock in stocks:
- quantity = max(0, stock.available_quantity)
+ reserved_quantity = stocks_reservations[stock.id]
+ quantity = max(0, stock.available_quantity - reserved_quantity)
variant_id = stock.product_variant_id
warehouse_id = stock.warehouse_id
shipping_zone_ids = warehouse_shipping_zones_map[warehouse_id]
@@ -206,6 +221,55 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
]
+class StocksReservationsByCheckoutTokenLoader(DataLoader):
+ context_key = "stock_reservations_by_checkout_token"
+
+ def batch_load(self, keys):
+ from ..checkout.dataloaders import CheckoutLinesByCheckoutTokenLoader
+
+ def with_checkouts_lines(checkouts_lines):
+ checkouts_keys_map = {}
+ for i, key in enumerate(keys):
+ for checkout_line in checkouts_lines[i]:
+ checkouts_keys_map[checkout_line.id] = key
+
+ def with_lines_reservations(lines_reservations):
+ reservations_map = defaultdict(list)
+ for reservations in lines_reservations:
+ for reservation in reservations:
+ checkout_key = checkouts_keys_map[reservation.checkout_line_id]
+ reservations_map[checkout_key].append(reservation)
+
+ return [reservations_map[key] for key in keys]
+
+ return (
+ ActiveReservationsByCheckoutLineIdLoader(self.context)
+ .load_many(checkouts_keys_map.keys())
+ .then(with_lines_reservations)
+ )
+
+ return (
+ CheckoutLinesByCheckoutTokenLoader(self.context)
+ .load_many(keys)
+ .then(with_checkouts_lines)
+ )
+
+
+class ActiveReservationsByCheckoutLineIdLoader(DataLoader):
+ context_key = "active_reservations_by_checkout_line_id"
+
+ def batch_load(self, keys):
+ reservations_by_checkout_line = defaultdict(list)
+ 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
+ )
+ return [reservations_by_checkout_line[key] for key in keys]
+
+
class WarehouseByIdLoader(DataLoader):
context_key = "warehouse_by_id"
diff --git a/saleor/graphql/warehouse/tests/test_stock.py b/saleor/graphql/warehouse/tests/test_stock.py
index 873fdb60a6..8b4b382f65 100644
--- a/saleor/graphql/warehouse/tests/test_stock.py
+++ b/saleor/graphql/warehouse/tests/test_stock.py
@@ -1,7 +1,10 @@
+from datetime import timedelta
+
import graphene
+from django.utils import timezone
from ....core.permissions import ProductPermissions
-from ....warehouse.models import Stock, Warehouse
+from ....warehouse.models import Reservation, Stock, Warehouse
from ....warehouse.tests.utils import get_quantity_allocated_for_stock
from ...tests.utils import (
assert_no_permission,
@@ -22,6 +25,7 @@ query stock($id: ID!) {
}
quantity
quantityAllocated
+ quantityReserved
}
}
"""
@@ -44,6 +48,7 @@ QUERY_STOCKS = """
}
quantity
quantityAllocated
+ quantityReserved
}
}
}
@@ -84,6 +89,52 @@ def test_query_stock(staff_api_client, stock, permission_manage_products):
assert content_stock["warehouse"]["name"] == stock.warehouse.name
assert content_stock["quantity"] == stock.quantity
assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)
+ assert content_stock["quantityReserved"] == 0
+
+
+def test_query_stock_with_reservations(
+ site_settings_with_reservations,
+ staff_api_client,
+ stock,
+ checkout_line_with_reservation_in_many_stocks,
+ permission_manage_products,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ stock_id = graphene.Node.to_global_id("Stock", stock.pk)
+ response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
+ content = get_graphql_content(response)
+ content_stock = content["data"]["stock"]
+ assert (
+ content_stock["productVariant"]["product"]["name"]
+ == stock.product_variant.product.name
+ )
+ assert content_stock["warehouse"]["name"] == stock.warehouse.name
+ assert content_stock["quantity"] == stock.quantity
+ assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)
+ assert content_stock["quantityReserved"] == 2
+
+
+def test_query_stock_with_expired_reservations(
+ site_settings_with_reservations,
+ staff_api_client,
+ stock,
+ checkout_line_with_reservation_in_many_stocks,
+ permission_manage_products,
+):
+ Reservation.objects.update(reserved_until=timezone.now() - timedelta(minutes=2))
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ stock_id = graphene.Node.to_global_id("Stock", stock.pk)
+ response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
+ content = get_graphql_content(response)
+ content_stock = content["data"]["stock"]
+ assert (
+ content_stock["productVariant"]["product"]["name"]
+ == stock.product_variant.product.name
+ )
+ assert content_stock["warehouse"]["name"] == stock.warehouse.name
+ assert content_stock["quantity"] == stock.quantity
+ assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)
+ assert content_stock["quantityReserved"] == 0
def test_staff_query_stock_by_invalid_id(
diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.py
index 2e3e650175..600f481ae5 100644
--- a/saleor/graphql/warehouse/types.py
+++ b/saleor/graphql/warehouse/types.py
@@ -1,9 +1,11 @@
import graphene
-from django.db.models import Sum
+from django.db.models import Q, Sum
from django.db.models.functions import Coalesce
+from django.utils import timezone
from ...core.permissions import OrderPermissions, ProductPermissions
from ...warehouse import models
+from ...warehouse.reservations import is_reservation_enabled
from ..account.dataloaders import AddressByIdLoader
from ..channel import ChannelContext
from ..core.connection import CountableDjangoObjectType
@@ -103,12 +105,21 @@ class Stock(CountableDjangoObjectType):
quantity_allocated = graphene.Int(
required=True, description="Quantity allocated for orders"
)
+ quantity_reserved = graphene.Int(
+ required=True, description="Quantity reserved for checkouts"
+ )
class Meta:
description = "Represents stock."
model = models.Stock
interfaces = [graphene.relay.Node]
- only_fields = ["warehouse", "product_variant", "quantity", "quantity_allocated"]
+ only_fields = [
+ "warehouse",
+ "product_variant",
+ "quantity",
+ "quantity_allocated",
+ "quantity_reserved",
+ ]
@staticmethod
@one_of_permissions_required(
@@ -126,6 +137,24 @@ class Stock(CountableDjangoObjectType):
quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)
)["quantity_allocated"]
+ @staticmethod
+ @one_of_permissions_required(
+ [ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS]
+ )
+ def resolve_quantity_reserved(root, info, *_args):
+ if not is_reservation_enabled(info.context.site.settings):
+ return 0
+
+ return root.reservations.aggregate(
+ quantity_reserved=Coalesce(
+ Sum(
+ "quantity_reserved",
+ filter=Q(reserved_until__gt=timezone.now()),
+ ),
+ 0,
+ )
+ )["quantity_reserved"]
+
@staticmethod
def resolve_product_variant(root, *_args):
return ChannelContext(node=root.product_variant, channel_slug=None)
diff --git a/saleor/settings.py b/saleor/settings.py
index b611a2715f..3696701159 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -490,6 +490,10 @@ CELERY_BEAT_SCHEDULE = {
"task": "saleor.product.tasks.deactivate_preorder_for_variants_task",
"schedule": timedelta(hours=1),
},
+ "delete-expired-reservations": {
+ "task": "saleor.warehouse.tasks.delete_expired_reservations_task",
+ "schedule": timedelta(days=1),
+ },
}
# Change this value if your application is running behind a proxy,
diff --git a/saleor/site/migrations/0033_sitesettings_reserve_stock_duration_minutes.py b/saleor/site/migrations/0033_sitesettings_reserve_stock_duration_minutes.py
new file mode 100644
index 0000000000..693b46d319
--- /dev/null
+++ b/saleor/site/migrations/0033_sitesettings_reserve_stock_duration_minutes.py
@@ -0,0 +1,23 @@
+# Generated by Django 3.2.5 on 2021-07-26 14:51
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("site", "0032_gift_card_settings"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sitesettings",
+ name="reserve_stock_duration_anonymous_user",
+ field=models.IntegerField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="sitesettings",
+ name="reserve_stock_duration_authenticated_user",
+ field=models.IntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 56c075ed9e..43f088ac5a 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -70,6 +70,12 @@ class SiteSettings(models.Model):
fulfillment_auto_approve = models.BooleanField(default=True)
fulfillment_allow_unpaid = models.BooleanField(default=True)
+ # Duration in minutes
+ reserve_stock_duration_anonymous_user = models.IntegerField(blank=True, null=True)
+ reserve_stock_duration_authenticated_user = models.IntegerField(
+ blank=True, null=True
+ )
+
# gift card settings
gift_card_expiry_type = models.CharField(
max_length=32,
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index c5e1dd3e1f..4d0a2adcec 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -2,6 +2,7 @@ import datetime
import uuid
from collections import namedtuple
from contextlib import contextmanager
+from datetime import timedelta
from decimal import Decimal
from functools import partial
from io import BytesIO
@@ -110,7 +111,13 @@ from ..shipping.models import (
)
from ..site.models import SiteSettings
from ..warehouse import WarehouseClickAndCollectOption
-from ..warehouse.models import Allocation, PreorderAllocation, Stock, Warehouse
+from ..warehouse.models import (
+ Allocation,
+ PreorderAllocation,
+ Reservation,
+ Stock,
+ Warehouse,
+)
from ..webhook.event_types import WebhookEventType
from ..webhook.models import Webhook, WebhookEvent
from ..wishlist.models import Wishlist
@@ -262,6 +269,14 @@ def site_settings(db, settings) -> SiteSettings:
return obj
+def site_settings_with_reservations(site_settings):
+ site_settings.reserve_stock_duration_anonymous_user = 5
+ site_settings.reserve_stock_duration_authenticated_user = 5
+ site_settings.save()
+ return site_settings
+
+
@pytest.fixture
def checkout(db, channel_USD):
checkout = Checkout.objects.create(
@@ -280,6 +295,11 @@ def checkout_with_item(checkout, product):
return checkout
+def checkout_line(checkout_with_item):
+ return checkout_with_item.lines.first()
+
+
@pytest.fixture
def checkouts_list(channel_USD, channel_PLN):
checkouts_usd = Checkout.objects.bulk_create(
@@ -2965,6 +2985,64 @@ def order_line_with_one_allocation(
return order_line
+def checkout_line_with_reservation_in_many_stocks(
+ customer_user, variant_with_many_stocks, checkout
+):
+ address = customer_user.default_billing_address.get_copy()
+ variant = variant_with_many_stocks
+ stocks = variant.stocks.all().order_by("pk")
+ checkout_line = checkout.lines.create(
+ variant=variant,
+ quantity=3,
+ )
+
+ reserved_until = timezone.now() + timedelta(minutes=5)
+
+ Reservation.objects.bulk_create(
+ [
+ Reservation(
+ checkout_line=checkout_line,
+ stock=stocks[0],
+ quantity_reserved=2,
+ reserved_until=reserved_until,
+ ),
+ Reservation(
+ checkout_line=checkout_line,
+ stock=stocks[1],
+ quantity_reserved=1,
+ reserved_until=reserved_until,
+ ),
+ ]
+ )
+
+ return checkout_line
+
+
+def checkout_line_with_one_reservation(
+ customer_user, variant_with_many_stocks, checkout
+):
+ address = customer_user.default_billing_address.get_copy()
+ variant = variant_with_many_stocks
+ stocks = variant.stocks.all().order_by("pk")
+ checkout_line = checkout.lines.create(
+ variant=variant,
+ quantity=2,
+ )
+
+ reserved_until = timezone.now() + timedelta(minutes=5)
+
+ Reservation.objects.create(
+ checkout_line=checkout_line,
+ stock=stocks[0],
+ quantity_reserved=2,
+ reserved_until=reserved_until,
+ )
+
+ return checkout_line
+
+
@pytest.fixture
def gift_card(customer_user):
return GiftCard.objects.create(
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index 6f2830bf3a..34ae6067e4 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -6,13 +6,19 @@ from django.db.models.functions import Coalesce
from ..core.exceptions import InsufficientStock, InsufficientStockData
from ..product.models import ProductVariantChannelListing
-from .models import Stock, StockQuerySet
+from .models import Reservation, Stock, StockQuerySet
if TYPE_CHECKING:
- from ..product.models import ProductVariant
+ from ..checkout.fetch import CheckoutLineInfo
+ from ..checkout.models import CheckoutLine
+ from ..product.models import Product, ProductVariant
-def _get_available_quantity(stocks: StockQuerySet) -> int:
+def _get_available_quantity(
+ stocks: StockQuerySet,
+ checkout_lines: Optional[List["CheckoutLine"]] = None,
+ check_reservations: bool = False,
+) -> int:
results = stocks.aggregate(
total_quantity=Coalesce(Sum("quantity", distinct=True), 0),
quantity_allocated=Coalesce(Sum("allocations__quantity_allocated"), 0),
@@ -20,7 +26,12 @@ def _get_available_quantity(stocks: StockQuerySet) -> int:
total_quantity = results["total_quantity"]
quantity_allocated = results["quantity_allocated"]
- return max(total_quantity - quantity_allocated, 0)
+ if check_reservations:
+ quantity_reserved = get_reserved_quantity(stocks, checkout_lines)
+ else:
+ quantity_reserved = 0
+
+ return max(total_quantity - quantity_allocated - quantity_reserved, 0)
def check_stock_and_preorder_quantity(
@@ -38,7 +49,12 @@ def check_stock_and_preorder_quantity(
def check_stock_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 available for given variant in given country.
@@ -52,7 +68,10 @@ def check_stock_quantity(
if not stocks:
raise InsufficientStock([InsufficientStockData(variant=variant)])
- if quantity > _get_available_quantity(stocks):
+ available_quantity = _get_available_quantity(
+ stocks, checkout_lines, check_reservations
+ )
+ if quantity > available_quantity:
raise InsufficientStock([InsufficientStockData(variant=variant)])
@@ -64,6 +83,7 @@ def check_stock_and_preorder_quantity_bulk(
additional_filter_lookup: Optional[Dict[str, Any]] = None,
existing_lines: Iterable = None,
replace: bool = False,
+ check_reservations: bool = False,
):
"""Validate if products are available for stocks/preorder.
@@ -85,6 +105,7 @@ def check_stock_and_preorder_quantity_bulk(
additional_filter_lookup,
existing_lines,
replace,
+ check_reservations,
)
if preorder_variants:
check_preorder_threshold_bulk(
@@ -122,8 +143,9 @@ def check_stock_quantity_bulk(
quantities: Iterable[int],
channel_slug: str,
additional_filter_lookup: Optional[Dict[str, Any]] = None,
- existing_lines: Iterable = None,
+ existing_lines: Iterable["CheckoutLineInfo"] = None,
replace=False,
+ check_reservations: bool = False,
):
"""Validate if there is stock available for given variants in given country.
@@ -143,6 +165,14 @@ def check_stock_quantity_bulk(
for stock in all_variants_stocks:
variant_stocks[stock.product_variant_id].append(stock)
+ if check_reservations:
+ variant_reservations = get_reserved_quantity_bulk(
+ all_variants_stocks,
+ [line.line for line in existing_lines] if existing_lines else [],
+ )
+ else:
+ variant_reservations = defaultdict(int)
+
insufficient_stocks: List[InsufficientStockData] = []
variants_quantities = {
line.variant.pk: line.line.quantity for line in existing_lines or []
@@ -155,6 +185,9 @@ def check_stock_quantity_bulk(
available_quantity = sum(
[stock.available_quantity for stock in stocks] # type: ignore
)
+ available_quantity = max(
+ available_quantity - variant_reservations[variant.pk], 0
+ )
if quantity > 0:
if not stocks:
@@ -240,3 +273,75 @@ def check_preorder_threshold_bulk(
if insufficient_stocks:
raise InsufficientStock(insufficient_stocks)
+
+
+def get_available_quantity(
+ variant: "ProductVariant",
+ country_code: str,
+ channel_slug: str,
+ checkout_lines: Optional[List["CheckoutLine"]] = None,
+ check_reservations: bool = False,
+) -> int:
+ """Return available quantity for given product in given country."""
+ stocks = Stock.objects.get_variant_stocks_for_country(
+ country_code, channel_slug, variant
+ )
+ if not stocks:
+ return 0
+ return _get_available_quantity(stocks, checkout_lines, check_reservations)
+
+
+def is_product_in_stock(
+ product: "Product", country_code: str, channel_slug: str
+) -> bool:
+ """Check if there is any variant of given product available in given country."""
+ stocks = Stock.objects.get_product_stocks_for_country_and_channel(
+ country_code, channel_slug, product
+ ).annotate_available_quantity()
+ return any(stocks.values_list("available_quantity", flat=True))
+
+
+def get_reserved_quantity(
+ stocks: StockQuerySet, lines: Optional[List["CheckoutLine"]] = None
+) -> int:
+ result = (
+ Reservation.objects.filter(
+ stock__in=stocks,
+ )
+ .not_expired()
+ .exclude_checkout_lines(lines)
+ .aggregate(
+ quantity_reserved=Coalesce(Sum("quantity_reserved"), 0),
+ )
+ ) # type: ignore
+
+ return result["quantity_reserved"]
+
+
+def get_reserved_quantity_bulk(
+ stocks: Iterable[Stock],
+ checkout_lines: Iterable["CheckoutLine"],
+) -> Dict[int, int]:
+ reservations: Dict[int, int] = defaultdict(int)
+ if not stocks:
+ return reservations
+
+ result = (
+ Reservation.objects.filter(
+ stock__in=stocks,
+ )
+ .not_expired()
+ .exclude_checkout_lines(checkout_lines)
+ .values("stock_id")
+ .annotate(
+ quantity_reserved=Coalesce(Sum("quantity_reserved"), 0),
+ )
+ ) # type: ignore
+
+ stocks_variants = {stock.id: stock.product_variant_id for stock in stocks}
+ for stock_reservations in result:
+ variant_id = stocks_variants.get(stock_reservations["stock_id"])
+ if variant_id:
+ reservations[variant_id] += stock_reservations["quantity_reserved"]
+
+ return reservations
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 4c75f27b0a..53195da15a 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -3,7 +3,9 @@ from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, ca
from django.db import transaction
from django.db.models import F, Sum
+from django.db.models.functions import Coalesce
+from ..checkout.models import CheckoutLine
from ..core.exceptions import (
AllocationError,
InsufficientStock,
@@ -14,7 +16,7 @@ from ..core.tracing import traced_atomic_transaction
from ..order import OrderLineData
from ..plugins.manager import PluginsManager
from ..product.models import ProductVariant, ProductVariantChannelListing
-from .models import Allocation, PreorderAllocation, Stock, Warehouse
+from .models import Allocation, PreorderAllocation, Reservation, Stock, Warehouse
if TYPE_CHECKING:
from ..order.models import Order, OrderLine
@@ -30,6 +32,8 @@ def allocate_stocks(
channel_slug: str,
manager: PluginsManager,
additional_filter_lookup: Optional[Dict[str, Any]] = None,
+ check_reservations: bool = False,
+ checkout_lines: Optional[Iterable["CheckoutLine"]] = None,
):
"""Allocate stocks for given `order_lines` in given country.
@@ -59,7 +63,26 @@ def allocate_stocks(
.order_by("pk")
.values("id", "product_variant", "pk", "quantity")
)
- stocks_id = (stock.pop("id") for stock in stocks)
+ stocks_id = [stock.pop("id") for stock in stocks]
+
+ quantity_reservation_for_stocks: Dict = defaultdict(int)
+
+ if check_reservations:
+ quantity_reservation = (
+ Reservation.objects.filter(
+ stock_id__in=stocks_id,
+ )
+ .not_expired()
+ .exclude_checkout_lines(checkout_lines or [])
+ .values("stock")
+ .annotate(
+ quantity_reserved=Coalesce(Sum("quantity_reserved"), 0),
+ )
+ ) # type: ignore
+ for reservation in quantity_reservation:
+ quantity_reservation_for_stocks[reservation["stock"]] += reservation[
+ "quantity_reserved"
+ ]
quantity_allocation_list = list(
Allocation.objects.filter(
@@ -89,6 +112,7 @@ def allocate_stocks(
line_info,
stock_allocations,
quantity_allocation_for_stocks,
+ quantity_reservation_for_stocks,
insufficient_stock,
)
allocations.extend(allocation_items)
@@ -115,18 +139,17 @@ def allocate_stocks(
def _create_allocations(
line_info: "OrderLineData",
stocks: List[StockData],
- quantity_allocation_for_stocks: dict,
+ stocks_allocations: dict,
+ stocks_reservations: dict,
insufficient_stock: List[InsufficientStockData],
):
quantity = line_info.quantity
quantity_allocated = 0
allocations = []
for stock_data in stocks:
- quantity_allocated_in_stock = quantity_allocation_for_stocks.get(
- stock_data.pk, 0
- )
-
- quantity_available_in_stock = stock_data.quantity - quantity_allocated_in_stock
+ quantity_available_in_stock = stock_data.quantity
+ quantity_available_in_stock -= stocks_allocations.get(stock_data.pk, 0)
+ quantity_available_in_stock -= stocks_reservations.get(stock_data.pk, 0)
quantity_to_allocate = min(
(quantity - quantity_allocated), quantity_available_in_stock
diff --git a/saleor/warehouse/migrations/0018_auto_20210323_2116.py b/saleor/warehouse/migrations/0018_auto_20210323_2116.py
new file mode 100644
index 0000000000..1433001ba3
--- /dev/null
+++ b/saleor/warehouse/migrations/0018_auto_20210323_2116.py
@@ -0,0 +1,61 @@
+# Generated by Django 3.1.7 on 2021-03-23 21:16
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("checkout", "0034_remove_checkout_quantity"),
+ ("warehouse", "0017_preorderallocation"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="Reservation",
+ 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="reservations",
+ to="checkout.checkoutline",
+ ),
+ ),
+ (
+ "stock",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="reservations",
+ to="warehouse.stock",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("pk",),
+ },
+ ),
+ migrations.AddIndex(
+ model_name="reservation",
+ index=models.Index(
+ fields=["checkout_line", "reserved_until"],
+ name="warehouse_r_checkou_b66369_idx",
+ ),
+ ),
+ migrations.AlterUniqueTogether(
+ name="reservation",
+ unique_together={("checkout_line", "stock")},
+ ),
+ ]
diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.py
index d7dfb01b03..86a1f4dd99 100644
--- a/saleor/warehouse/models.py
+++ b/saleor/warehouse/models.py
@@ -1,12 +1,13 @@
import itertools
import uuid
-from typing import Set
+from typing import Iterable, Optional, Set
from django.db import models
from django.db.models import Count, Exists, F, OuterRef, Prefetch, Q, Sum
from django.db.models.expressions import Subquery
from django.db.models.functions import Coalesce
from django.db.models.query import QuerySet
+from django.utils import timezone
from ..account.models import Address
from ..channel.models import Channel
@@ -144,6 +145,17 @@ class StockQuerySet(models.QuerySet):
)
)
+ def annotate_reserved_quantity(self):
+ return self.annotate(
+ reserved_quantity=Coalesce(
+ Sum(
+ "reservations__quantity_reserved",
+ filter=Q(reservations__reserved_until__gt=timezone.now()),
+ ),
+ 0,
+ )
+ )
+
def for_channel(self, channel_slug: str):
ShippingZoneChannel = Channel.shipping_zones.through # type: ignore
WarehouseShippingZone = ShippingZone.warehouses.through # type: ignore
@@ -186,6 +198,20 @@ class StockQuerySet(models.QuerySet):
product_variant=product_variant
)
+ def get_variants_stocks_for_country(
+ self,
+ country_code: str,
+ channel_slug: str,
+ products_variants: Iterable[ProductVariant],
+ ):
+ """Return the stock information about the a stock for a given country.
+
+ Note it will raise a 'Stock.DoesNotExist' exception if no such stock is found.
+ """
+ return self.for_country_and_channel(country_code, channel_slug).filter(
+ product_variant__in=products_variants
+ )
+
def get_product_stocks_for_country_and_channel(
self, country_code: str, channel_slug: str, product: Product
):
@@ -280,3 +306,42 @@ class PreorderAllocation(models.Model):
class Meta:
unique_together = [["order_line", "product_variant_channel_listing"]]
ordering = ("pk",)
+
+
+class ReservationQuerySet(models.QuerySet):
+ def not_expired(self):
+ return self.filter(reserved_until__gt=timezone.now())
+
+ def exclude_checkout_lines(self, checkout_lines: Optional[Iterable[CheckoutLine]]):
+ if checkout_lines:
+ return self.exclude(checkout_line__in=checkout_lines)
+
+ return self
+
+
+class Reservation(models.Model):
+ checkout_line = models.ForeignKey(
+ CheckoutLine,
+ null=False,
+ blank=False,
+ on_delete=models.CASCADE,
+ related_name="reservations",
+ )
+ stock = models.ForeignKey(
+ Stock,
+ null=False,
+ blank=False,
+ on_delete=models.CASCADE,
+ related_name="reservations",
+ )
+ quantity_reserved = models.PositiveIntegerField(default=0)
+ reserved_until = models.DateTimeField()
+
+ objects = models.Manager.from_queryset(ReservationQuerySet)()
+
+ class Meta:
+ unique_together = [["checkout_line", "stock"]]
+ indexes = [
+ models.Index(fields=["checkout_line", "reserved_until"]),
+ ]
+ ordering = ("pk",)
diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.py
new file mode 100644
index 0000000000..3b0285ad4b
--- /dev/null
+++ b/saleor/warehouse/reservations.py
@@ -0,0 +1,191 @@
+from collections import defaultdict, namedtuple
+from datetime import datetime, timedelta
+from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple
+
+from django.db.models import Sum
+from django.utils import timezone
+
+from ..core.exceptions import InsufficientStock, InsufficientStockData
+from ..core.tracing import traced_atomic_transaction
+from ..product.models import ProductVariant
+from .models import Allocation, Reservation, Stock
+
+if TYPE_CHECKING:
+ from ..checkout.fetch import CheckoutLine
+
+StockData = namedtuple("StockData", ["pk", "quantity"])
+
+
+@traced_atomic_transaction()
+def reserve_stocks(
+ checkout_lines: Iterable["CheckoutLine"],
+ variants: Iterable["ProductVariant"],
+ country_code: str,
+ channel_slug: str,
+ length_in_minutes: int,
+ *,
+ replace=True,
+):
+ """Reserve stocks 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}
+
+ # Reservation is only applied to checkout lines with variants with track inventory
+ # set to True
+ checkout_lines = get_checkout_lines_to_reserve(checkout_lines, variants_map)
+ if not checkout_lines:
+ return
+
+ reserved_until = timezone.now() + timedelta(minutes=length_in_minutes)
+
+ stocks = list(
+ Stock.objects.select_for_update(of=("self",))
+ .get_variants_stocks_for_country(country_code, channel_slug, variants)
+ .order_by("pk")
+ .values("id", "product_variant", "pk", "quantity")
+ )
+ stocks_id = [stock.pop("id") for stock in stocks]
+
+ quantity_allocation_list = list(
+ Allocation.objects.filter(
+ stock_id__in=stocks_id,
+ quantity_allocated__gt=0,
+ )
+ .values("stock")
+ .annotate(quantity_allocated_sum=Sum("quantity_allocated"))
+ )
+ quantity_allocation_for_stocks: Dict = defaultdict(int)
+ for allocation in quantity_allocation_list:
+ quantity_allocation_for_stocks[allocation["stock"]] += allocation[
+ "quantity_allocated_sum"
+ ]
+
+ quantity_reservation_list = list(
+ Reservation.objects.filter(
+ stock_id__in=stocks_id,
+ quantity_reserved__gt=0,
+ )
+ .not_expired()
+ .exclude_checkout_lines(checkout_lines)
+ .values("stock")
+ .annotate(quantity_reserved_sum=Sum("quantity_reserved"))
+ ) # type: ignore
+ quantity_reservation_for_stocks: Dict = defaultdict(int)
+ for reservation in quantity_reservation_list:
+ quantity_reservation_for_stocks[reservation["stock"]] += reservation[
+ "quantity_reserved_sum"
+ ]
+
+ variant_to_stocks: Dict[int, List[StockData]] = defaultdict(list)
+ for stock_data in stocks:
+ variant = stock_data.pop("product_variant")
+ variant_to_stocks[variant].append(StockData(**stock_data))
+
+ insufficient_stocks: List[InsufficientStockData] = []
+ reservations: List[Reservation] = []
+ for line in checkout_lines:
+ stock_reservations = variant_to_stocks[line.variant_id]
+ insufficient_stocks, reserved_items = _create_reservations(
+ line,
+ variants_map[line.variant_id],
+ stock_reservations,
+ quantity_allocation_for_stocks,
+ quantity_reservation_for_stocks,
+ insufficient_stocks,
+ reserved_until,
+ )
+ reservations.extend(reserved_items)
+
+ if insufficient_stocks:
+ raise InsufficientStock(insufficient_stocks)
+
+ if reservations:
+ if replace:
+ Reservation.objects.filter(checkout_line__in=checkout_lines).delete()
+ Reservation.objects.bulk_create(reservations)
+
+
+def _create_reservations(
+ line: "CheckoutLine",
+ variant: "ProductVariant",
+ stocks: List[StockData],
+ quantity_allocation_for_stocks: dict,
+ quantity_reservation_for_stocks: dict,
+ insufficient_stocks: List[InsufficientStockData],
+ reserved_until: datetime,
+) -> Tuple[List[InsufficientStockData], List[Reservation]]:
+ quantity = line.quantity
+ quantity_reserved = 0
+ reservations = []
+ for stock_data in stocks:
+ quantity_allocated_in_stock = quantity_allocation_for_stocks.get(
+ stock_data.pk, 0
+ )
+ quantity_reserved_in_stock = quantity_reservation_for_stocks.get(
+ stock_data.pk, 0
+ )
+
+ quantity_available_in_stock = max(
+ stock_data.quantity
+ - quantity_allocated_in_stock
+ - quantity_reserved_in_stock,
+ 0,
+ )
+
+ quantity_to_reserve = min(
+ (quantity - quantity_reserved), quantity_available_in_stock
+ )
+ if quantity_to_reserve > 0:
+ reservations.append(
+ Reservation(
+ checkout_line=line,
+ stock_id=stock_data.pk,
+ quantity_reserved=quantity_to_reserve,
+ reserved_until=reserved_until,
+ )
+ )
+
+ quantity_reserved += quantity_to_reserve
+ if quantity_reserved == quantity:
+ return insufficient_stocks, reservations
+
+ if quantity_reserved != quantity:
+ insufficient_stocks.append(
+ InsufficientStockData(
+ variant=variant,
+ available_quantity=quantity,
+ ) # type: ignore
+ )
+ return insufficient_stocks, []
+
+ return [], []
+
+
+def get_checkout_lines_to_reserve(
+ lines: Iterable["CheckoutLine"],
+ variants_map: Dict[int, "ProductVariant"],
+) -> Iterable["CheckoutLine"]:
+ """Return checkout lines which can be reserved."""
+ valid_lines = []
+ for line in lines:
+ if (
+ line.quantity
+ and line.variant_id
+ and variants_map[line.variant_id].track_inventory
+ ):
+ valid_lines.append(line)
+ return valid_lines
+
+
+def is_reservation_enabled(settings) -> bool:
+ return bool(
+ settings.reserve_stock_duration_authenticated_user
+ or settings.reserve_stock_duration_anonymous_user
+ )
+
+
+def get_reservation_length(request) -> Optional[int]:
+ if request.user.is_authenticated:
+ return request.site.settings.reserve_stock_duration_authenticated_user
+ return request.site.settings.reserve_stock_duration_anonymous_user
diff --git a/saleor/warehouse/tasks.py b/saleor/warehouse/tasks.py
index 455a5ee6c7..76e4de0047 100644
--- a/saleor/warehouse/tasks.py
+++ b/saleor/warehouse/tasks.py
@@ -1,7 +1,8 @@
from celery.utils.log import get_task_logger
+from django.utils import timezone
from ..celeryconf import app
-from .models import Allocation
+from .models import Allocation, Reservation
task_logger = get_task_logger(__name__)
@@ -11,3 +12,10 @@ def delete_empty_allocations_task():
count, _ = Allocation.objects.filter(quantity_allocated=0).delete()
if count:
task_logger.debug("Removed %s allocations", count)
+
+
+def delete_expired_reservations_task():
+ count, _ = Reservation.objects.filter(reserved_until__lt=timezone.now()).delete()
+ if count:
+ task_logger.debug("Removed %s reservations", count)
diff --git a/saleor/warehouse/tests/test_reservations_management.py b/saleor/warehouse/tests/test_reservations_management.py
new file mode 100644
index 0000000000..2fc8d21f64
--- /dev/null
+++ b/saleor/warehouse/tests/test_reservations_management.py
@@ -0,0 +1,226 @@
+from datetime import timedelta
+
+import pytest
+from django.utils import timezone
+
+from ...checkout.models import Checkout
+from ...core.exceptions import InsufficientStock
+from ..models import Reservation, Stock, Warehouse
+from ..reservations import reserve_stocks
+
+COUNTRY_CODE = "US"
+RESERVATION_LENGTH = 5
+
+
+def test_reserve_stocks(checkout_line, channel_USD):
+ checkout_line.quantity = 5
+ checkout_line.save()
+
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ stock.quantity = 10
+ stock.save(update_fields=["quantity"])
+
+ reserve_stocks(
+ [checkout_line],
+ [checkout_line.variant],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ RESERVATION_LENGTH,
+ )
+
+ stock.refresh_from_db()
+ assert stock.quantity == 10
+ reservation = Reservation.objects.get(checkout_line=checkout_line, stock=stock)
+ assert reservation.quantity_reserved == 5
+ assert reservation.reserved_until > timezone.now() + timedelta(minutes=1)
+
+
+def test_stocks_reservation_skips_prev_stocks_delete_if_replace_is_disabled(
+ checkout_line, assert_num_queries, channel_USD
+):
+ with assert_num_queries(3):
+ reserve_stocks(
+ [checkout_line],
+ [checkout_line.variant],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ RESERVATION_LENGTH,
+ replace=False,
+ )
+
+ with assert_num_queries(4):
+ reserve_stocks(
+ [checkout_line],
+ [checkout_line.variant],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ RESERVATION_LENGTH,
+ )
+
+
+def test_multiple_stocks_are_reserved_if_single_stock_is_not_enough(
+ checkout_line, warehouse, shipping_zone, channel_USD
+):
+ checkout_line.quantity = 5
+ checkout_line.save()
+
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ stock.quantity = 3
+ stock.save(update_fields=["quantity"])
+
+ secondary_warehouse = Warehouse.objects.create(
+ address=warehouse.address,
+ name="Warehouse 2",
+ slug="warehouse-2",
+ email=warehouse.email,
+ )
+ secondary_warehouse.shipping_zones.add(shipping_zone)
+ secondary_warehouse.save()
+
+ secondary_stock = Stock.objects.create(
+ warehouse=secondary_warehouse, product_variant=stock.product_variant, quantity=3
+ )
+
+ reserve_stocks(
+ [checkout_line],
+ [checkout_line.variant],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ RESERVATION_LENGTH,
+ )
+
+ stock.refresh_from_db()
+ assert stock.quantity == 3
+
+ reservation = Reservation.objects.get(checkout_line=checkout_line, stock=stock)
+ assert reservation.quantity_reserved == 3
+ assert reservation.reserved_until > timezone.now() + timedelta(minutes=1)
+
+ second_reservation = Reservation.objects.get(
+ checkout_line=checkout_line, stock=secondary_stock
+ )
+ assert second_reservation.quantity_reserved == 2
+ assert second_reservation.reserved_until > timezone.now() + timedelta(minutes=1)
+
+
+def test_stocks_reservation_removes_previous_reservations_for_checkout(
+ checkout_line, channel_USD
+):
+ checkout_line.quantity = 5
+ checkout_line.save()
+
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ stock.quantity = 10
+ stock.save(update_fields=["quantity"])
+
+ previous_reservation = Reservation.objects.create(
+ checkout_line=checkout_line,
+ stock=stock,
+ quantity_reserved=5,
+ reserved_until=timezone.now() + timedelta(hours=1),
+ )
+
+ reserve_stocks(
+ [checkout_line],
+ [checkout_line.variant],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ RESERVATION_LENGTH,
+ )
+
+ with pytest.raises(Reservation.DoesNotExist):
+ previous_reservation.refresh_from_db()
+
+
+def test_stock_reservation_fails_if_there_is_not_enough_stock_available(
+ checkout_line, channel_USD
+):
+ checkout_line.quantity = 5
+ checkout_line.save()
+
+ stock = Stock.objects.get(product_variant=checkout_line.variant)
+ stock.quantity = 3
+ stock.save(update_fields=["quantity"])
+
+ with pytest.raises(InsufficientStock):
+ reserve_stocks(
+ [checkout_line],
+ [checkout_line.variant],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ RESERVATION_LENGTH,
+ )
+
+
+def test_stock_reservation_fails_if_there_is_no_stock(checkout_line, channel_USD):
+ checkout_line.quantity = 5
+ checkout_line.save()
+
+ Stock.objects.all().delete()
+
+ with pytest.raises(InsufficientStock):
+ reserve_stocks(
+ [checkout_line],
+ [checkout_line.variant],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ RESERVATION_LENGTH,
+ )
+
+
+def test_stock_reservation_accounts_for_order_allocations(
+ order_line_with_allocation_in_many_stocks, checkout, channel_USD
+):
+ variant = order_line_with_allocation_in_many_stocks.variant
+ variant.stocks.update(quantity=3) # 2 x 3 = 6
+
+ checkout_line = checkout.lines.create(
+ quantity=4,
+ variant=variant,
+ )
+
+ with pytest.raises(InsufficientStock):
+ reserve_stocks(
+ [checkout_line],
+ [variant],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ RESERVATION_LENGTH,
+ )
+
+
+def test_stock_reservation_accounts_for_order_allocations_and_reservations(
+ order_line_with_allocation_in_many_stocks, checkout, channel_USD
+):
+ variant = order_line_with_allocation_in_many_stocks.variant
+ variant.stocks.update(quantity=3) # 2 x 3 = 6
+
+ other_checkout = Checkout.objects.create(
+ currency=channel_USD.currency_code, channel=channel_USD
+ )
+ other_checkout.set_country("US", commit=True)
+ other_checkout_line = checkout.lines.create(
+ quantity=2,
+ variant=variant,
+ )
+
+ Reservation.objects.create(
+ checkout_line=other_checkout_line,
+ stock=variant.stocks.order_by("pk").last(),
+ quantity_reserved=2,
+ reserved_until=timezone.now() + timedelta(hours=1),
+ )
+
+ checkout_line = checkout.lines.create(
+ quantity=2,
+ variant=variant,
+ )
+
+ with pytest.raises(InsufficientStock):
+ reserve_stocks(
+ [checkout_line],
+ [variant],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ RESERVATION_LENGTH,
+ )
diff --git a/saleor/warehouse/tests/test_stock_availability.py b/saleor/warehouse/tests/test_stock_availability.py
index 4e973a48b7..a4471d1643 100644
--- a/saleor/warehouse/tests/test_stock_availability.py
+++ b/saleor/warehouse/tests/test_stock_availability.py
@@ -1,11 +1,14 @@
import pytest
+from ...checkout.fetch import fetch_checkout_lines
from ...core.exceptions import InsufficientStock
from ..availability import (
_get_available_quantity,
check_stock_quantity,
check_stock_quantity_bulk,
+ get_available_quantity,
)
+from ..models import Allocation
COUNTRY_CODE = "US"
@@ -49,6 +52,46 @@ def test_check_stock_quantity_with_allocations_out_of_stock(
)
+def test_check_stock_quantity_with_reservations(
+ variant_with_many_stocks,
+ checkout_line_with_reservation_in_many_stocks,
+ checkout_line_with_one_reservation,
+ channel_USD,
+):
+ assert (
+ check_stock_quantity(
+ variant_with_many_stocks,
+ COUNTRY_CODE,
+ channel_USD.slug,
+ 2,
+ check_reservations=True,
+ )
+ is None
+ )
+
+
+def test_check_stock_quantity_with_reservations_excluding_given_checkout_lines(
+ variant_with_many_stocks,
+ checkout_line_with_reservation_in_many_stocks,
+ checkout_line_with_one_reservation,
+ channel_USD,
+):
+ assert (
+ check_stock_quantity(
+ variant_with_many_stocks,
+ COUNTRY_CODE,
+ channel_USD.slug,
+ 7,
+ [
+ checkout_line_with_reservation_in_many_stocks,
+ checkout_line_with_one_reservation,
+ ],
+ check_reservations=True,
+ )
+ is None
+ )
+
+
def test_check_stock_quantity_without_stocks(variant_with_many_stocks, channel_USD):
variant_with_many_stocks.stocks.all().delete()
with pytest.raises(InsufficientStock):
@@ -67,6 +110,90 @@ def test_check_stock_quantity_without_one_stock(variant_with_many_stocks, channe
)
+def test_get_available_quantity(variant_with_many_stocks, channel_USD):
+ available_quantity = get_available_quantity(
+ variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug
+ )
+ assert available_quantity == 7
+
+
+def test_get_available_quantity_without_allocation(order_line, stock, channel_USD):
+ assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()
+ available_quantity = get_available_quantity(
+ order_line.variant, COUNTRY_CODE, channel_USD.slug
+ )
+ assert available_quantity == stock.quantity
+
+
+def test_get_available_quantity_with_allocations(
+ variant_with_many_stocks,
+ order_line_with_allocation_in_many_stocks,
+ order_line_with_one_allocation,
+ channel_USD,
+):
+ available_quantity = get_available_quantity(
+ variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug
+ )
+ assert available_quantity == 3
+
+
+def test_get_available_quantity_with_reservations(
+ variant_with_many_stocks,
+ checkout_line_with_reservation_in_many_stocks,
+ checkout_line_with_one_reservation,
+ channel_USD,
+):
+ available_quantity = get_available_quantity(
+ variant_with_many_stocks,
+ COUNTRY_CODE,
+ channel_USD.slug,
+ check_reservations=True,
+ )
+ assert available_quantity == 2
+
+
+def test_get_available_quantity_with_allocations_and_reservations(
+ variant_with_many_stocks,
+ order_line_with_one_allocation,
+ checkout_line_with_one_reservation,
+ channel_USD,
+):
+ available_quantity = get_available_quantity(
+ variant_with_many_stocks,
+ COUNTRY_CODE,
+ channel_USD.slug,
+ check_reservations=True,
+ )
+ assert available_quantity == 4
+
+
+def test_get_available_quantity_with_reservations_excluding_given_checkout_lines(
+ variant_with_many_stocks,
+ checkout_line_with_reservation_in_many_stocks,
+ checkout_line_with_one_reservation,
+ channel_USD,
+):
+ available_quantity = get_available_quantity(
+ variant_with_many_stocks,
+ COUNTRY_CODE,
+ channel_USD.slug,
+ [
+ checkout_line_with_reservation_in_many_stocks,
+ checkout_line_with_one_reservation,
+ ],
+ check_reservations=True,
+ )
+ assert available_quantity == 7
+
+
+def test_get_available_quantity_without_stocks(variant_with_many_stocks, channel_USD):
+ variant_with_many_stocks.stocks.all().delete()
+ available_quantity = get_available_quantity(
+ variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug
+ )
+ assert available_quantity == 0
+
+
def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):
variant = variant_with_many_stocks
country_code = "US"
@@ -75,7 +202,10 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):
# test that it doesn't raise error for available quantity
assert (
check_stock_quantity_bulk(
- [variant_with_many_stocks], country_code, [available_quantity], channel_USD
+ [variant_with_many_stocks],
+ country_code,
+ [available_quantity],
+ channel_USD.slug,
)
is None
)
@@ -93,7 +223,10 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):
variant.stocks.all().delete()
with pytest.raises(InsufficientStock):
check_stock_quantity_bulk(
- [variant_with_many_stocks], country_code, [available_quantity], channel_USD
+ [variant_with_many_stocks],
+ country_code,
+ [available_quantity],
+ channel_USD.slug,
)
@@ -107,5 +240,60 @@ def test_check_stock_quantity_bulk_no_channel_shipping_zones(
with pytest.raises(InsufficientStock):
check_stock_quantity_bulk(
- [variant_with_many_stocks], country_code, [available_quantity], channel_USD
+ [variant_with_many_stocks],
+ country_code,
+ [available_quantity],
+ channel_USD.slug,
+ )
+
+
+def test_check_stock_quantity_bulk_with_reservations(
+ variant_with_many_stocks,
+ checkout_line_with_reservation_in_many_stocks,
+ checkout_line_with_one_reservation,
+ channel_USD,
+):
+ variant = variant_with_many_stocks
+ country_code = "US"
+ available_quantity = get_available_quantity(
+ variant,
+ country_code,
+ channel_USD.slug,
+ check_reservations=True,
+ )
+
+ # test that it doesn't raise error for available quantity
+ assert (
+ check_stock_quantity_bulk(
+ [variant_with_many_stocks],
+ country_code,
+ [available_quantity],
+ channel_USD.slug,
+ check_reservations=True,
+ )
+ is None
+ )
+
+ # test that it raises an error for exceeded quantity
+ with pytest.raises(InsufficientStock):
+ check_stock_quantity_bulk(
+ [variant_with_many_stocks],
+ country_code,
+ [available_quantity + 1],
+ channel_USD.slug,
+ check_reservations=True,
+ )
+
+ # test that it passes if checkout lines are excluded
+ checkout_lines = fetch_checkout_lines(checkout_line_with_one_reservation.checkout)
+ assert (
+ check_stock_quantity_bulk(
+ [variant_with_many_stocks],
+ country_code,
+ [available_quantity + 1],
+ channel_USD.slug,
+ existing_lines=checkout_lines,
+ check_reservations=True,
)
+ is None
+ )
diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.py
index 5fc67f1788..e76aed269a 100644
--- a/saleor/warehouse/tests/test_stock_management.py
+++ b/saleor/warehouse/tests/test_stock_management.py
@@ -96,6 +96,52 @@ def test_allocate_stock_many_stocks(order_line, variant_with_many_stocks, channe
assert allocations[1].quantity_allocated == 1
+def test_allocate_stock_with_reservations(
+ order_line,
+ variant_with_many_stocks,
+ channel_USD,
+ checkout_line_with_one_reservation,
+):
+ variant = variant_with_many_stocks
+ stocks = variant.stocks.all()
+
+ line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=3)
+ allocate_stocks(
+ [line_data],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ manager=get_plugins_manager(),
+ check_reservations=True,
+ )
+
+ allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)
+ assert allocations[0].quantity_allocated == 2
+ assert allocations[1].quantity_allocated == 1
+
+
+def test_allocate_stock_insufficient_stock_due_to_reservations(
+ order_line,
+ variant_with_many_stocks,
+ channel_USD,
+ checkout_line_with_reservation_in_many_stocks,
+):
+ variant = variant_with_many_stocks
+ variant.stocks.all()
+
+ line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=5)
+
+ with pytest.raises(InsufficientStock):
+ allocate_stocks(
+ [line_data],
+ COUNTRY_CODE,
+ channel_USD.slug,
+ manager=get_plugins_manager(),
+ check_reservations=True,
+ )
+
+ assert not Allocation.objects.exists()
+
+
def test_allocate_stock_many_stocks_partially_allocated(
order_line,
order_line_with_allocation_in_many_stocks,
diff --git a/saleor/warehouse/tests/test_tasks.py b/saleor/warehouse/tests/test_tasks.py
new file mode 100644
index 0000000000..3d1cc8dc38
--- /dev/null
+++ b/saleor/warehouse/tests/test_tasks.py
@@ -0,0 +1,23 @@
+from datetime import timedelta
+
+from django.utils import timezone
+
+from ..models import Reservation
+from ..tasks import delete_expired_reservations_task
+
+
+def test_delete_expired_reservations_task_deletes_expired_reservations(
+ checkout_line_with_reservation_in_many_stocks,
+):
+ Reservation.objects.update(reserved_until=timezone.now() - timedelta(seconds=1))
+ delete_expired_reservations_task()
+ assert not Reservation.objects.exists()
+
+
+def test_delete_expired_reservations_task_skips_active_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