Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Feature: preorders (#7817)
Aleksander Spyra9f2e41846f30
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 06d5046270..b64f589601 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -36,8 +36,8 @@ from ..payment import PaymentError, gatewayfrom ..payment.models import Payment, Transactionfrom ..payment.utils import fetch_customer_id, store_customer_idfrom ..product.models import ProductTranslation, ProductVariantTranslation-from ..warehouse.availability import check_stock_quantity_bulk-from ..warehouse.management import allocate_stocks+from ..warehouse.availability import check_stock_and_preorder_quantity_bulk+from ..warehouse.management import allocate_preorders, allocate_stocksfrom . import AddressTypefrom .checkout_cleaner import clean_checkout_payment, clean_checkout_shippingfrom .models import Checkout@@ -256,7 +256,7 @@ def _create_lines_for_order(additional_warehouse_lookup = (checkout_info.delivery_method_info.get_warehouse_filter_lookup())- check_stock_quantity_bulk(+ check_stock_and_preorder_quantity_bulk(variants,country_code,quantities,@@ -428,6 +428,7 @@ def _create_order(manager,additional_warehouse_lookup,)+ allocate_preorders(order_lines_info, checkout_info.channel.slug)add_gift_cards_to_order(checkout_info, order, total_price_left, user, app)diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex f91a250680..5d3ae09579 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -1009,7 +1009,7 @@ def test_create_order_with_variant_tracking_false(@override_settings(LANGUAGE_CODE="fr")-def test_create_order_use_tanslations(+def test_create_order_use_translations(checkout_with_item, customer_user, shipping_method):translated_product_name = "French name"diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex f7a1c849fa..ff603c6c08 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -27,7 +27,10 @@ from ..giftcard.utils import (from ..plugins.manager import PluginsManagerfrom ..product import models as product_modelsfrom ..shipping.models import ShippingMethod-from ..warehouse.availability import check_stock_quantity, check_stock_quantity_bulk+from ..warehouse.availability import (+ check_stock_and_preorder_quantity,+ check_stock_and_preorder_quantity_bulk,+)from ..warehouse.models import Warehousefrom . import AddressType, calculationsfrom .error_codes import CheckoutErrorCode@@ -71,7 +74,7 @@ def check_variant_in_stock()if new_quantity > 0 and check_quantity:- check_stock_quantity(+ check_stock_and_preorder_quantity(variant, checkout.get_country(), channel_slug, new_quantity)@@ -138,7 +141,9 @@ def add_variants_to_checkout(# check quantitiescountry_code = checkout.get_country()if not skip_stock_check:- check_stock_quantity_bulk(variants, country_code, quantities, channel_slug)+ check_stock_and_preorder_quantity_bulk(+ variants, country_code, quantities, channel_slug+ )channel_listings = product_models.ProductChannelListing.objects.filter(channel_id=checkout.channel.id,diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.pyindex 849da7f9cf..d64db527ad 100644--- a/saleor/core/exceptions.py+++ b/saleor/core/exceptions.py@@ -31,6 +31,12 @@ class AllocationError(Exception):self.order_lines = order_lines+class PreorderAllocationError(Exception):+ def __init__(self, order_line):+ super().__init__(f"Unable to allocate in stock for line {str(order_line)}.")+ self.order_line = order_line++class ReadOnlyException(Exception):def __init__(self, msg=None):if msg is None:diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.pyindex ad1946aab7..e1732a31c4 100644--- a/saleor/core/management/commands/populatedb.py+++ b/saleor/core/management/commands/populatedb.py@@ -16,6 +16,7 @@ from ...utils.random_data import (create_page_type,create_pages,create_permission_groups,+ create_preorder_orders,create_product_sales,create_products_by_schema,create_shipping_zones,@@ -106,6 +107,8 @@ class Command(BaseCommand):self.stdout.write(msg)for msg in create_orders(20):self.stdout.write(msg)+ for msg in create_preorder_orders(1):+ self.stdout.write(msg)for msg in create_menus():self.stdout.write(msg)diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.pyindex b690977348..af7dde0274 100644--- a/saleor/core/tests/test_core.py+++ b/saleor/core/tests/test_core.py@@ -16,7 +16,7 @@ from ...account.utils import create_superuserfrom ...channel.models import Channelfrom ...discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListingfrom ...giftcard.models import GiftCard-from ...order.models import Order+from ...order.models import Order, OrderLinefrom ...product import ProductTypeKindfrom ...product.models import ProductMedia, ProductTypefrom ...shipping.models import ShippingZone@@ -151,11 +151,17 @@ def test_create_fake_order(db, monkeypatch, image, media_root, warehouse):for msg in random_data.create_pages():passrandom_data.create_products_by_schema("/", False)- how_many = 2- for _ in random_data.create_orders(how_many):+ how_many_orders = 2+ for _ in random_data.create_orders(how_many_orders):passassert Order.objects.all().count() == 2+ how_many_preorder_orders = 1+ for _ in random_data.create_preorder_orders(how_many_preorder_orders):+ pass+ assert Order.objects.count() == how_many_orders + how_many_preorder_orders+ assert OrderLine.objects.filter(variant__is_preorder=True).exists()+def test_create_product_sales(db):how_many = 5diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 648529093a..a67c444f10 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -84,7 +84,7 @@ from ...shipping.models import ()from ...warehouse import WarehouseClickAndCollectOptionfrom ...warehouse.management import increase_stock-from ...warehouse.models import Stock, Warehouse+from ...warehouse.models import PreorderAllocation, Stock, Warehousefake = Factory.create()fake.seed(0)@@ -573,7 +573,7 @@ def create_order_lines(order, discounts, how_many=10):"variant_id", flat=True)variants = (- ProductVariant.objects.filter(pk__in=available_variant_ids)+ ProductVariant.objects.filter(pk__in=available_variant_ids, is_preorder=False).order_by("?").prefetch_related("product__product_type")[:how_many])@@ -581,36 +581,8 @@ def create_order_lines(order, discounts, how_many=10):lines = []for _ in range(how_many):variant = next(variants_iter)- variant_channel_listing = variant.channel_listings.get(channel=channel)- product = variant.product- quantity = random.randrange(1, 5)- unit_price = variant.get_price(- product,- product.collections.all(),- channel,- variant_channel_listing,- discounts,- )- unit_price = TaxedMoney(net=unit_price, gross=unit_price)- total_price = unit_price * quantity- lines.append(- OrderLine(- order=order,- product_name=str(product),- variant_name=str(variant),- product_sku=variant.sku,- product_variant_id=variant.get_global_id(),- is_shipping_required=variant.is_shipping_required(),- is_gift_card=variant.is_gift_card(),- quantity=quantity,- variant=variant,- unit_price=unit_price,- total_price=total_price,- undiscounted_unit_price=unit_price,- undiscounted_total_price=total_price,- tax_rate=0,- )- )+ lines.append(_get_new_order_line(order, variant, channel, discounts))+lines = OrderLine.objects.bulk_create(lines)manager = get_plugins_manager()country = order.shipping_method.shipping_zone.countries[0]@@ -649,6 +621,101 @@ def create_order_lines(order, discounts, how_many=10):return lines+def create_order_lines_with_preorder(order, discounts, how_many=1):+ channel = order.channel+ available_variant_ids = channel.variant_listings.values_list(+ "variant_id", flat=True+ )+ variants = (+ ProductVariant.objects.filter(pk__in=available_variant_ids, is_preorder=True)+ .order_by("?")+ .prefetch_related("product__product_type")[:how_many]+ )+ variants_iter = itertools.cycle(variants)+ lines = []+ for _ in range(how_many):+ variant = next(variants_iter)+ lines.append(_get_new_order_line(order, variant, channel, discounts))++ lines = OrderLine.objects.bulk_create(lines)+ manager = get_plugins_manager()++ preorder_allocations = []+ for line in lines:+ variant = line.variant+ unit_price = manager.calculate_order_line_unit(+ order, line, variant, variant.product+ )+ total_price = manager.calculate_order_line_total(+ order, line, variant, variant.product+ )+ line.unit_price = unit_price+ line.total_price = total_price+ line.undiscounted_unit_price = unit_price+ line.undiscounted_total_price = total_price+ line.tax_rate = unit_price.tax / unit_price.net+ variant_channel_listing = variant.channel_listings.get(channel=channel)+ preorder_allocations.append(+ PreorderAllocation(+ order_line=line,+ product_variant_channel_listing=variant_channel_listing,+ quantity=line.quantity,+ )+ )+ PreorderAllocation.objects.bulk_create(preorder_allocations)++ OrderLine.objects.bulk_update(+ lines,+ [+ "unit_price_net_amount",+ "unit_price_gross_amount",+ "undiscounted_unit_price_gross_amount",+ "undiscounted_unit_price_net_amount",+ "undiscounted_total_price_gross_amount",+ "undiscounted_total_price_net_amount",+ "currency",+ "tax_rate",+ ],+ )+ return lines+++def _get_new_order_line(order, variant, channel, discounts):+ variant_channel_listing = variant.channel_listings.get(channel=channel)+ product = variant.product+ quantity = random.randrange(+ 1,+ variant_channel_listing.preorder_quantity_threshold+ or variant.preorder_global_threshold+ or 5,+ )+ unit_price = variant.get_price(+ product,+ product.collections.all(),+ channel,+ variant_channel_listing,+ discounts,+ )+ unit_price = TaxedMoney(net=unit_price, gross=unit_price)+ total_price = unit_price * quantity+ return OrderLine(+ order=order,+ product_name=str(product),+ variant_name=str(variant),+ product_sku=variant.sku,+ product_variant_id=variant.get_global_id(),+ is_shipping_required=variant.is_shipping_required(),+ is_gift_card=variant.is_gift_card(),+ quantity=quantity,+ variant=variant,+ unit_price=unit_price,+ total_price=total_price,+ undiscounted_unit_price=unit_price,+ undiscounted_total_price=total_price,+ tax_rate=0,+ )++def create_fulfillments(order):for line in order.lines.all():if random.choice([False, True]):@@ -667,7 +734,7 @@ def create_fulfillments(order):update_order_status(order)-def create_fake_order(discounts, max_order_lines=5):+def create_fake_order(discounts, max_order_lines=5, create_preorder_lines=False):channel = Channel.objects.all().order_by("?").first()customers = (User.objects.filter(is_superuser=False)@@ -677,7 +744,9 @@ def create_fake_order(discounts, max_order_lines=5):customer = random.choice([None, customers.first()])# 20% chance to be unconfirmed order.- will_be_unconfirmed = random.choice([0, 0, 0, 0, 1])+ will_be_unconfirmed = (+ random.choice([0, 0, 0, 0, 1]) if not create_preorder_lines else True+ )if customer:address = customer.default_shipping_address@@ -695,13 +764,13 @@ def create_fake_order(discounts, max_order_lines=5):}manager = get_plugins_manager()- shipping_method_chanel_listing = (+ shipping_method_channel_listing = (ShippingMethodChannelListing.objects.filter(channel=channel).order_by("?").first())- shipping_method = shipping_method_chanel_listing.shipping_method- shipping_price = shipping_method_chanel_listing.price+ shipping_method = shipping_method_channel_listing.shipping_method+ shipping_price = shipping_method_channel_listing.priceshipping_price = manager.apply_taxes_to_shipping(shipping_price, address, channel_slug=channel.slug)@@ -717,7 +786,12 @@ def create_fake_order(discounts, max_order_lines=5):order_data["status"] = OrderStatus.UNCONFIRMEDorder = Order.objects.create(**order_data)- lines = create_order_lines(order, discounts, random.randrange(1, max_order_lines))+ if create_preorder_lines:+ lines = create_order_lines_with_preorder(order, discounts)+ else:+ lines = create_order_lines(+ order, discounts, random.randrange(1, max_order_lines)+ )order.total = sum([line.total_price for line in lines], shipping_price)weight = Weight(kg=0)for line in order.lines.all():@@ -754,7 +828,7 @@ def create_fake_sale():def create_users(user_password, how_many=10):- for dummy in range(how_many):+ for _ in range(how_many):user = create_fake_user(user_password)yield "User: %s" % (user.email,)@@ -845,8 +919,15 @@ def create_orders(how_many=10):yield "Order: %s" % (order,)+def create_preorder_orders(how_many=1):+ discounts = fetch_discounts(timezone.now())+ for _ in range(how_many):+ order = create_fake_order(discounts, create_preorder_lines=True)+ yield "Order: %s" % (order,)++def create_product_sales(how_many=5):- for dummy in range(how_many):+ for _ in range(how_many):sale = create_fake_sale()update_products_discounted_prices_of_discount_task.delay(sale.pk)yield "Sale: %s" % (sale,)diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.pyindex ae42f9a21f..b9f1d9306c 100644--- a/saleor/csv/tests/export/products_data/test_get_products_data.py+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py@@ -115,6 +115,11 @@ def test_get_products_data(product, product_with_image, collection, image, chann"variant_weight": ("{} g".foramt(int(variant.weight.value)) if variant.weight else ""),+ "variants__is_preorder": variant.is_preorder,+ "variants__preorder_global_threshold": (+ variant.preorder_global_threshold+ ),+ "variants__preorder_end_date": variant.preorder_end_date,}data.update(product_data)diff --git a/saleor/csv/tests/export/products_data/test_prepare_headers.py b/saleor/csv/tests/export/products_data/test_prepare_headers.pyindex 0d18ea39e4..9750ad8f1d 100644--- a/saleor/csv/tests/export/products_data/test_prepare_headers.py+++ b/saleor/csv/tests/export/products_data/test_prepare_headers.py@@ -127,6 +127,7 @@ def test_get_channels_headers(channel_USD, channel_PLN):"price amount","variant currency code","variant cost price",+ "variant preorder quantity threshold",]:expected_headers.append(f"{channel_slug} (channel {field})")assert channel_headers == expected_headers@@ -200,6 +201,7 @@ def test_get_export_fields_and_headers_info("price amount","variant currency code","variant cost price",+ "variant preorder quantity threshold",]:channel_headers.append(f"{slug} (channel {field})")diff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.pyindex 63b94aca7c..dd678e810b 100644--- a/saleor/csv/tests/export/products_data/utils.py+++ b/saleor/csv/tests/export/products_data/utils.py@@ -105,12 +105,21 @@ def add_channel_to_expected_variant_data(data, variant, channel_ids, pk=None):price_header = f"{channel_slug} (channel price amount)"currency_header = f"{channel_slug} (channel variant currency code)"cost_price = f"{channel_slug} (channel variant cost price)"+ preorder_quantity_threshold = (+ f"{channel_slug} (channel variant preorder quantity threshold)"+ )if pk:data[pk][price_header] = channel_listing.price_amountdata[pk][currency_header] = channel_listing.currencydata[pk][cost_price] = channel_listing.cost_price_amount+ data[pk][+ preorder_quantity_threshold+ ] = channel_listing.preorder_quantity_thresholdelse:data[price_header] = channel_listing.price_amountdata[currency_header] = channel_listing.currencydata[cost_price] = channel_listing.cost_price_amount+ data[+ preorder_quantity_threshold+ ] = channel_listing.preorder_quantity_thresholdreturn datadiff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.pyindex 8aa4bd1436..8a84f3cb08 100644--- a/saleor/csv/utils/__init__.py+++ b/saleor/csv/utils/__init__.py@@ -13,6 +13,9 @@ class ProductExportFields:"variant id": "variants__id","variant sku": "variants__sku","variant weight": "variant_weight",+ "variant is preorder": "variants__is_preorder",+ "variant preorder global threshold": "variants__preorder_global_threshold",+ "variant preorder end date": "variants__preorder_end_date",},"product_many_to_many": {"collections": "collections__slug",@@ -73,4 +76,7 @@ class ProductExportFields:"price_amount": "variants__channel_listings__price_amount","variant_currency_code": "variants__channel_listings__currency","variant_cost_price": "variants__channel_listings__cost_price_amount",+ "variant_preorder_quantity_threshold": (+ "variants__channel_listings__preorder_quantity_threshold"+ ),}diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 8fe1d4fb37..6bba22d962 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -40,7 +40,7 @@ from ...product import models as product_modelsfrom ...product.models import ProductChannelListingfrom ...shipping import models as shipping_modelsfrom ...warehouse import models as warehouse_models-from ...warehouse.availability import check_stock_quantity_bulk+from ...warehouse.availability import check_stock_and_preorder_quantity_bulkfrom ..account.i18n import I18nMixinfrom ..account.types import AddressInputfrom ..channel.utils import clean_channel@@ -169,7 +169,7 @@ def check_lines_quantity(})try:- check_stock_quantity_bulk(+ check_stock_and_preorder_quantity_bulk(variants,country,quantities,diff --git a/saleor/graphql/checkout/tests/benchmark/conftest.py b/saleor/graphql/checkout/tests/benchmark/conftest.pyindex b8549835ba..5c66ae78d3 100644--- a/saleor/graphql/checkout/tests/benchmark/conftest.py+++ b/saleor/graphql/checkout/tests/benchmark/conftest.py@@ -194,3 +194,46 @@ def checkout_with_charged_payment_for_cc(checkout_with_billing_address_for_cc):)return checkout+++def checkout_preorder_with_charged_payment(+ checkout_with_billing_address,+ preorder_variant_channel_threshold,+ preorder_variant_global_threshold,+):+ checkout = checkout_with_billing_address+ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ add_variant_to_checkout(checkout_info, preorder_variant_channel_threshold, 1)+ add_variant_to_checkout(checkout_info, preorder_variant_global_threshold, 1)++ lines = fetch_checkout_lines(checkout)+ manager = get_plugins_manager()+ taxed_total = calculations.checkout_total(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ payment = Payment.objects.create(+ gateway="mirumee.payments.dummy",+ is_active=True,+ total=taxed_total.gross.amount,+ currency="USD",+ )++ payment.charge_status = ChargeStatus.FULLY_CHARGED+ payment.captured_amount = payment.total+ payment.checkout = checkout+ payment.save()++ payment.transactions.create(+ amount=payment.total,+ kind=TransactionKind.CAPTURE,+ gateway_response={},+ is_success=True,+ )++ return checkoutdiff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 269e82f4c6..ec84f8f655 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -1010,3 +1010,18 @@ def test_customer_complete_checkout_for_cc(response = get_graphql_content(api_client.post_graphql(query, variables))assert not response["data"]["checkoutComplete"]["errors"]++[email protected]_queries(autouse=False)+def test_complete_checkout_preorder(+ api_client, checkout_preorder_with_charged_payment, count_queries+):+ query = COMPLETE_CHECKOUT_MUTATION++ variables = {+ "token": checkout_preorder_with_charged_payment.token,+ }++ response = get_graphql_content(api_client.post_graphql(query, variables))+ assert not response["data"]["checkoutComplete"]["errors"]diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex f6f4ad2aee..e2beb96e13 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -1624,6 +1624,7 @@ def test_checkout_complete_raises_InsufficientStock_when_quantity_above_stock_sutotal = calculations.checkout_total(manager=manager, checkout_info=checkout_info, lines=lines, address=address)+payment = payment_dummypayment.is_active = Truepayment.order = None@@ -1690,3 +1691,79 @@ def test_checkout_complete_raises_InvalidShippingMethod_when_warehouse_disabled(content["errors"][0]["code"] == CheckoutErrorCode.INVALID_SHIPPING_METHOD.name)assert Order.objects.count() == initial_order_count+++@patch("saleor.plugins.manager.PluginsManager.order_confirmed")+def test_checkout_complete_with_preorder_variant(+ order_confirmed_mock,+ site_settings,+ user_api_client,+ checkout_with_item_and_preorder_item,+ payment_dummy,+ address,+ shipping_method,+):+ checkout = checkout_with_item_and_preorder_item+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ variants_and_quantities = {line.variant_id: line.quantity for line in checkout}++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ site_settings.automatically_confirm_all_new_orders = True+ site_settings.save()+ 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()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ variables = {"token": checkout.token, "redirectUrl": "https://www.example.com"}+ 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.status == OrderStatus.UNFULFILLED+ assert order.origin == OrderOrigin.CHECKOUT+ assert not order.original+ assert order.token == order_token+ assert order.total.gross == total.gross++ assert order.lines.count() == len(variants_and_quantities)+ for variant_id, quantity in variants_and_quantities.items():+ order.lines.get(variant_id=variant_id).quantity == quantity+ assert order.shipping_address == address+ assert order.shipping_method == checkout.shipping_method+ assert order.payments.exists()+ assert payment.transactions.count() == 1++ preorder_line = order.lines.filter(variant__is_preorder=True).first()+ assert not preorder_line.allocations.exists()+ preorder_allocation = preorder_line.preorder_allocations.get()+ assert preorder_allocation.quantity == quantity++ stock_line = order.lines.filter(variant__is_preorder=False).first()+ assert stock_line.allocations.exists()+ assert not stock_line.preorder_allocations.exists()++ assert not Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should have been deleted"+ order_confirmed_mock.assert_called_once_with(order)diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex bfe9f2c16c..7e78d58e4f 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -19,7 +19,7 @@ from ....order.utils import (recalculate_order,update_order_prices,)-from ....warehouse.management import allocate_stocks+from ....warehouse.management import allocate_preorders, allocate_stocksfrom ...account.i18n import I18nMixinfrom ...account.types import AddressInputfrom ...channel.types import Channel@@ -419,7 +419,12 @@ class DraftOrderComplete(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, id):manager = info.context.plugins- order = cls.get_node_or_error(info, id, only_type=Order)+ order = cls.get_node_or_error(+ info,+ id,+ only_type=Order,+ qs=models.Order.objects.prefetch_related("lines__variant"),+ )country = get_order_country(order)validate_draft_order(order, country)cls.update_user_fields(order)@@ -435,12 +440,15 @@ class DraftOrderComplete(BaseMutation):order.save()for line in order.lines.all():- if line.variant.track_inventory:+ if line.variant.track_inventory or line.variant.is_preorder_active():line_data = OrderLineData(line=line, quantity=line.quantity, variant=line.variant)+ channel_slug = order.channel.slugtry:- allocate_stocks([line_data], country, order.channel.slug, manager)+ with traced_atomic_transaction():+ allocate_stocks([line_data], country, channel_slug, manager)+ allocate_preorders([line_data], channel_slug)except InsufficientStock as exc:errors = prepare_insufficient_stock_order_validation_errors(exc)raise ValidationError({"lines": errors})diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.pyindex 074122ff86..bf31fa70da 100644--- a/saleor/graphql/order/mutations/fulfillments.py+++ b/saleor/graphql/order/mutations/fulfillments.py@@ -158,6 +158,23 @@ class OrderFulfill(BaseMutation):})+ @classmethod+ def check_lines_for_preorder(cls, order_lines):+ for order_line in order_lines:+ if order_line.variant_id and order_line.variant.is_preorder_active():+ order_line_global_id = graphene.Node.to_global_id(+ "OrderLine", order_line.pk+ )+ raise ValidationError(+ {+ "order_line_id": ValidationError(+ "Can not fulfill preorder variant.",+ code=OrderErrorCode.FULFILL_ORDER_LINE,+ params={"order_lines": [order_line_global_id]},+ )+ }+ )+@classmethoddef check_total_quantity_of_items(cls, quantities_for_lines):flat_quantities = sum(quantities_for_lines, [])@@ -210,6 +227,9 @@ class OrderFulfill(BaseMutation):cls.clean_lines(order_lines, order_line_id_to_total_quantity)+ if site_settings.fulfillment_auto_approve:+ cls.check_lines_for_preorder(order_lines)+cls.check_total_quantity_of_items(quantities_for_lines)lines_for_warehouses = defaultdict(list)@@ -232,7 +252,13 @@ class OrderFulfill(BaseMutation):@classmethod@traced_atomic_transaction()def perform_mutation(cls, _root, info, order, **data):- order = cls.get_node_or_error(info, order, field="order", only_type=Order)+ order = cls.get_node_or_error(+ info,+ order,+ field="order",+ only_type=Order,+ qs=order_models.Order.objects.prefetch_related("lines__variant"),+ )data = data.get("input")cleaned_input = cls.clean_input(info, order, data)@@ -445,6 +471,9 @@ class FulfillmentApprove(BaseMutation):"fulfillments can be accepted.",code=OrderErrorCode.INVALID.value,)++ OrderFulfill.check_lines_for_preorder([line.order_line for line in fulfillment])+if (not info.context.site.settings.fulfillment_allow_unpaidand not fulfillment.order.is_fully_paid()diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.pyindex 6facea264e..1e8d14600a 100644--- a/saleor/graphql/order/tests/test_fulfillment.py+++ b/saleor/graphql/order/tests/test_fulfillment.py@@ -1221,6 +1221,92 @@ def test_order_fulfill_warehouse_duplicated_order_line_id(mock_create_fulfillments.assert_not_called()+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")+def test_order_fulfill_preorder(+ mock_create_fulfillments,+ staff_api_client,+ staff_user,+ order_with_lines,+ permission_manage_orders,+ warehouse,+):+ query = ORDER_FULFILL_QUERY+ order_id = graphene.Node.to_global_id("Order", order_with_lines.id)+ order_line = order_with_lines.lines.first()+ variant = order_line.variant+ variant.is_preorder = True+ variant.save(update_fields=["is_preorder"])++ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ variables = {+ "order": order_id,+ "input": {+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 0, "warehouse": warehouse_id}],+ }+ ]+ },+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfill"]+ assert data["errors"]+ error = data["errors"][0]+ assert error["field"] == "orderLineId"+ assert error["code"] == OrderErrorCode.FULFILL_ORDER_LINE.name+ assert error["orderLines"]++ mock_create_fulfillments.assert_not_called()+++def test_order_fulfill_preorder_waiting_fulfillment(+ staff_api_client,+ order_with_lines,+ permission_manage_orders,+ warehouse,+ site_settings,+):+ """If fulfillment_auto_approve is set to False,+ it's possible to fulfill lines to WAITING_FOR_APPROVAL status."""+ site_settings.fulfillment_auto_approve = False+ site_settings.save(update_fields=["fulfillment_auto_approve"])+ query = ORDER_FULFILL_QUERY+ order_id = graphene.Node.to_global_id("Order", order_with_lines.id)+ order_line = order_with_lines.lines.first()+ variant = order_line.variant+ variant.is_preorder = True+ variant.save(update_fields=["is_preorder"])++ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ variables = {+ "order": order_id,+ "input": {+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],+ }+ ]+ },+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfill"]+ assert not data["errors"]+ assert (+ order_with_lines.fulfillments.first().status+ == FulfillmentStatus.WAITING_FOR_APPROVAL+ )++@patch("saleor.plugins.manager.PluginsManager.notify")def test_fulfillment_update_tracking(send_fulfillment_update_mock,@@ -1844,6 +1930,36 @@ def test_fulfillment_approve_order_unpaid(assert data["errors"][0]["code"] == OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER.name+def test_fulfillment_approve_preorder(+ staff_api_client, fulfillment, permission_manage_orders, site_settings+):+ """Fulfillment with WAITING_FOR_APPROVAL status can not be fulfilled+ if it contains variant in preorder."""+ site_settings.fulfillment_auto_approve = False+ site_settings.save(update_fields=["fulfillment_auto_approve"])++ order_line = fulfillment.order.lines.first()+ variant = order_line.variant+ variant.is_preorder = True+ variant.save(update_fields=["is_preorder"])+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL+ fulfillment.save(update_fields=["status"])+ query = APPROVE_FULFILLMENT_MUTATION++ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)+ variables = {"id": fulfillment_id, "notifyCustomer": False}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfillmentApprove"]+ assert data["errors"]++ error = data["errors"][0]+ assert error["field"] == "orderLineId"+ assert error["code"] == OrderErrorCode.FULFILL_ORDER_LINE.name++QUERY_FULFILLMENT = """query fulfillment($id: ID!) {order(id: $id) {diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 95e41761b8..37e876170a 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -34,7 +34,7 @@ from ....payment.models import Paymentfrom ....plugins.manager import PluginsManagerfrom ....product.models import ProductVariant, ProductVariantChannelListingfrom ....shipping.models import ShippingMethod, ShippingMethodChannelListing-from ....warehouse.models import Allocation, Stock, Warehouse+from ....warehouse.models import Allocation, PreorderAllocation, Stock, Warehousefrom ....warehouse.tests.utils import get_available_quantity_for_stockfrom ...order.mutations.orders import (clean_order_cancel,@@ -3631,6 +3631,82 @@ def test_draft_order_complete_unavailable_for_purchase(assert error["code"] == OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name+def test_draft_order_complete_preorders(+ staff_api_client,+ permission_manage_orders,+ staff_user,+ draft_order_with_preorder_lines,+):+ order = draft_order_with_preorder_lines++ # Ensure no events were created+ assert not OrderEvent.objects.exists()++ # Ensure no preorder allocation were created+ assert not PreorderAllocation.objects.filter(order_line__order=order).exists()++ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["draftOrderComplete"]["order"]+ order.refresh_from_db()+ assert data["status"] == order.status.upper()+ assert data["origin"] == OrderOrigin.DRAFT.upper()++ for line in order.lines.all():+ preorder_allocation = line.preorder_allocations.get()+ assert preorder_allocation.quantity == line.quantity_unfulfilled++ # ensure there are only 2 events with correct types+ event_params = {+ "user": staff_user,+ "type__in": [+ order_events.OrderEvents.PLACED_FROM_DRAFT,+ order_events.OrderEvents.CONFIRMED,+ ],+ "parameters": {},+ }+ matching_events = OrderEvent.objects.filter(**event_params)+ assert matching_events.count() == 2+ assert matching_events[0].type != matching_events[1].type+ assert not OrderEvent.objects.exclude(**event_params).exists()+++def test_draft_order_complete_insufficient_stock_preorders(+ staff_api_client,+ permission_manage_orders,+ staff_user,+ draft_order_with_preorder_lines,+ channel_USD,+):+ order = draft_order_with_preorder_lines++ # Ensure no events were created+ assert not OrderEvent.objects.exists()++ line = order.lines.order_by("-quantity").first()+ channel_listing = line.variant.channel_listings.get(channel_id=channel_USD.id)+ line.quantity = channel_listing.preorder_quantity_threshold + 1+ line.save()++ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ error = content["data"]["draftOrderComplete"]["errors"][0]+ order.refresh_from_db()+ assert order.status == OrderStatus.DRAFT+ assert order.origin == OrderOrigin.DRAFT++ assert error["field"] == "lines"+ assert error["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name++ORDER_LINES_CREATE_MUTATION = """mutation OrderLinesCreate($orderId: ID!, $variantId: ID!, $quantity: Int!) {orderLinesCreate(id: $orderId,diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.pyindex a7bdfc5428..ec79aebcad 100644--- a/saleor/graphql/order/utils.py+++ b/saleor/graphql/order/utils.py@@ -7,7 +7,7 @@ from django.core.exceptions import ValidationErrorfrom ...core.exceptions import InsufficientStockfrom ...order.error_codes import OrderErrorCodefrom ...product.models import Product, ProductChannelListing, ProductVariant-from ...warehouse.availability import check_stock_quantity+from ...warehouse.availability import check_stock_and_preorder_quantityfrom ..core.validators import validate_variants_available_in_channelif TYPE_CHECKING:@@ -83,7 +83,7 @@ def validate_order_lines(order: "Order", country: str, errors: T_ERRORS):)elif line.variant.track_inventory:try:- check_stock_quantity(+ check_stock_and_preorder_quantity(line.variant, country, order.channel.slug, line.quantity)except InsufficientStock as exc:diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.pyindex 73c41478a4..7807225026 100644--- a/saleor/graphql/product/bulk_mutations/products.py+++ b/saleor/graphql/product/bulk_mutations/products.py@@ -274,6 +274,14 @@ class ProductVariantBulkCreate(BaseMutation):cleaned_input["sku"] = clean_variant_sku(cleaned_input.get("sku"))+ preorder_settings = cleaned_input.get("preorder")+ if preorder_settings:+ cleaned_input["is_preorder"] = True+ cleaned_input["preorder_global_threshold"] = preorder_settings.get(+ "global_threshold"+ )+ cleaned_input["preorder_end_date"] = preorder_settings.get("end_date")+return cleaned_input@classmethod@@ -463,6 +471,7 @@ class ProductVariantBulkCreate(BaseMutation):channel = channel_listing_data["channel"]price = channel_listing_data["price"]cost_price = channel_listing_data.get("cost_price")+ preorder_quantity_threshold = channel_listing_data.get("preorder_threshold")variant_channel_listings.append(models.ProductVariantChannelListing(channel=channel,@@ -470,6 +479,7 @@ class ProductVariantBulkCreate(BaseMutation):price_amount=price,cost_price_amount=cost_price,currency=channel.currency_code,+ preorder_quantity_threshold=preorder_quantity_threshold,))models.ProductVariantChannelListing.objects.bulk_create(diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.pyindex 266f3b36ae..3bc9dd9151 100644--- a/saleor/graphql/product/dataloaders/products.py+++ b/saleor/graphql/product/dataloaders/products.py@@ -234,7 +234,8 @@ class VariantChannelListingByVariantIdLoader(DataLoader):def batch_load(self, keys):variant_channel_listings = ProductVariantChannelListing.objects.filter(variant_id__in=keys- )+ ).annotate_preorder_quantity_allocated()+variant_id_variant_channel_listings_map = defaultdict(list)for variant_channel_listing in variant_channel_listings:variant_id_variant_channel_listings_map[@@ -283,7 +284,9 @@ class VariantChannelListingByVariantIdAndChannelLoader("variant_id__in": variant_ids,"price_amount__isnull": False,}- variant_channel_listings = ProductVariantChannelListing.objects.filter(**filter)+ variant_channel_listings = ProductVariantChannelListing.objects.filter(+ **filter+ ).annotate_preorder_quantity_allocated()variant_channel_listings_map: Dict[int, ProductVariantChannelListing] = {}for variant_channel_listing in variant_channel_listings.iterator():diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex f938839831..74c391cc96 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -8,6 +8,7 @@ from django.contrib.postgres.search import SearchQuery, SearchRankfrom django.db.models import Exists, F, FloatField, OuterRef, Q, Subquery, Sumfrom django.db.models.fields import IntegerFieldfrom django.db.models.functions import Cast, Coalesce+from django.utils import timezonefrom graphene_django.filter import GlobalIDMultipleChoiceFilterfrom ...attribute import AttributeInputType@@ -383,6 +384,20 @@ def filter_has_category(qs, _, value):return qs.filter(category__isnull=not value)+def filter_has_preordered_variants(qs, _, value):+ variants = (+ ProductVariant.objects.filter(is_preorder=True)+ .filter(+ Q(preorder_end_date__isnull=True) | Q(preorder_end_date__gt=timezone.now())+ )+ .values("product_id")+ )+ if value:+ return qs.filter(Exists(variants.filter(product_id=OuterRef("pk"))))+ else:+ return qs.filter(~Exists(variants.filter(product_id=OuterRef("pk"))))++def filter_collections(qs, _, value):if value:_, collection_pks = resolve_global_ids_to_primary_keys(@@ -527,6 +542,17 @@ def filter_sku_list(qs, _, value):return qs.filter(sku__in=value)+def filter_is_preorder(qs, _, value):+ if value:+ return qs.filter(is_preorder=True).filter(+ Q(preorder_end_date__isnull=True) | Q(preorder_end_date__gte=timezone.now())+ )+ return qs.filter(+ Q(is_preorder=False)+ | (Q(is_preorder=True)) & Q(preorder_end_date__lt=timezone.now())+ )++def filter_quantity(qs, quantity_value, warehouses=None):"""Filter products queryset by product variants quantity.@@ -583,6 +609,9 @@ class ProductFilter(MetadataFilterBase):search = django_filters.CharFilter(method=filter_search)gift_card = django_filters.BooleanFilter(method=filter_gift_card)ids = GlobalIDMultipleChoiceFilter(method=filter_product_ids)+ has_preordered_variants = django_filters.BooleanFilter(+ method=filter_has_preordered_variants+ )class Meta:model = Product@@ -627,6 +656,7 @@ class ProductVariantFilter(MetadataFilterBase):method=filter_fields_containing_value("name", "product__name", "sku"))sku = ListObjectTypeFilter(input_class=graphene.String, method=filter_sku_list)+ is_preorder = django_filters.BooleanFilter(method=filter_is_preorder)class Meta:model = ProductVariantdiff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.pyindex 37d8da3905..3cd79c9900 100644--- a/saleor/graphql/product/mutations/channels.py+++ b/saleor/graphql/product/mutations/channels.py@@ -20,6 +20,7 @@ from ....product.tasks import update_product_discounted_price_taskfrom ...channel import ChannelContextfrom ...channel.mutations import BaseChannelListingMutationfrom ...channel.types import Channel+from ...core.descriptions import ADDED_IN_31from ...core.mutations import BaseMutationfrom ...core.scalars import PositiveDecimalfrom ...core.types.common import (@@ -305,6 +306,9 @@ class ProductVariantChannelListingAddInput(graphene.InputObjectType):required=True, description="Price of the particular variant in channel.")cost_price = PositiveDecimal(description="Cost price of the variant in channel.")+ preorder_threshold = graphene.Int(+ description=f"{ADDED_IN_31} The threshold for preorder variant in channel."+ )class ProductVariantChannelListingUpdate(BaseMutation):@@ -425,6 +429,10 @@ class ProductVariantChannelListingUpdate(BaseMutation):defaults["cost_price_amount"] = channel_listing_data.get("cost_price", None)+ if "preorder_threshold" in channel_listing_data.keys():+ defaults["preorder_quantity_threshold"] = channel_listing_data.get(+ "preorder_threshold", None+ )ProductVariantChannelListing.objects.update_or_create(variant=variant,channel=channel,diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 52f91d62cd..fd3152e546 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -10,7 +10,7 @@ from django.utils.text import slugifyfrom ....attribute import AttributeInputType, AttributeTypefrom ....attribute import models as attribute_models-from ....core.exceptions import PermissionDenied+from ....core.exceptions import PermissionDenied, PreorderAllocationErrorfrom ....core.permissions import ProductPermissions, ProductTypePermissionsfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils.editorjs import clean_editor_js@@ -33,9 +33,11 @@ from ....product.thumbnails import ()from ....product.utils import delete_categories, get_products_ids_without_variantsfrom ....product.utils.variants import generate_and_set_variant_name+from ....warehouse.management import deactivate_preorder_for_variantfrom ...attribute.types import AttributeValueInputfrom ...attribute.utils import AttributeAssignmentMixin, AttrValuesInputfrom ...channel import ChannelContext+from ...core.descriptions import ADDED_IN_31from ...core.inputs import ReorderInputfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.scalars import WeightScalar@@ -746,6 +748,13 @@ class ProductDelete(ModelDeleteMutation):).delete()+class PreorderSettingsInput(graphene.InputObjectType):+ global_threshold = graphene.Int(+ description="The global threshold for preorder variant."+ )+ end_date = graphene.DateTime(description="The end date for preorder.")++class ProductVariantInput(graphene.InputObjectType):attributes = graphene.List(graphene.NonNull(AttributeValueInput),@@ -760,6 +769,9 @@ class ProductVariantInput(graphene.InputObjectType):))weight = WeightScalar(description="Weight of the Product Variant.", required=False)+ preorder = PreorderSettingsInput(+ description=f"{ADDED_IN_31} Determines if variant is in preorder."+ )class ProductVariantCreateInput(ProductVariantInput):@@ -888,6 +900,14 @@ class ProductVariantCreate(ModelMutation):if "sku" in cleaned_input:cleaned_input["sku"] = clean_variant_sku(cleaned_input.get("sku"))+ preorder_settings = cleaned_input.get("preorder")+ if preorder_settings:+ cleaned_input["is_preorder"] = True+ cleaned_input["preorder_global_threshold"] = preorder_settings.get(+ "global_threshold"+ )+ cleaned_input["preorder_end_date"] = preorder_settings.get("end_date")+return cleaned_input@classmethod@@ -1691,3 +1711,54 @@ class VariantMediaUnassign(BaseMutation):lambda: info.context.plugins.product_variant_updated(variant.node))return VariantMediaUnassign(product_variant=variant, media=media)+++class ProductVariantPreorderDeactivate(BaseMutation):+ product_variant = graphene.Field(+ ProductVariant, description="Product variant with ended preorder."+ )++ class Arguments:+ id = graphene.ID(+ required=True,+ description="ID of a variant which preorder should be deactivated.",+ )++ class Meta:+ description = (+ f"{ADDED_IN_31} Deactivates product variant preorder."+ "It changes all preorder allocation into regular allocation."+ )+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = ProductError++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info, id):+ qs = models.ProductVariant.objects.prefetched_for_webhook()+ variant = cls.get_node_or_error(+ info, id, field="id", only_type=ProductVariant, qs=qs+ )+ if not variant.is_preorder:+ raise ValidationError(+ {+ "id": ValidationError(+ "This variant is not in preorder.",+ code=ProductErrorCode.INVALID,+ )+ }+ )++ try:+ deactivate_preorder_for_variant(variant)+ except PreorderAllocationError as error:+ raise ValidationError(+ str(error),+ code=ProductErrorCode.PREORDER_VARIANT_CANNOT_BE_DEACTIVATED,+ )++ variant = ChannelContext(node=variant, channel_slug=None)+ transaction.on_commit(+ lambda: info.context.plugins.product_variant_updated(variant.node)+ )+ return ProductVariantPreorderDeactivate(product_variant=variant)diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 3306488980..00fe991dae 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -81,6 +81,7 @@ from .mutations.products import (ProductUpdate,ProductVariantCreate,ProductVariantDelete,+ ProductVariantPreorderDeactivate,ProductVariantReorder,ProductVariantSetDefault,ProductVariantUpdate,@@ -455,6 +456,7 @@ class ProductMutations(graphene.ObjectType):product_variant_reorder_attribute_values = (ProductVariantReorderAttributeValues.Field())+ product_variant_preorder_deactivate = ProductVariantPreorderDeactivate.Field()variant_media_assign = VariantMediaAssign.Field()variant_media_unassign = VariantMediaUnassign.Field()diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 73798d10c1..bc514bb694 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -10,6 +10,7 @@ import pytestimport pytzfrom django.core.exceptions import ValidationErrorfrom django.db.models import Sum+from django.utils import timezonefrom django.utils.dateparse import parse_datetimefrom django.utils.html import strip_tagsfrom django.utils.text import slugify@@ -2738,6 +2739,88 @@ def test_query_products_with_filter_ids(assert [node["node"]["id"] for node in products_data] == product_ids+def test_products_query_with_filter_has_preordered_variants_false(+ query_products_with_filter,+ staff_api_client,+ preorder_variant_global_threshold,+ product_without_shipping,+ permission_manage_products,+):+ product = product_without_shipping+ variables = {"filter": {"hasPreorderedVariants": False}}+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ product_id = graphene.Node.to_global_id("Product", product.id)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == product_id+ assert products[0]["node"]["name"] == product.name+++def test_products_query_with_filter_has_preordered_variants_true(+ query_products_with_filter,+ staff_api_client,+ preorder_variant_global_threshold,+ product_without_shipping,+ permission_manage_products,+):+ product = preorder_variant_global_threshold.product+ variables = {"filter": {"hasPreorderedVariants": True}}+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ product_id = graphene.Node.to_global_id("Product", product.id)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == product_id+ assert products[0]["node"]["name"] == product.name+++def test_products_query_with_filter_has_preordered_variants_before_end_date(+ query_products_with_filter,+ staff_api_client,+ preorder_variant_global_threshold,+ permission_manage_products,+):+ variant = preorder_variant_global_threshold+ variant.preorder_end_date = timezone.now() + timedelta(days=3)+ variant.save(update_fields=["preorder_end_date"])++ product = preorder_variant_global_threshold.product+ variables = {"filter": {"hasPreorderedVariants": True}}+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ product_id = graphene.Node.to_global_id("Product", product.id)+ products = content["data"]["products"]["edges"]++ assert len(products) == 1+ assert products[0]["node"]["id"] == product_id+ assert products[0]["node"]["name"] == product.name+++def test_products_query_with_filter_has_preordered_variants_after_end_date(+ query_products_with_filter,+ staff_api_client,+ preorder_variant_global_threshold,+ permission_manage_products,+):+ variant = preorder_variant_global_threshold+ variant.preorder_end_date = timezone.now() - timedelta(days=3)+ variant.save(update_fields=["preorder_end_date"])++ variables = {"filter": {"hasPreorderedVariants": True}}+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(query_products_with_filter, variables)+ content = get_graphql_content(response)+ products = content["data"]["products"]["edges"]++ assert len(products) == 0++QUERY_PRODUCT_MEDIA_BY_ID = """query productMediaById($mediaId: ID!, $productId: ID!, $channel: String) {product(id: $productId, channel: $channel) {diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex 6084fc8e4d..66de793d20 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -1,5 +1,5 @@import json-from datetime import datetime+from datetime import datetime, timedeltafrom unittest.mock import ANY, patchfrom uuid import uuid4@@ -14,6 +14,7 @@ from prices import Money, TaxedMoneyfrom ....attribute import AttributeInputTypefrom ....attribute.models import AttributeValuefrom ....attribute.utils import associate_attribute_values_to_instance+from ....core.exceptions import PreorderAllocationErrorfrom ....core.units import WeightUnitsfrom ....order import OrderEvents, OrderStatusfrom ....order.models import OrderEvent, OrderLine@@ -21,7 +22,7 @@ from ....product.error_codes import ProductErrorCodefrom ....product.models import Product, ProductChannelListing, ProductVariantfrom ....tests.utils import dummy_editorjs, flush_post_commit_hooksfrom ....warehouse.error_codes import StockErrorCode-from ....warehouse.models import Stock, Warehouse+from ....warehouse.models import Allocation, Stock, Warehousefrom ...core.enums import WeightUnitsEnumfrom ...tests.utils import (assert_no_permission,@@ -150,6 +151,10 @@ QUERY_PRODUCT_VARIANT_CHANNEL_LISTING = """currencyamount}+ preorderThreshold {+ quantity+ soldUnits+ }}}}@@ -187,6 +192,10 @@ def test_get_product_variant_channel_listing_as_staff_user("currency": channel_listing.currency,"amount": channel_listing.cost_price_amount,},+ "preorderThreshold": {+ "quantity": channel_listing.preorder_quantity_threshold,+ "soldUnits": 0,+ },} in data["channelListings"]assert len(data["channelListings"]) == variant.channel_listings.count()@@ -222,6 +231,10 @@ def test_get_product_variant_channel_listing_as_app("currency": channel_listing.currency,"amount": channel_listing.cost_price_amount,},+ "preorderThreshold": {+ "quantity": channel_listing.preorder_quantity_threshold,+ "soldUnits": 0,+ },} in data["channelListings"]assert len(data["channelListings"]) == variant.channel_listings.count()@@ -377,6 +390,98 @@ def test_get_product_variant_stocks_no_channel_shipping_zones(assert stocks_count > 0+QUERY_PRODUCT_VARIANT_PREORDER = """+ query ProductVariantDetails($id: ID!, $channel: String) {+ productVariant(id: $id, channel: $channel) {+ preorder {+ globalThreshold+ globalSoldUnits+ endDate+ }+ }+ }+"""+++def test_get_product_variant_preorder_as_staff(+ staff_api_client,+ preorder_variant_global_and_channel_threshold,+ preorder_allocation,+ channel_USD,+ permission_manage_products,+):+ # given+ variant = preorder_variant_global_and_channel_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {"id": variant_id, "channel": channel_USD.slug}++ # when+ response = staff_api_client.post_graphql(+ QUERY_PRODUCT_VARIANT_PREORDER,+ variables,+ permissions=[permission_manage_products],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["productVariant"]["preorder"]+ assert data["globalThreshold"] == variant.preorder_global_threshold+ assert data["globalSoldUnits"] == preorder_allocation.quantity+ assert data["endDate"] == variant.preorder_end_date+++def test_get_product_variant_preorder_as_customer_not_allowed_fields(+ user_api_client,+ preorder_variant_global_threshold,+ channel_USD,+):+ # given+ variant = preorder_variant_global_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {"id": variant_id, "channel": channel_USD.slug}++ # when+ response = user_api_client.post_graphql(+ QUERY_PRODUCT_VARIANT_PREORDER,+ variables,+ )++ # then+ assert_no_permission(response)+++def test_get_product_variant_preorder_as_customer_allowed_fields(+ user_api_client,+ preorder_variant_global_threshold,+ channel_USD,+):+ # given+ variant = preorder_variant_global_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ query = """+ query ProductVariantDetails($id: ID!, $channel: String) {+ productVariant(id: $id, channel: $channel) {+ preorder {+ endDate+ }+ }+ }+ """+ variables = {"id": variant_id, "channel": channel_USD.slug}++ # when+ response = user_api_client.post_graphql(+ query,+ variables,+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["productVariant"]["preorder"]+ assert data["endDate"] == variant.preorder_end_date++CREATE_VARIANT_MUTATION = """mutation createVariant ($productId: ID!,@@ -384,7 +489,8 @@ CREATE_VARIANT_MUTATION = """$stocks: [StockInput!],$attributes: [AttributeValueInput!]!,$weight: WeightScalar,- $trackInventory: Boolean) {+ $trackInventory: Boolean,+ $preorder: PreorderSettingsInput) {productVariantCreate(input: {product: $productId,@@ -392,7 +498,8 @@ CREATE_VARIANT_MUTATION = """stocks: $stocks,attributes: $attributes,trackInventory: $trackInventory,- weight: $weight+ weight: $weight,+ preorder: $preorder}) {errors {field@@ -432,6 +539,10 @@ CREATE_VARIANT_MUTATION = """slug}}+ preorder {+ globalThreshold+ endDate+ }}}}@@ -495,6 +606,57 @@ def test_create_variant(updated_webhook_mock.assert_not_called()+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_create_variant_preorder(+ updated_webhook_mock,+ created_webhook_mock,+ staff_api_client,+ product,+ product_type,+ permission_manage_products,+):+ query = CREATE_VARIANT_MUTATION+ product_id = graphene.Node.to_global_id("Product", product.pk)+ variant_id = graphene.Node.to_global_id(+ "Attribute", product_type.variant_attributes.first().pk+ )+ variant_value = "test-value"+ global_threshold = 10+ end_date = (+ (datetime.now() + timedelta(days=3))+ .astimezone()+ .replace(microsecond=0)+ .isoformat()+ )++ variables = {+ "productId": product_id,+ "sku": "1",+ "weight": 10.22,+ "attributes": [{"id": variant_id, "values": [variant_value]}],+ "preorder": {+ "globalThreshold": global_threshold,+ "endDate": end_date,+ },+ }++ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ flush_post_commit_hooks()++ assert not content["errors"]+ data = content["productVariant"]+ assert data["name"] == variant_value++ assert data["preorder"]["globalThreshold"] == global_threshold+ assert data["preorder"]["endDate"] == end_date+ created_webhook_mock.assert_called_once_with(product.variants.last())+ updated_webhook_mock.assert_not_called()++@patch("saleor.plugins.manager.PluginsManager.product_variant_created")def test_create_variant_with_file_attribute(created_webhook_mock,@@ -2879,6 +3041,98 @@ def test_update_product_variant_with_price_does_not_raise_price_validation_errorassert not content["data"]["productVariantUpdate"]["errors"]+QUERY_UPDATE_VARIANT_PREORDER = """+ mutation updateVariant (+ $id: ID!,+ $sku: String!,+ $preorder: PreorderSettingsInput) {+ productVariantUpdate(+ id: $id,+ input: {+ sku: $sku,+ preorder: $preorder,+ }) {+ productVariant {+ sku+ preorder {+ globalThreshold+ endDate+ }+ }+ }+ }+"""+++def test_update_product_variant_change_preorder_data(+ staff_api_client,+ permission_manage_products,+ preorder_variant_global_threshold,+):+ variant = preorder_variant_global_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ sku = "test sku"++ new_global_threshold = variant.preorder_global_threshold + 5+ assert variant.preorder_end_date is None+ new_preorder_end_date = (+ (datetime.now() + timedelta(days=3))+ .astimezone()+ .replace(microsecond=0)+ .isoformat()+ )+ variables = {+ "id": variant_id,+ "sku": sku,+ "preorder": {+ "globalThreshold": new_global_threshold,+ "endDate": new_preorder_end_date,+ },+ }++ response = staff_api_client.post_graphql(+ QUERY_UPDATE_VARIANT_PREORDER,+ variables,+ permissions=[permission_manage_products],+ )+ variant.refresh_from_db()+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantUpdate"]["productVariant"]++ assert data["sku"] == sku+ assert data["preorder"]["globalThreshold"] == new_global_threshold+ assert data["preorder"]["endDate"] == new_preorder_end_date+++def test_update_product_variant_can_not_turn_off_preorder(+ staff_api_client,+ permission_manage_products,+ preorder_variant_global_threshold,+):+ """Passing None with `preorder` field can not turn off preorder,+ it could be done only with ProductVariantPreorderDeactivate mutation."""+ variant = preorder_variant_global_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ sku = "test sku"++ variables = {"id": variant_id, "sku": sku, "preorder": None}++ response = staff_api_client.post_graphql(+ QUERY_UPDATE_VARIANT_PREORDER,+ variables,+ permissions=[permission_manage_products],+ )+ variant.refresh_from_db()+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantUpdate"]["productVariant"]++ assert data["sku"] == sku+ assert data["preorder"]["globalThreshold"] == variant.preorder_global_threshold+ assert data["preorder"]["endDate"] is None++DELETE_VARIANT_MUTATION = """mutation variantDelete($id: ID!) {productVariantDelete(id: $id) {@@ -3635,6 +3889,13 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """currencyamount}+ preorderThreshold {+ quantity+ }+ }+ preorder {+ globalThreshold+ endDate}}count@@ -4092,6 +4353,7 @@ def test_product_variant_bulk_create_channel_listings_input("amount": variants[0]["channelListings"][0]["costPrice"],"currency": channel_USD.currency_code,},+ "preorderThreshold": {"quantity": None},}],},@@ -4108,6 +4370,7 @@ def test_product_variant_bulk_create_channel_listings_input("amount": variants[1]["channelListings"][0]["costPrice"],"currency": channel_USD.currency_code,},+ "preorderThreshold": {"quantity": None},},{"channel": {"slug": channel_PLN.slug},@@ -4119,6 +4382,7 @@ def test_product_variant_bulk_create_channel_listings_input("amount": variants[1]["channelListings"][1]["costPrice"],"currency": channel_PLN.currency_code,},+ "preorderThreshold": {"quantity": None},},],},@@ -4136,6 +4400,126 @@ def test_product_variant_bulk_create_channel_listings_input()+def test_product_variant_bulk_create_preorder_channel_listings_input(+ staff_api_client,+ product_available_in_many_channels,+ permission_manage_products,+ size_attribute,+ channel_USD,+ channel_PLN,+):+ product = product_available_in_many_channels+ ProductChannelListing.objects.filter(product=product, channel=channel_PLN).update(+ is_published=False+ )+ product_variant_count = ProductVariant.objects.count()+ product_id = graphene.Node.to_global_id("Product", product.pk)+ attribute_value_count = size_attribute.values.count()+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)+ attribute_value = size_attribute.values.last()++ global_threshold = 10+ end_date = (+ (datetime.now() + timedelta(days=3))+ .astimezone()+ .replace(microsecond=0)+ .isoformat()+ )++ variants = [+ {+ "sku": str(uuid4())[:12],+ "channelListings": [+ {+ "price": 10.0,+ "costPrice": 11.0,+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),+ "preorderThreshold": 5,+ }+ ],+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],+ "preorder": {+ "globalThreshold": global_threshold,+ "endDate": end_date,+ },+ },+ {+ "sku": str(uuid4())[:12],+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],+ "channelListings": [+ {+ "price": 15.0,+ "costPrice": 16.0,+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),+ "preorderThreshold": None,+ },+ {+ "price": 12.0,+ "costPrice": 13.0,+ "channelId": graphene.Node.to_global_id("Channel", channel_PLN.pk),+ "preorderThreshold": 4,+ },+ ],+ "preorder": {+ "globalThreshold": global_threshold,+ "endDate": end_date,+ },+ },+ ]++ variables = {"productId": product_id, "variants": variants}+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkCreate"]+ assert not data["errors"]+ assert data["count"] == 2+ assert product_variant_count + 2 == ProductVariant.objects.count()+ assert attribute_value_count + 1 == size_attribute.values.count()++ expected_result = {+ variants[0]["sku"]: {+ "sku": variants[0]["sku"],+ "channelListings": [{"preorderThreshold": {"quantity": 5}}],+ "preorder": {+ "globalThreshold": global_threshold,+ "endDate": end_date,+ },+ },+ variants[1]["sku"]: {+ "sku": variants[1]["sku"],+ "channelListings": [+ {"preorderThreshold": {"quantity": None}},+ {"preorderThreshold": {"quantity": 4}},+ ],+ "preorder": {+ "globalThreshold": global_threshold,+ "endDate": end_date,+ },+ },+ }+ for variant_data in data["productVariants"]:+ variant_data.pop("id")+ assert variant_data["sku"] in expected_result+ expected_variant = expected_result[variant_data["sku"]]+ expected_channel_listing_thresholds = [+ channel_listing["preorderThreshold"]["quantity"]+ for channel_listing in expected_variant["channelListings"]+ ]+ assert all(+ [+ channel_listing["preorderThreshold"]["quantity"]+ in expected_channel_listing_thresholds+ for channel_listing in variant_data["channelListings"]+ ]+ )+ preorder_data = variant_data["preorder"]+ assert preorder_data["globalThreshold"] == global_threshold+ assert preorder_data["endDate"] == end_date++def test_product_variant_bulk_create_duplicated_channels(staff_api_client,product_available_in_many_channels,@@ -5071,3 +5455,170 @@ def test_query_product_variant_for_federation(api_client, variant, channel_USD):"name": variant.name,}]+++QUERY_VARIANT_DEACTIVATE_PREORDER = """+ mutation deactivatePreorder (+ $id: ID!+ ) {+ productVariantPreorderDeactivate(id: $id) {+ productVariant {+ sku+ preorder {+ globalThreshold+ endDate+ }+ stocks {+ quantityAllocated+ }+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_product_variant_deactivate_preorder(+ updated_webhook_mock,+ staff_api_client,+ permission_manage_products,+ preorder_variant_global_and_channel_threshold,+ preorder_allocation,+):+ variant = preorder_variant_global_and_channel_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ allocations_before = Allocation.objects.filter(+ stock__product_variant_id=variant.pk+ ).count()++ response = staff_api_client.post_graphql(+ QUERY_VARIANT_DEACTIVATE_PREORDER,+ {"id": variant_id},+ permissions=[permission_manage_products],+ )+ variant.refresh_from_db()+ content = get_graphql_content(response)+ flush_post_commit_hooks()+ data = content["data"]["productVariantPreorderDeactivate"]["productVariant"]++ assert not data["preorder"]+ assert data["stocks"][0]["quantityAllocated"] > allocations_before++ updated_webhook_mock.assert_called_once_with(variant)+++def test_product_variant_deactivate_preorder_non_preorder_variant(+ staff_api_client,+ permission_manage_products,+ variant,+):+ assert variant.is_preorder is False+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ response = staff_api_client.post_graphql(+ QUERY_VARIANT_DEACTIVATE_PREORDER,+ {"id": variant_id},+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ error = content["data"]["productVariantPreorderDeactivate"]["errors"][0]++ assert error["field"] == "id"+ assert error["code"] == ProductErrorCode.INVALID.name+++@patch("saleor.graphql.product.mutations.products.deactivate_preorder_for_variant")+def test_product_variant_deactivate_preorder_cannot_deactivate(+ mock_deactivate_preorder_for_variant,+ staff_api_client,+ permission_manage_products,+ preorder_variant_global_and_channel_threshold,+ preorder_allocation,+):+ variant = preorder_variant_global_and_channel_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ mock_deactivate_preorder_for_variant.side_effect = PreorderAllocationError(+ preorder_allocation.order_line+ )++ response = staff_api_client.post_graphql(+ QUERY_VARIANT_DEACTIVATE_PREORDER,+ {"id": variant_id},+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ error = content["data"]["productVariantPreorderDeactivate"]["errors"][0]++ assert error["field"] is None+ assert error["code"] == ProductErrorCode.PREORDER_VARIANT_CANNOT_BE_DEACTIVATED.name+++def test_product_variant_deactivate_preorder_as_customer(+ user_api_client,+ preorder_variant_global_and_channel_threshold,+):+ variant = preorder_variant_global_and_channel_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ response = user_api_client.post_graphql(+ QUERY_VARIANT_DEACTIVATE_PREORDER,+ {"id": variant_id},+ )++ assert_no_permission(response)+++def test_product_variant_deactivate_preorder_as_anonymous(+ api_client,+ preorder_variant_global_and_channel_threshold,+):+ variant = preorder_variant_global_and_channel_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ response = api_client.post_graphql(+ QUERY_VARIANT_DEACTIVATE_PREORDER,+ {"id": variant_id},+ )++ assert_no_permission(response)+++def test_product_variant_deactivate_preorder_as_app_with_permission(+ app_api_client,+ preorder_variant_global_and_channel_threshold,+ permission_manage_products,+):+ variant = preorder_variant_global_and_channel_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ response = app_api_client.post_graphql(+ QUERY_VARIANT_DEACTIVATE_PREORDER,+ {"id": variant_id},+ permissions=[permission_manage_products],+ )++ content = get_graphql_content(response)+ data = content["data"]["productVariantPreorderDeactivate"]["productVariant"]+ assert not data["preorder"]+++def test_product_variant_deactivate_preorder_as_app(+ app_api_client,+ preorder_variant_global_and_channel_threshold,+):+ variant = preorder_variant_global_and_channel_threshold+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ response = app_api_client.post_graphql(+ QUERY_VARIANT_DEACTIVATE_PREORDER,+ {"id": variant_id},+ )++ assert_no_permission(response)diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.pyindex 75c6036e2f..afce70c218 100644--- a/saleor/graphql/product/tests/test_variant_availability.py+++ b/saleor/graphql/product/tests/test_variant_availability.py@@ -226,3 +226,62 @@ def test_variant_quantity_available_without_inventory_tracking_and_stocks(variant_data = content["data"]["productVariant"]assert variant_data["deprecatedByCountry"] == settings.MAX_CHECKOUT_LINE_QUANTITYassert variant_data["byAddress"] == settings.MAX_CHECKOUT_LINE_QUANTITY+++@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)+def test_variant_quantity_available_preorder_with_channel_threshold(+ api_client,+ preorder_variant_channel_threshold,+ channel_USD,+):+ variant = preorder_variant_channel_threshold+ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "country": COUNTRY_CODE,+ "channel": channel_USD.slug,+ }+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)+ content = get_graphql_content(response)+ variant_data = content["data"]["productVariant"]+ channel_listing = variant.channel_listings.get()+ assert (+ variant_data["deprecatedByCountry"]+ == channel_listing.preorder_quantity_threshold+ )+ assert variant_data["byAddress"] == channel_listing.preorder_quantity_threshold+++@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)+def test_variant_quantity_available_preorder_with_global_threshold(+ api_client, preorder_variant_global_threshold, channel_USD+):+ variant = preorder_variant_global_threshold+ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "country": COUNTRY_CODE,+ "channel": channel_USD.slug,+ }+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)+ content = get_graphql_content(response)+ variant_data = content["data"]["productVariant"]+ assert variant_data["deprecatedByCountry"] == variant.preorder_global_threshold+ assert variant_data["byAddress"] == variant.preorder_global_threshold+++@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)+def test_variant_quantity_available_preorder_without_threshold(+ api_client, preorder_variant_global_threshold, settings, channel_USD+):+ variant = preorder_variant_global_threshold+ variant.preorder_global_threshold = None+ variant.save(update_fields=["preorder_global_threshold"])+ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "country": COUNTRY_CODE,+ "channel": channel_USD.slug,+ }+ response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)+ content = get_graphql_content(response)+ variant_data = content["data"]["productVariant"]+ assert variant_data["deprecatedByCountry"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert variant_data["byAddress"] == settings.MAX_CHECKOUT_LINE_QUANTITYdiff --git a/saleor/graphql/product/tests/test_variant_channel_listing_update.py b/saleor/graphql/product/tests/test_variant_channel_listing_update.pyindex ff92270fa9..6640b78651 100644--- a/saleor/graphql/product/tests/test_variant_channel_listing_update.py+++ b/saleor/graphql/product/tests/test_variant_channel_listing_update.py@@ -40,6 +40,9 @@ mutation UpdateProductVariantChannelListing(currency}margin+ preorderThreshold {+ quantity+ }}}}@@ -218,14 +221,24 @@ def test_variant_channel_listing_update_as_staff_user(variant_data = data["variant"]assert not data["errors"]assert variant_data["id"] == variant_id- assert variant_data["channelListings"][0]["price"]["currency"] == "USD"- assert variant_data["channelListings"][0]["price"]["amount"] == price- assert variant_data["channelListings"][0]["costPrice"]["amount"] == price- assert variant_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug- assert variant_data["channelListings"][1]["price"]["currency"] == "PLN"- assert variant_data["channelListings"][1]["price"]["amount"] == second_price- assert variant_data["channelListings"][1]["costPrice"]["amount"] == second_price- assert variant_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug+ channel_usd_data = next(+ channel_data+ for channel_data in variant_data["channelListings"]+ if channel_data["channel"]["id"] == channel_usd_id+ )+ channel_pln_data = next(+ channel_data+ for channel_data in variant_data["channelListings"]+ if channel_data["channel"]["id"] == channel_pln_id+ )+ assert channel_usd_data["price"]["currency"] == "USD"+ assert channel_usd_data["price"]["amount"] == price+ assert channel_usd_data["costPrice"]["amount"] == price+ assert channel_usd_data["channel"]["slug"] == channel_USD.slug+ assert channel_pln_data["price"]["currency"] == "PLN"+ assert channel_pln_data["price"]["amount"] == second_price+ assert channel_pln_data["costPrice"]["amount"] == second_price+ assert channel_pln_data["channel"]["slug"] == channel_PLN.slug@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")@@ -308,12 +321,22 @@ def test_variant_channel_listing_update_as_app(variant_data = data["variant"]assert not data["errors"]assert variant_data["id"] == variant_id- assert variant_data["channelListings"][0]["price"]["currency"] == "USD"- assert variant_data["channelListings"][0]["price"]["amount"] == 1- assert variant_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug- assert variant_data["channelListings"][1]["price"]["currency"] == "PLN"- assert variant_data["channelListings"][1]["price"]["amount"] == 20- assert variant_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug+ channel_usd_data = next(+ channel_data+ for channel_data in variant_data["channelListings"]+ if channel_data["channel"]["id"] == channel_usd_id+ )+ channel_pln_data = next(+ channel_data+ for channel_data in variant_data["channelListings"]+ if channel_data["channel"]["id"] == channel_pln_id+ )+ assert channel_usd_data["price"]["currency"] == "USD"+ assert channel_usd_data["price"]["amount"] == 1+ assert channel_usd_data["channel"]["slug"] == channel_USD.slug+ assert channel_pln_data["price"]["currency"] == "PLN"+ assert channel_pln_data["price"]["amount"] == 20+ assert channel_pln_data["channel"]["slug"] == channel_PLN.slugdef test_variant_channel_listing_update_as_customer(@@ -486,3 +509,71 @@ def test_product_channel_listing_update_invalid_cost_price(# thenassert_negative_positive_decimal_value(response)+++def test_variant_channel_listing_update_preorder(+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN+):+ # given+ ProductChannelListing.objects.create(+ product=product,+ channel=channel_PLN,+ is_published=True,+ )+ variant = product.variants.get()+ variant.is_preorder = True+ variant.save(update_fields=["is_preorder"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)+ preorder_threshold_channel_usd = 10+ preorder_threshold_channel_pln = 20+ variables = {+ "id": variant_id,+ "input": [+ {+ "channelId": channel_usd_id,+ "price": 1,+ "preorderThreshold": preorder_threshold_channel_usd,+ },+ {+ "channelId": channel_pln_id,+ "price": 20,+ "preorderThreshold": preorder_threshold_channel_pln,+ },+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_products,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["productVariantChannelListingUpdate"]+ variant_data = data["variant"]+ assert not data["errors"]+ assert variant_data["id"] == variant_id+ channel_usd_data = next(+ channel_data+ for channel_data in variant_data["channelListings"]+ if channel_data["channel"]["id"] == channel_usd_id+ )+ channel_pln_data = next(+ channel_data+ for channel_data in variant_data["channelListings"]+ if channel_data["channel"]["id"] == channel_pln_id+ )+ assert channel_usd_data["channel"]["slug"] == channel_USD.slug+ assert (+ channel_usd_data["preorderThreshold"]["quantity"]+ == preorder_threshold_channel_usd+ )+ assert channel_pln_data["channel"]["slug"] == channel_PLN.slug+ assert (+ channel_pln_data["preorderThreshold"]["quantity"]+ == preorder_threshold_channel_pln+ )diff --git a/saleor/graphql/product/tests/test_variant_with_filtering.py b/saleor/graphql/product/tests/test_variant_with_filtering.pyindex b06db192c3..dc988cc543 100644--- a/saleor/graphql/product/tests/test_variant_with_filtering.py+++ b/saleor/graphql/product/tests/test_variant_with_filtering.py@@ -1,4 +1,7 @@+from datetime import timedelta+import pytest+from django.utils import timezonefrom ....product.models import Product, ProductVariantfrom ...tests.utils import get_graphql_content@@ -57,6 +60,12 @@ def products_for_variant_filtering(product_type, category):category=category,product_type=product_type,),+ Product(+ name="ProductWithPreorder",+ slug="prod5",+ category=category,+ product_type=product_type,+ ),])ProductVariant.objects.bulk_create(@@ -86,6 +95,23 @@ def products_for_variant_filtering(product_type, category):ProductVariant(product=products[5],),+ ProductVariant(+ product=products[6],+ sku="Preorder-V1",+ is_preorder=True,+ ),+ ProductVariant(+ product=products[6],+ sku="Preorder-V2",+ is_preorder=True,+ preorder_end_date=timezone.now() + timedelta(days=1),+ ),+ ProductVariant(+ product=products[6],+ sku="Preorder-V3",+ is_preorder=True,+ preorder_end_date=timezone.now() - timedelta(days=1),+ ),])return products@@ -106,6 +132,21 @@ def products_for_variant_filtering(product_type, category):({"sku": ["P1-V1", "P1-V2", "PP1-V1"]}, ["P1-V1", "P1-V2", "PP1-V1"]),({"sku": ["PP1-V1", "PP2-V1"]}, ["PP1-V1", "PP2-V1"]),({"sku": ["invalid"]}, []),+ ({"isPreorder": True}, ["Preorder-V1", "Preorder-V2"]),+ (+ {"isPreorder": False},+ [+ "P-NO-SKU",+ "P1-V1",+ "P1-V2",+ "P2-V1",+ "P3-V1",+ "PP1-V1",+ "PP2-V1",+ "Preorder-V3",+ None,+ ],+ ),],)def test_products_pagination_with_filtering(@@ -129,6 +170,18 @@ def test_products_pagination_with_filtering(# thencontent = get_graphql_content(response)products_nodes = content["data"]["productVariants"]["edges"]- for index, variant_sku in enumerate(variants):- assert variant_sku == products_nodes[index]["node"]["sku"]- assert len(variants) == len(products_nodes)+ assert sorted([variant for variant in variants if variant is not None]) == sorted(+ [+ product_node["node"]["sku"]+ for product_node in products_nodes+ if product_node["node"]["sku"] is not None+ ]+ )+ if None in variants:+ assert variants.count(None) == len(+ [+ product_node["node"]["sku"]+ for product_node in products_nodes+ if product_node["node"]["sku"] is None+ ]+ )diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex ec19b1c459..547ae49c4d 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -16,6 +16,7 @@ from ....product.utils.costs import (from ...account import types as account_typesfrom ...channel.dataloaders import ChannelByIdLoaderfrom ...core.connection import CountableDjangoObjectType+from ...core.descriptions import ADDED_IN_31from ...decorators import permission_requiredfrom ...discount.dataloaders import DiscountsByDateTimeLoaderfrom ..dataloaders import (@@ -234,9 +235,28 @@ class ProductChannelListing(CountableDjangoObjectType):)+class PreorderThreshold(graphene.ObjectType):+ quantity = graphene.Int(+ required=False,+ description="Preorder threshold for product variant in this channel.",+ )+ sold_units = graphene.Int(+ required=True,+ description="Number of sold product variant in this channel.",+ )++ class Meta:+ description = "Represents preorder variant data for channel."++class ProductVariantChannelListing(CountableDjangoObjectType):cost_price = graphene.Field(Money, description="Cost price of the variant.")margin = graphene.Int(description="Gross margin percentage value.")+ preorder_threshold = graphene.Field(+ PreorderThreshold,+ required=False,+ description=f"{ADDED_IN_31} Preorder variant data.",+ )class Meta:description = "Represents product varaint channel listing."@@ -253,6 +273,17 @@ class ProductVariantChannelListing(CountableDjangoObjectType):def resolve_margin(root: models.ProductVariantChannelListing, *_args):return get_margin_for_variant_channel_listing(root)+ @staticmethod+ def resolve_preorder_threshold(+ root: models.ProductVariantChannelListing, info, **_kwargs+ ):+ # The preorder_quantity_allocated field is added through annotation+ # when using the `resolve_channel_listings` resolver.+ return PreorderThreshold(+ quantity=root.preorder_quantity_threshold,+ sold_units=getattr(root, "preorder_quantity_allocated", 0),+ )+class CollectionChannelListing(CountableDjangoObjectType):class Meta:diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex df7950c135..bef6757083 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -35,7 +35,11 @@ from ...channel.dataloaders import ChannelBySlugLoaderfrom ...channel.types import ChannelContextType, ChannelContextTypeWithMetadatafrom ...channel.utils import get_default_channel_slug_or_graphql_errorfrom ...core.connection import CountableDjangoObjectType-from ...core.descriptions import DEPRECATED_IN_3X_FIELD, DEPRECATED_IN_3X_INPUT+from ...core.descriptions import (+ ADDED_IN_31,+ DEPRECATED_IN_3X_FIELD,+ DEPRECATED_IN_3X_INPUT,+)from ...core.enums import ReportingPeriodfrom ...core.fields import (ChannelContextFilterConnectionField,@@ -177,6 +181,30 @@ class ProductPricingInfo(BasePricingInfo):description = "Represents availability of a product in the storefront."+class PreorderData(graphene.ObjectType):+ global_threshold = graphene.Int(+ required=False, description="The global preorder threshold for product variant."+ )+ global_sold_units = graphene.Int(+ required=True,+ description="Total number of sold product variant during preorder.",+ )+ end_date = graphene.DateTime(required=False, description="Preorder end date.")++ class Meta:+ description = "Represents preorder settings for product variant."++ @staticmethod+ @permission_required(ProductPermissions.MANAGE_PRODUCTS)+ def resolve_global_threshold(root, *_args):+ return root.global_threshold++ @staticmethod+ @permission_required(ProductPermissions.MANAGE_PRODUCTS)+ def resolve_global_sold_units(root, *_args):+ return root.global_sold_units++@key(fields="id channel")class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):channel = graphene.String(@@ -261,6 +289,11 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):),),)+ preorder = graphene.Field(+ PreorderData,+ required=False,+ description=f"{ADDED_IN_31} Preorder data for product variant.",+ )class Meta:default_resolver = ChannelContextType.resolver_with_context@@ -301,6 +334,40 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):if address is not None:country_code = address.country+ if root.node.is_preorder_active():+ variant = root.node+ channel_listing = VariantChannelListingByVariantIdAndChannelSlugLoader(+ info.context+ ).load((variant.id, str(root.channel_slug)))++ def calculate_available_per_channel(channel_listing):+ if channel_listing.preorder_quantity_threshold is not None:+ return min(+ channel_listing.preorder_quantity_threshold+ - channel_listing.preorder_quantity_allocated,+ settings.MAX_CHECKOUT_LINE_QUANTITY,+ )+ if variant.preorder_global_threshold is not None:+ variant_channel_listings = VariantChannelListingByVariantIdLoader(+ info.context+ ).load(variant.id)++ def calculate_available_global(variant_channel_listings):+ global_sold_units = sum(+ channel_listing.preorder_quantity_allocated+ for channel_listing in variant_channel_listings+ )+ return min(+ variant.preorder_global_threshold - global_sold_units,+ settings.MAX_CHECKOUT_LINE_QUANTITY,+ )++ return variant_channel_listings.then(calculate_available_global)++ return settings.MAX_CHECKOUT_LINE_QUANTITY++ return channel_listing.then(calculate_available_per_channel)+if not root.node.track_inventory:return settings.MAX_CHECKOUT_LINE_QUANTITY@@ -519,6 +586,32 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):def resolve_weight(root: ChannelContext[models.ProductVariant], _info, **_kwargs):return convert_weight_to_default_weight_unit(root.node.weight)+ @staticmethod+ @traced_resolver+ def resolve_preorder(root: ChannelContext[models.ProductVariant], _info, **_kwargs):+ variant = root.node++ variant_channel_listings = VariantChannelListingByVariantIdLoader(+ _info.context+ ).load(variant.id)++ def calculate_global_sold_units(variant_channel_listings):+ global_sold_units = sum(+ channel_listing.preorder_quantity_allocated+ for channel_listing in variant_channel_listings+ )+ return (+ PreorderData(+ global_threshold=variant.preorder_global_threshold,+ global_sold_units=global_sold_units,+ end_date=variant.preorder_end_date,+ )+ if variant.is_preorder_active()+ else None+ )++ return variant_channel_listings.then(calculate_global_sold_units)+@key(fields="id channel")class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 64e2f17d00..3510cbb5c6 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -3796,6 +3796,7 @@ type Mutation {productVariantTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): ProductVariantTranslateproductVariantChannelListingUpdate(id: ID!, input: [ProductVariantChannelListingAddInput!]!): ProductVariantChannelListingUpdateproductVariantReorderAttributeValues(attributeId: ID!, moves: [ReorderInput]!, variantId: ID!): ProductVariantReorderAttributeValues+ productVariantPreorderDeactivate(id: ID!): ProductVariantPreorderDeactivatevariantMediaAssign(mediaId: ID!, variantId: ID!): VariantMediaAssignvariantMediaUnassign(mediaId: ID!, variantId: ID!): VariantMediaUnassignpaymentCapture(amount: PositiveDecimal, paymentId: ID!): PaymentCapture@@ -5128,6 +5129,22 @@ enum PostalCodeRuleInclusionTypeEnum {EXCLUDE}+type PreorderData {+ globalThreshold: Int+ globalSoldUnits: Int!+ endDate: DateTime+}++input PreorderSettingsInput {+ globalThreshold: Int+ endDate: DateTime+}++type PreorderThreshold {+ quantity: Int+ soldUnits: Int!+}+input PriceInput {currency: String!amount: PositiveDecimal!@@ -5311,6 +5328,7 @@ enum ProductErrorCode {CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANTPRODUCT_NOT_ASSIGNED_TO_CHANNELUNSUPPORTED_MEDIA_PROVIDER+ PREORDER_VARIANT_CANNOT_BE_DEACTIVATED}enum ProductFieldEnum {@@ -5343,6 +5361,7 @@ input ProductFilterInput {productTypes: [ID]giftCard: Booleanids: [ID]+ hasPreorderedVariants: Booleanchannel: String}@@ -5629,6 +5648,7 @@ type ProductVariant implements Node & ObjectWithMetadata {digitalContent: DigitalContentstocks(address: AddressInput, countryCode: CountryCode): [Stock]quantityAvailable(address: AddressInput, countryCode: CountryCode): Int!+ preorder: PreorderData}type ProductVariantBulkCreate {@@ -5643,6 +5663,7 @@ input ProductVariantBulkCreateInput {sku: StringtrackInventory: Booleanweight: WeightScalar+ preorder: PreorderSettingsInputstocks: [StockInput!]channelListings: [ProductVariantChannelListingAddInput!]}@@ -5659,12 +5680,14 @@ type ProductVariantChannelListing implements Node {price: MoneycostPrice: Moneymargin: Int+ preorderThreshold: PreorderThreshold}input ProductVariantChannelListingAddInput {channelId: ID!price: PositiveDecimal!costPrice: PositiveDecimal+ preorderThreshold: Int}type ProductVariantChannelListingUpdate {@@ -5695,6 +5718,7 @@ input ProductVariantCreateInput {sku: StringtrackInventory: Booleanweight: WeightScalar+ preorder: PreorderSettingsInputproduct: ID!stocks: [StockInput!]}@@ -5709,6 +5733,7 @@ input ProductVariantFilterInput {search: Stringsku: [String]metadata: [MetadataFilter]+ isPreorder: Boolean}input ProductVariantInput {@@ -5716,6 +5741,12 @@ input ProductVariantInput {sku: StringtrackInventory: Booleanweight: WeightScalar+ preorder: PreorderSettingsInput+}++type ProductVariantPreorderDeactivate {+ productVariant: ProductVariant+ errors: [ProductError!]!}type ProductVariantReorder {diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 3c84fa4f69..9cb4191817 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -739,6 +739,7 @@ def create_fulfillments()FulfillmentLine.objects.bulk_create(fulfillment_lines)+ order.refresh_from_db()post_creation_func = (order_fulfilled if approved else order_awaits_fulfillment_approval)diff --git a/saleor/order/notifications.py b/saleor/order/notifications.pyindex ebe000087f..70ff39641a 100644--- a/saleor/order/notifications.py+++ b/saleor/order/notifications.py@@ -82,6 +82,9 @@ def get_product_variant_payload(variant: ProductVariant):return {"id": variant.id,"weight": str(variant.weight or ""),+ "is_preorder": variant.is_preorder_active(),+ "preorder_global_threshold": variant.preorder_global_threshold,+ "preorder_end_date": variant.preorder_end_date,**get_default_images_payload(images),}diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.pyindex 9bc8adaef4..5a6369eab9 100644--- a/saleor/order/tests/test_notifications.py+++ b/saleor/order/tests/test_notifications.py@@ -124,6 +124,9 @@ def test_get_order_line_payload(order_line):"first_image": None,"images": None,"weight": "",+ "is_preorder": False,+ "preorder_global_threshold": None,+ "preorder_end_date": None,},"product": {"attributes": expected_attributes_payload,diff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.pyindex 3e0888d52e..747669d1ca 100644--- a/saleor/product/error_codes.py+++ b/saleor/product/error_codes.py@@ -19,6 +19,7 @@ class ProductErrorCode(Enum):CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT = "cannot_manage_product_without_variant"PRODUCT_NOT_ASSIGNED_TO_CHANNEL = "product_not_assigned_to_channel"UNSUPPORTED_MEDIA_PROVIDER = "unsupported_media_provider"+ PREORDER_VARIANT_CANNOT_BE_DEACTIVATED = "preorder_variant_cannot_be_deactivated"class CollectionErrorCode(Enum):diff --git a/saleor/product/migrations/0150_auto_20211001_1004.py b/saleor/product/migrations/0150_auto_20211001_1004.pynew file mode 100644index 0000000000..5bb3a82443--- /dev/null+++ b/saleor/product/migrations/0150_auto_20211001_1004.py@@ -0,0 +1,33 @@+# Generated by Django 3.2.7 on 2021-10-01 10:04++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0149_alter_productvariant_sku"),+ ]++ operations = [+ migrations.AddField(+ model_name="productvariant",+ name="is_preorder",+ field=models.BooleanField(default=False),+ ),+ migrations.AddField(+ model_name="productvariant",+ name="preorder_end_date",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="productvariant",+ name="preorder_global_threshold",+ field=models.IntegerField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="productvariantchannellisting",+ name="preorder_quantity_threshold",+ field=models.IntegerField(blank=True, null=True),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 0fbef41fe3..5ddd80abaf 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -28,6 +28,7 @@ from django.db.models import ()from django.db.models.functions import Coalescefrom django.urls import reverse+from django.utils import timezonefrom django.utils.encoding import smart_textfrom django_measurement.models import MeasurementFieldfrom django_prices.models import MoneyField@@ -546,6 +547,9 @@ class ProductVariant(SortableModel, ModelWithMetadata):)media = models.ManyToManyField("ProductMedia", through="VariantMedia")track_inventory = models.BooleanField(default=True)+ is_preorder = models.BooleanField(default=False)+ preorder_end_date = models.DateTimeField(null=True, blank=True)+ preorder_global_threshold = models.IntegerField(blank=True, null=True)weight = MeasurementField(measurement=Weight,@@ -613,6 +617,11 @@ class ProductVariant(SortableModel, ModelWithMetadata):def get_ordering_queryset(self):return self.product.variants.all()+ def is_preorder_active(self):+ return self.is_preorder and (+ self.preorder_end_date is None or timezone.now() <= self.preorder_end_date+ )+class ProductVariantTranslation(Translation):product_variant = models.ForeignKey(@@ -644,6 +653,15 @@ class ProductVariantTranslation(Translation):return {"name": self.name}+class ProductVariantChannelListingQuerySet(models.QuerySet):+ def annotate_preorder_quantity_allocated(self):+ return self.annotate(+ preorder_quantity_allocated=Coalesce(+ Sum("preorder_allocations__quantity"), 0+ ),+ )++class ProductVariantChannelListing(models.Model):variant = models.ForeignKey(ProductVariant,@@ -676,6 +694,10 @@ class ProductVariantChannelListing(models.Model):)cost_price = MoneyField(amount_field="cost_price_amount", currency_field="currency")+ preorder_quantity_threshold = models.IntegerField(blank=True, null=True)++ objects = models.Manager.from_queryset(ProductVariantChannelListingQuerySet)()+class Meta:unique_together = [["variant", "channel"]]ordering = ("pk",)diff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex acc2f6163d..68b908e54f 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -1,11 +1,15 @@import loggingfrom typing import Iterable, List, Optional+from celery.utils.log import get_task_loggerfrom django.core.exceptions import ObjectDoesNotExist+from django.utils import timezonefrom ..attribute.models import Attributefrom ..celeryconf import app+from ..core.exceptions import PreorderAllocationErrorfrom ..discount.models import Sale+from ..warehouse.management import deactivate_preorder_for_variantfrom .models import Product, ProductType, ProductVariantfrom .utils.variant_prices import (update_product_discounted_price,@@ -16,6 +20,7 @@ from .utils.variant_prices import (from .utils.variants import generate_and_set_variant_namelogger = logging.getLogger(__name__)+task_logger = get_task_logger(__name__)def _update_variants_names(instance: ProductType, saved_attributes: Iterable):@@ -86,3 +91,20 @@ def update_products_discounted_prices_of_discount_task(discount_pk: int):def update_products_discounted_prices_task(product_ids: List[int]):products = Product.objects.filter(pk__in=product_ids)update_products_discounted_prices(products)+++def deactivate_preorder_for_variants_task():+ variants_to_clean = _get_preorder_variants_to_clean()++ for variant in variants_to_clean:+ try:+ deactivate_preorder_for_variant(variant)+ except PreorderAllocationError as e:+ task_logger.warning(str(e))+++def _get_preorder_variants_to_clean():+ return ProductVariant.objects.filter(+ is_preorder=True, preorder_end_date__lt=timezone.now()+ )diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.pyindex df67b4260f..4a44bda560 100644--- a/saleor/product/tests/test_tasks.py+++ b/saleor/product/tests/test_tasks.py@@ -1,7 +1,11 @@import logging+from datetime import timedeltafrom unittest.mock import patch+from django.utils import timezone+from ..tasks import (+ _get_preorder_variants_to_clean,update_product_discounted_price_task,update_products_discounted_prices_of_discount_task,update_variants_names,@@ -87,3 +91,26 @@ def test_update_variants_names_product_type_does_not_exist(# thenupdate_variants_names_mock.assert_not_called()assert f"Cannot find product type with id: {product_type_id}" in caplog.text+++def test_get_preorder_variants_to_clean(+ variant,+ preorder_variant_global_threshold,+ preorder_variant_channel_threshold,+ preorder_variant_global_and_channel_threshold,+):+ preorder_variant_before_end_date = preorder_variant_channel_threshold+ preorder_variant_before_end_date.preorder_end_date = timezone.now() + timedelta(+ days=1+ )+ preorder_variant_before_end_date.save(update_fields=["preorder_end_date"])++ preorder_variant_after_end_date = preorder_variant_global_and_channel_threshold+ preorder_variant_after_end_date.preorder_end_date = timezone.now() - timedelta(+ days=1+ )+ preorder_variant_after_end_date.save(update_fields=["preorder_end_date"])++ variants_to_clean = _get_preorder_variants_to_clean()+ assert len(variants_to_clean) == 1+ assert variants_to_clean[0] == preorder_variant_after_end_datediff --git a/saleor/settings.py b/saleor/settings.pyindex 730f65ddcf..fa6f41cd43 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -486,6 +486,10 @@ CELERY_BEAT_SCHEDULE = {"task": "saleor.warehouse.tasks.delete_empty_allocations_task","schedule": timedelta(days=1),},+ "deactivate-preorder-for-variants": {+ "task": "saleor.product.tasks.deactivate_preorder_for_variants_task",+ "schedule": timedelta(hours=1),+ },}# Change this value if your application is running behind a proxy,diff --git a/saleor/static/populatedb_data.json b/saleor/static/populatedb_data.jsonindex 8b1df17c6a..64332622ff 100644--- a/saleor/static/populatedb_data.json+++ b/saleor/static/populatedb_data.json@@ -4254,6 +4254,23 @@"default": true}},+ {+ "model": "product.productvariant",+ "pk": 322,+ "fields": {+ "private_metadata": {},+ "metadata": {},+ "sku": "waterfall-ballads-extended-mp3",+ "name": "MP3 Extended",+ "product": 124,+ "track_inventory": true,+ "weight": null,+ "default": true,+ "is_preorder": true,+ "preorder_end_date": null,+ "preorder_global_threshold": 10+ }+ },{"model": "product.productvariantchannellisting","pk": 1,@@ -6663,6 +6680,30 @@"cost_price_amount": null}},+ {+ "model": "product.productvariantchannellisting",+ "pk": 220,+ "fields": {+ "variant": 322,+ "channel": 1,+ "currency": "USD",+ "price_amount": "9.990",+ "cost_price_amount": null,+ "preorder_quantity_threshold": 8+ }+ },+ {+ "model": "product.productvariantchannellisting",+ "pk": 221,+ "fields": {+ "variant": 322,+ "channel": 2,+ "currency": "PLN",+ "price_amount": "20.000",+ "cost_price_amount": null,+ "preorder_quantity_threshold": 2+ }+ },{"model": "attribute.assignedproductattribute","pk": 1,@@ -8533,6 +8574,17 @@]}},+ {+ "model": "attribute.assignedvariantattribute",+ "pk": 135,+ "fields": {+ "variant": 322,+ "assignment": 8,+ "values": [+ 85+ ]+ }+ },{"model": "attribute.assignedpageattribute","pk": 1,diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f47a80f361..d1e66ba864 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -109,7 +109,7 @@ from ..shipping.models import ()from ..site.models import SiteSettingsfrom ..warehouse import WarehouseClickAndCollectOption-from ..warehouse.models import Allocation, Stock, Warehouse+from ..warehouse.models import Allocation, PreorderAllocation, Stock, Warehousefrom ..webhook.event_types import WebhookEventTypefrom ..webhook.models import Webhook, WebhookEventfrom ..wishlist.models import Wishlist@@ -479,6 +479,17 @@ def checkout_with_payments(checkout):return checkout+def checkout_with_item_and_preorder_item(+ checkout_with_item, product, preorder_variant_channel_threshold+):+ checkout_info = fetch_checkout_info(+ checkout_with_item, [], [], get_plugins_manager()+ )+ add_variant_to_checkout(checkout_info, preorder_variant_channel_threshold, 1)+ return checkout_with_item++@pytest.fixturedef address(db): # pylint: disable=W0613return Address.objects.create(@@ -2096,6 +2107,84 @@ def variant_with_many_stocks(variant, warehouses_with_shipping_zone):return variant+def preorder_variant_global_threshold(product, channel_USD):+ product_variant = ProductVariant.objects.create(+ product=product, sku="SKU_A_P", is_preorder=True, preorder_global_threshold=10+ )+ ProductVariantChannelListing.objects.create(+ variant=product_variant,+ channel=channel_USD,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=channel_USD.currency_code,+ )+ return product_variant+++def preorder_variant_channel_threshold(product, channel_USD):+ product_variant = ProductVariant.objects.create(+ product=product, sku="SKU_B_P", is_preorder=True, preorder_global_threshold=None+ )+ ProductVariantChannelListing.objects.create(+ variant=product_variant,+ channel=channel_USD,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=channel_USD.currency_code,+ preorder_quantity_threshold=10,+ )+ return product_variant+++def preorder_variant_global_and_channel_threshold(product, channel_USD, channel_PLN):+ product_variant = ProductVariant.objects.create(+ product=product, sku="SKU_C_P", is_preorder=True, preorder_global_threshold=10+ )+ ProductVariantChannelListing.objects.bulk_create(+ [+ ProductVariantChannelListing(+ variant=product_variant,+ channel=channel_USD,+ cost_price_amount=Decimal(1),+ price_amount=Decimal(10),+ currency=channel_USD.currency_code,+ preorder_quantity_threshold=8,+ ),+ ProductVariantChannelListing(+ variant=product_variant,+ channel=channel_PLN,+ cost_price_amount=Decimal(1),+ price_amount=Decimal(10),+ currency=channel_PLN.currency_code,+ preorder_quantity_threshold=4,+ ),+ ]+ )+ return product_variant+++def preorder_variant_with_end_date(product, channel_USD):+ product_variant = ProductVariant.objects.create(+ product=product,+ sku="SKU_D_P",+ is_preorder=True,+ preorder_global_threshold=10,+ preorder_end_date=timezone.now() + datetime.timedelta(days=10),+ )+ ProductVariantChannelListing.objects.create(+ variant=product_variant,+ channel=channel_USD,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=channel_USD.currency_code,+ )+ return product_variant++@pytest.fixturedef variant_with_many_stocks_different_shipping_zones(variant, warehouses_with_different_shipping_zone@@ -3303,6 +3392,78 @@ def order_with_line_without_inventory_tracking(return order+def order_with_preorder_lines(+ order, product_type, category, shipping_zone, warehouse, channel_USD+):+ product = Product.objects.create(+ name="Test product",+ slug="test-product-8",+ product_type=product_type,+ category=category,+ )+ ProductChannelListing.objects.create(+ product=product,+ channel=channel_USD,+ is_published=True,+ visible_in_listings=True,+ available_for_purchase=datetime.date.today(),+ )+ variant = ProductVariant.objects.create(+ product=product, sku="SKU_AA_P", is_preorder=True+ )+ channel_listing = ProductVariantChannelListing.objects.create(+ variant=variant,+ channel=channel_USD,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=channel_USD.currency_code,+ preorder_quantity_threshold=10,+ )++ net = variant.get_price(product, [], channel_USD, channel_listing)+ currency = net.currency+ gross = Money(amount=net.amount * Decimal(1.23), currency=currency)+ quantity = 3+ unit_price = TaxedMoney(net=net, gross=gross)+ line = order.lines.create(+ product_name=str(variant.product),+ variant_name=str(variant),+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ is_gift_card=variant.is_gift_card(),+ quantity=quantity,+ variant=variant,+ unit_price=unit_price,+ total_price=unit_price * quantity,+ undiscounted_unit_price=unit_price,+ undiscounted_total_price=unit_price * quantity,+ tax_rate=Decimal("0.23"),+ )+ PreorderAllocation.objects.create(+ order_line=line,+ product_variant_channel_listing=channel_listing,+ quantity=line.quantity,+ )++ order.shipping_address = order.billing_address.get_copy()+ order.channel = channel_USD+ shipping_method = shipping_zone.shipping_methods.first()+ shipping_price = shipping_method.channel_listings.get(channel_id=channel_USD.id)+ order.shipping_method_name = shipping_method.name+ order.shipping_method = shipping_method++ net = shipping_price.get_total()+ gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)+ order.shipping_price = TaxedMoney(net=net, gross=gross)+ order.save()++ recalculate_order(order)++ order.refresh_from_db()+ return order++@pytest.fixturedef order_events(order):for event_type, _ in OrderEvents.CHOICES:@@ -3440,6 +3601,17 @@ def draft_order_without_inventory_tracking(order_with_line_without_inventory_trareturn order_with_line_without_inventory_tracking+def draft_order_with_preorder_lines(order_with_preorder_lines):+ PreorderAllocation.objects.filter(+ order_line__order=order_with_preorder_lines+ ).delete()+ order_with_preorder_lines.status = OrderStatus.DRAFT+ order_with_preorder_lines.origin = OrderOrigin.DRAFT+ order_with_preorder_lines.save(update_fields=["status", "origin"])+ return order_with_preorder_lines++@pytest.fixturedef payment_txn_preauth(order_with_lines, payment_dummy):order = order_with_lines@@ -4849,6 +5021,19 @@ def allocations(order_list, stock, channel_USD):)+def preorder_allocation(+ order_line, preorder_variant_global_and_channel_threshold, channel_PLN+):+ variant = preorder_variant_global_and_channel_threshold+ product_variant_channel_listing = variant.channel_listings.get(channel=channel_PLN)+ return PreorderAllocation.objects.create(+ order_line=order_line,+ product_variant_channel_listing=product_variant_channel_listing,+ quantity=order_line.quantity,+ )++@pytest.fixturedef app_installation():app_installation = AppInstallation.objects.create(diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex e1abe80693..6f2830bf3a 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -1,10 +1,11 @@from collections import defaultdict-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple-from django.db.models import Sum+from django.db.models import F, Sumfrom django.db.models.functions import Coalescefrom ..core.exceptions import InsufficientStock, InsufficientStockData+from ..product.models import ProductVariantChannelListingfrom .models import Stock, StockQuerySetif TYPE_CHECKING:@@ -22,6 +23,20 @@ def _get_available_quantity(stocks: StockQuerySet) -> int:return max(total_quantity - quantity_allocated, 0)+def check_stock_and_preorder_quantity(+ variant: "ProductVariant", country_code: str, channel_slug: str, quantity: int+):+ """Validate if there is stock/preorder available for given variant.++ :raises InsufficientStock: when there is not enough items in stock for a variant+ or there is not enough available preorder items for a variant.+ """+ if variant.is_preorder_active():+ check_preorder_threshold_bulk([variant], [quantity], channel_slug)+ else:+ check_stock_quantity(variant, country_code, channel_slug, quantity)++def check_stock_quantity(variant: "ProductVariant", country_code: str, channel_slug: str, quantity: int):@@ -41,6 +56,66 @@ def check_stock_quantity(raise InsufficientStock([InsufficientStockData(variant=variant)])+def check_stock_and_preorder_quantity_bulk(+ variants: Iterable["ProductVariant"],+ country_code: str,+ quantities: Iterable[int],+ channel_slug: str,+ additional_filter_lookup: Optional[Dict[str, Any]] = None,+ existing_lines: Iterable = None,+ replace: bool = False,+):+ """Validate if products are available for stocks/preorder.++ :raises InsufficientStock: when there is not enough items in stock for a variant+ or there is not enough available preorder items for a variant.+ """+ (+ stock_variants,+ stock_quantities,+ preorder_variants,+ preorder_quantities,+ ) = _split_lines_for_trackable_and_preorder(variants, quantities)+ if stock_variants:+ check_stock_quantity_bulk(+ stock_variants,+ country_code,+ stock_quantities,+ channel_slug,+ additional_filter_lookup,+ existing_lines,+ replace,+ )+ if preorder_variants:+ check_preorder_threshold_bulk(+ preorder_variants, preorder_quantities, channel_slug+ )+++def _split_lines_for_trackable_and_preorder(+ variants: Iterable["ProductVariant"], quantities: Iterable[int]+) -> Tuple[+ Iterable["ProductVariant"], Iterable[int], Iterable["ProductVariant"], Iterable[int]+]:+ """Return variants and quantities splitted by "is_preorder_active"."""+ stock_variants, stock_quantities = [], []+ preorder_variants, preorder_quantities = [], []++ for variant, quantity in zip(variants, quantities):+ if variant.is_preorder_active():+ preorder_variants.append(variant)+ preorder_quantities.append(quantity)+ else:+ stock_variants.append(variant)+ stock_quantities.append(quantity)+ return (+ stock_variants,+ stock_quantities,+ preorder_variants,+ preorder_quantities,+ )++def check_stock_quantity_bulk(variants: Iterable["ProductVariant"],country_code: str,@@ -98,3 +173,70 @@ def check_stock_quantity_bulk(if insufficient_stocks:raise InsufficientStock(insufficient_stocks)+++def check_preorder_threshold_bulk(+ variants: Iterable["ProductVariant"],+ quantities: Iterable[int],+ channel_slug: str,+):+ """Validate if there is enough preordered variants according to thresholds.++ :raises InsufficientStock: when there is not enough available items for a variant.+ """+ all_variants_channel_listings = (+ ProductVariantChannelListing.objects.filter(variant__in=variants)+ .annotate_preorder_quantity_allocated()+ .annotate(+ available_preorder_quantity=F("preorder_quantity_threshold")+ - Coalesce(Sum("preorder_allocations__quantity"), 0),+ )+ .select_related("channel")+ )+ variants_channel_availability = {+ channel_listing.variant_id: (+ channel_listing.available_preorder_quantity,+ channel_listing.preorder_quantity_threshold,+ )+ for channel_listing in all_variants_channel_listings+ if channel_listing.channel.slug == channel_slug+ }++ variant_channels: Dict[int, List[ProductVariantChannelListing]] = defaultdict(list)+ for channel_listing in all_variants_channel_listings:+ variant_channels[channel_listing.variant_id].append(channel_listing)++ variants_global_allocations = {+ variant_id: sum(+ channel_listing.preorder_quantity_allocated # type: ignore+ for channel_listing in channel_listings+ )+ for variant_id, channel_listings in variant_channels.items()+ }++ insufficient_stocks: List[InsufficientStockData] = []+ for variant, quantity in zip(variants, quantities):+ if variants_channel_availability[variant.id][1] is not None:+ if quantity > variants_channel_availability[variant.id][0]:+ insufficient_stocks.append(+ InsufficientStockData(+ variant=variant,+ available_quantity=variants_channel_availability[variant.id][0],+ )+ )++ if variant.preorder_global_threshold is not None:+ global_availability = (+ variant.preorder_global_threshold+ - variants_global_allocations[variant.id]+ )+ if quantity > global_availability:+ insufficient_stocks.append(+ InsufficientStockData(+ variant=variant,+ available_quantity=global_availability,+ )+ )++ if insufficient_stocks:+ raise InsufficientStock(insufficient_stocks)diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 862671fc04..4e084fc9c5 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -1,15 +1,20 @@from collections import defaultdict, namedtuple-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, cast+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, castfrom django.db import transactionfrom django.db.models import F, Sum-from ..core.exceptions import AllocationError, InsufficientStock, InsufficientStockData+from ..core.exceptions import (+ AllocationError,+ InsufficientStock,+ InsufficientStockData,+ PreorderAllocationError,+)from ..core.tracing import traced_atomic_transactionfrom ..order import OrderLineDatafrom ..plugins.manager import PluginsManager-from ..product.models import ProductVariant-from .models import Allocation, Stock, Warehouse+from ..product.models import ProductVariant, ProductVariantChannelListing+from .models import Allocation, PreorderAllocation, Stock, Warehouseif TYPE_CHECKING:from ..order.models import Order, OrderLine@@ -428,7 +433,9 @@ def get_order_lines_with_track_inventory(return [line_infofor line_info in order_lines_info- if line_info.variant and line_info.variant.track_inventory+ if line_info.variant+ and line_info.variant.track_inventory+ and not line_info.variant.is_preorder_active()]@@ -446,3 +453,217 @@ def deallocate_stock_for_order(order: "Order", manager: PluginsManager):)allocations.update(quantity_allocated=0)+++@traced_atomic_transaction()+def allocate_preorders(order_lines_info: Iterable["OrderLineData"], channel_slug: str):+ """Allocate preorder variant for given `order_lines` in given channel."""+ order_lines_info = get_order_lines_with_preorder(order_lines_info)+ if not order_lines_info:+ return++ variants = [line_info.variant for line_info in order_lines_info]++ all_variants_channel_listings = (+ ProductVariantChannelListing.objects.filter(variant__in=variants)+ .select_for_update(of=("self",))+ .select_related("channel")+ .values("id", "channel__slug", "preorder_quantity_threshold", "variant_id")+ )+ all_variants_channel_listings_id = (+ channel_listing["id"] for channel_listing in all_variants_channel_listings+ )++ quantity_allocation_list = list(+ PreorderAllocation.objects.filter(+ product_variant_channel_listing_id__in=all_variants_channel_listings_id, # noqa: E501+ quantity__gt=0,+ )+ .values("product_variant_channel_listing")+ .annotate(preorder_quantity_allocated=Sum("quantity"))+ )+ quantity_allocation_for_channel: Dict = defaultdict(int)+ for allocation in quantity_allocation_list:+ quantity_allocation_for_channel[+ allocation["product_variant_channel_listing"]+ ] = allocation["preorder_quantity_allocated"]++ variants_to_channel_listings = {+ channel_listing["variant_id"]: (+ channel_listing["id"],+ channel_listing["preorder_quantity_threshold"],+ )+ for channel_listing in all_variants_channel_listings+ if channel_listing["channel__slug"] == channel_slug+ }++ variants_global_allocations: Dict[int, int] = defaultdict(int)+ for channel_listing in all_variants_channel_listings:+ variants_global_allocations[+ channel_listing["variant_id"]+ ] += quantity_allocation_for_channel[channel_listing["id"]]++ insufficient_stocks: List[InsufficientStockData] = []+ allocations: List[PreorderAllocation] = []+ for line_info in order_lines_info:+ variant = cast(ProductVariant, line_info.variant)+ allocation_item, insufficient_stock = _create_preorder_allocation(+ line_info,+ variants_to_channel_listings[variant.id],+ variants_global_allocations[variant.id],+ quantity_allocation_for_channel,+ )+ if allocation_item:+ allocations.append(allocation_item)+ if insufficient_stock:+ insufficient_stocks.append(insufficient_stock)++ if insufficient_stocks:+ raise InsufficientStock(insufficient_stocks)++ if allocations:+ PreorderAllocation.objects.bulk_create(allocations)+++def get_order_lines_with_preorder(+ order_lines_info: Iterable["OrderLineData"],+) -> Iterable["OrderLineData"]:+ """Return order lines with variants with preorder flag set to True."""+ return [+ line_info+ for line_info in order_lines_info+ if line_info.variant and line_info.variant.is_preorder_active()+ ]+++def _create_preorder_allocation(+ line_info: "OrderLineData",+ variant_channel_data: Tuple[int, Optional[int]],+ variant_global_allocation: int,+ quantity_allocation_for_channel: Dict[int, int],+) -> Tuple[Optional[PreorderAllocation], Optional[InsufficientStockData]]:+ variant = cast(ProductVariant, line_info.variant)+ quantity = line_info.quantity+ channel_listing_id, channel_quantity_threshold = variant_channel_data++ if channel_quantity_threshold is not None:+ channel_availability = (+ channel_quantity_threshold+ - quantity_allocation_for_channel[channel_listing_id]+ )+ if quantity > channel_availability:+ return None, InsufficientStockData(+ variant=variant,+ available_quantity=channel_availability,+ )++ if variant.preorder_global_threshold is not None:+ global_availability = (+ variant.preorder_global_threshold - variant_global_allocation+ )+ if quantity > global_availability:+ return None, InsufficientStockData(+ variant=variant, available_quantity=global_availability+ )++ return (+ PreorderAllocation(+ order_line=line_info.line,+ product_variant_channel_listing_id=channel_listing_id,+ quantity=quantity,+ ),+ None,+ )+++@traced_atomic_transaction()+def deactivate_preorder_for_variant(product_variant: ProductVariant):+ """Complete preorder for product variant.++ All preorder settings should be cleared and all preorder allocations+ should be replaced by regular allocations.+ """+ if not product_variant.is_preorder:+ return+ channel_listings = ProductVariantChannelListing.objects.filter(+ variant_id=product_variant.pk+ )+ channel_listings_pk = (channel_listing.id for channel_listing in channel_listings)+ preorder_allocations = PreorderAllocation.objects.filter(+ product_variant_channel_listing_id__in=channel_listings_pk+ ).select_related("order_line", "order_line__order")++ allocations_to_create = []+ stocks_to_create = []+ for preorder_allocation in preorder_allocations:+ stock = _get_stock_for_preorder_allocation(preorder_allocation, product_variant)+ if stock._state.adding:+ stocks_to_create.append(stock)+ allocations_to_create.append(+ Allocation(+ order_line=preorder_allocation.order_line,+ stock=stock,+ quantity_allocated=preorder_allocation.quantity,+ )+ )++ if stocks_to_create:+ Stock.objects.bulk_create(stocks_to_create)++ if allocations_to_create:+ Allocation.objects.bulk_create(allocations_to_create)++ if preorder_allocations:+ preorder_allocations.delete()++ product_variant.preorder_global_threshold = None+ product_variant.preorder_end_date = None+ product_variant.is_preorder = False+ product_variant.save(+ update_fields=["preorder_global_threshold", "preorder_end_date", "is_preorder"]+ )++ ProductVariantChannelListing.objects.filter(variant_id=product_variant.pk).update(+ preorder_quantity_threshold=None+ )+++def _get_stock_for_preorder_allocation(+ preorder_allocation: PreorderAllocation, product_variant: ProductVariant+) -> Stock:+ """Return stock where preordered variant should be allocated.++ By default this function uses any warehouse from the shipping zone that matches+ order's shipping method. If order has no shipping method set, it uses any warehouse+ that matches order's country. Function returns existing stock for selected warehouse+ or creates a new one unsaved `Stock` instance. Function raises an error if there is+ no warehouse assigned to any shipping zone handles order's country.+ """+ order = preorder_allocation.order_line.order+ shipping_method_id = order.shipping_method_id+ if shipping_method_id is not None:+ warehouse = Warehouse.objects.filter(+ shipping_zones__id=order.shipping_method.shipping_zone_id # type: ignore+ ).first()+ else:+ from ..order.utils import get_order_country++ country = get_order_country(order)+ warehouse = Warehouse.objects.filter(+ shipping_zones__countries__contains=country+ ).first()++ if not warehouse:+ raise PreorderAllocationError(preorder_allocation.order_line)++ stock = list(+ (+ Stock.objects.select_for_update(of=("self",)).filter(+ warehouse=warehouse, product_variant=product_variant+ )+ )+ )++ return (stock[0] if stock else None) or Stock(+ warehouse=warehouse, product_variant=product_variant, quantity=0+ )diff --git a/saleor/warehouse/migrations/0017_preorderallocation.py b/saleor/warehouse/migrations/0017_preorderallocation.pynew file mode 100644index 0000000000..6150be39b3--- /dev/null+++ b/saleor/warehouse/migrations/0017_preorderallocation.py@@ -0,0 +1,51 @@+# Generated by Django 3.2.7 on 2021-10-01 10:04++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0150_auto_20211001_1004"),+ ("order", "0120_orderline_optional_sku"),+ ("warehouse", "0016_merge_20210921_1036"),+ ]++ operations = [+ migrations.CreateModel(+ name="PreorderAllocation",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("quantity", models.PositiveIntegerField(default=0)),+ (+ "order_line",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="preorder_allocations",+ to="order.orderline",+ ),+ ),+ (+ "product_variant_channel_listing",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="preorder_allocations",+ to="product.productvariantchannellisting",+ ),+ ),+ ],+ options={+ "ordering": ("pk",),+ "unique_together": {("order_line", "product_variant_channel_listing")},+ },+ ),+ ]diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 40fa7d9d6e..d7dfb01b03 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -13,7 +13,7 @@ from ..channel.models import Channelfrom ..checkout.models import CheckoutLinefrom ..core.models import ModelWithMetadatafrom ..order.models import OrderLine-from ..product.models import Product, ProductVariant+from ..product.models import Product, ProductVariant, ProductVariantChannelListingfrom ..shipping.models import ShippingZonefrom . import WarehouseClickAndCollectOption@@ -258,3 +258,25 @@ class Allocation(models.Model):class Meta:unique_together = [["order_line", "stock"]]ordering = ("pk",)+++class PreorderAllocation(models.Model):+ order_line = models.ForeignKey(+ OrderLine,+ null=False,+ blank=False,+ on_delete=models.CASCADE,+ related_name="preorder_allocations",+ )+ quantity = models.PositiveIntegerField(default=0)+ product_variant_channel_listing = models.ForeignKey(+ ProductVariantChannelListing,+ null=False,+ blank=False,+ on_delete=models.CASCADE,+ related_name="preorder_allocations",+ )++ class Meta:+ unique_together = [["order_line", "product_variant_channel_listing"]]+ ordering = ("pk",)diff --git a/saleor/warehouse/tests/test_preorder_availability.py b/saleor/warehouse/tests/test_preorder_availability.pynew file mode 100644index 0000000000..f2585c0b6d--- /dev/null+++ b/saleor/warehouse/tests/test_preorder_availability.py@@ -0,0 +1,181 @@+from datetime import timedelta+from unittest.mock import patch++import pytest+from django.db.models import F, Sum+from django.db.models.functions import Coalesce+from freezegun import freeze_time++from ...core.exceptions import InsufficientStock+from ..availability import (+ check_preorder_threshold_bulk,+ check_stock_and_preorder_quantity,+ check_stock_and_preorder_quantity_bulk,+)+++@patch("saleor.warehouse.availability.check_preorder_threshold_bulk")+@patch("saleor.warehouse.availability.check_stock_quantity")+def test_check_stock_and_preorder_quantity(+ mock_check_stock_quantity,+ mock_check_preorder_threshold_bulk,+ variant,+ preorder_variant_channel_threshold,+ channel_USD,+):+ check_stock_and_preorder_quantity(variant, "US", channel_USD.slug, 1)+ mock_check_stock_quantity.assert_called_once()++ check_stock_and_preorder_quantity(+ preorder_variant_channel_threshold, "US", channel_USD.slug, 1+ )+ mock_check_preorder_threshold_bulk.assert_called_once()+ assert mock_check_preorder_threshold_bulk.call_args[0][0] == [+ preorder_variant_channel_threshold+ ]+ assert mock_check_preorder_threshold_bulk.call_args[0][1] == [1]+++@patch("saleor.warehouse.availability.check_preorder_threshold_bulk")+@patch("saleor.warehouse.availability.check_stock_quantity_bulk")+def test_check_stock_and_preorder_quantity_bulk(+ mock_check_stock_quantity_bulk,+ mock_check_preorder_threshold_bulk,+ variant,+ preorder_variant_channel_threshold,+ preorder_variant_with_end_date,+ channel_USD,+):+ stock_variant_quantity = 2+ preorder_quantity = 1++ with freeze_time(+ preorder_variant_with_end_date.preorder_end_date + timedelta(days=3)+ ):+ check_stock_and_preorder_quantity_bulk(+ [+ variant,+ preorder_variant_channel_threshold,+ preorder_variant_with_end_date,+ ],+ "US",+ [stock_variant_quantity, preorder_quantity, stock_variant_quantity],+ channel_USD.slug,+ )++ mock_check_stock_quantity_bulk.assert_called_once()+ assert mock_check_stock_quantity_bulk.call_args[0][0] == [+ variant,+ preorder_variant_with_end_date,+ ]+ assert mock_check_stock_quantity_bulk.call_args[0][2] == [+ stock_variant_quantity,+ stock_variant_quantity,+ ]++ mock_check_preorder_threshold_bulk.assert_called_once()+ assert mock_check_preorder_threshold_bulk.call_args[0][0] == [+ preorder_variant_channel_threshold+ ]+ assert mock_check_preorder_threshold_bulk.call_args[0][1] == [preorder_quantity]+++def test_check_preorder_threshold_bulk_channel_threshold(+ preorder_variant_channel_threshold, channel_USD+):++ variant = preorder_variant_channel_threshold+ # test it doesn't raise an error for available preorder variant+ channel_listings = variant.channel_listings.all()+ available_preorder_quantity = channel_listings.annotate(+ available_preorder_quantity=F("preorder_quantity_threshold")+ - Coalesce(Sum("preorder_allocations__quantity"), 0)+ )[0].available_preorder_quantity+ assert (+ check_preorder_threshold_bulk(+ [variant], [available_preorder_quantity], channel_USD.slug+ )+ is None+ )++ # test if it raises error for exceeded quantity+ with pytest.raises(InsufficientStock):+ check_preorder_threshold_bulk(+ [variant], [available_preorder_quantity + 1], channel_USD.slug+ )+++def test_check_preorder_threshold_bulk_global_threshold(+ preorder_variant_global_threshold, channel_USD+):+ variant = preorder_variant_global_threshold+ channel_listings = variant.channel_listings.all()+ global_allocation = sum(+ channel_listings.annotate(+ allocated_preorder_quantity=Coalesce(+ Sum("preorder_allocations__quantity"), 0+ )+ ).values_list("allocated_preorder_quantity", flat=True)+ )+ available_preorder_quantity = variant.preorder_global_threshold - global_allocation++ # test it doesn't raise an error for available preorder variant+ assert (+ check_preorder_threshold_bulk(+ [variant], [available_preorder_quantity], channel_USD.slug+ )+ is None+ )++ # test if it raises error for exceeded quantity+ with pytest.raises(InsufficientStock):+ check_preorder_threshold_bulk(+ [variant], [available_preorder_quantity + 1], channel_USD.slug+ )+++def test_check_preorder_threshold_bulk_global_and_channel_threshold(+ preorder_variant_global_and_channel_threshold,+ preorder_allocation,+ channel_USD,+ channel_PLN,+):+ variant = preorder_variant_global_and_channel_threshold++ channel_listings = variant.channel_listings.all()+ channel_listings = channel_listings.annotate_preorder_quantity_allocated()+ channel_listing_USD = channel_listings.get(channel=channel_USD)+ channel_listing_PLN = channel_listings.get(channel=channel_PLN)++ assert (+ channel_listing_PLN.preorder_quantity_threshold+ - channel_listing_PLN.preorder_quantity_allocated+ < channel_listing_PLN.preorder_quantity_threshold+ )+ # Global availability is smaller than the channel_USD availability+ global_availability = variant.preorder_global_threshold - sum(+ channel_listing.preorder_quantity_allocated+ for channel_listing in channel_listings+ )+ channel_listing_USD_availability = (+ channel_listing_USD.preorder_quantity_threshold+ - channel_listing_USD.preorder_quantity_allocated+ )+ assert global_availability < channel_listing_USD_availability++ # test it doesn't raise any error if global limit is not exceeded+ assert (+ check_preorder_threshold_bulk(+ [variant], [global_availability], channel_USD.slug+ )+ is None+ )++ # test if it raises error due to global limit check+ # although it's available for this specific channel+ with pytest.raises(InsufficientStock):+ check_preorder_threshold_bulk(+ [variant],+ [channel_listing_USD_availability],+ channel_USD.slug,+ )diff --git a/saleor/warehouse/tests/test_preorder_complete.py b/saleor/warehouse/tests/test_preorder_complete.pynew file mode 100644index 0000000000..000f92886f--- /dev/null+++ b/saleor/warehouse/tests/test_preorder_complete.py@@ -0,0 +1,131 @@+from ...product.models import ProductVariantChannelListing+from ..management import deactivate_preorder_for_variant+from ..models import Allocation, PreorderAllocation, Stock+++def test_deactivate_preorder_for_variant(+ preorder_variant_global_and_channel_threshold,+ preorder_allocation,+ shipping_method_channel_PLN,+):+ variant = preorder_variant_global_and_channel_threshold+ order = preorder_allocation.order_line.order+ order.shipping_method = shipping_method_channel_PLN+ order.save(update_fields=["shipping_method"])++ channel_listings_id = ProductVariantChannelListing.objects.filter(+ variant_id=variant.pk+ ).values_list("id", flat=True)+ preorder_allocations_before = PreorderAllocation.objects.filter(+ product_variant_channel_listing_id__in=channel_listings_id+ ).count()+ assert preorder_allocations_before > 0++ allocations_before = Allocation.objects.filter(+ stock__product_variant_id=variant.pk+ ).count()+ # Allocations and stocks will be created+ assert variant.stocks.count() == 0++ deactivate_preorder_for_variant(variant)++ assert (+ PreorderAllocation.objects.filter(+ product_variant_channel_listing_id__in=channel_listings_id+ ).count()+ == 0+ )+ assert (+ Allocation.objects.filter(stock__product_variant_id=variant.pk).count()+ == allocations_before + preorder_allocations_before+ )++ variant.refresh_from_db()++ assert variant.is_preorder is False+ assert variant.preorder_global_threshold is None+ assert variant.preorder_end_date is None++ channel_listings = ProductVariantChannelListing.objects.filter(+ variant_id=variant.pk+ )+ for channel_listing in channel_listings:+ assert channel_listing.preorder_quantity_threshold is None+++def test_deactivate_preorder_for_variant_order_without_shipping_method(+ preorder_variant_global_and_channel_threshold,+ preorder_allocation,+):+ """When order has no shiping method set,+ use warehouse based on country from address."""+ variant = preorder_variant_global_and_channel_threshold+ order = preorder_allocation.order_line.order+ assert order.shipping_method is None++ channel_listings_id = ProductVariantChannelListing.objects.filter(+ variant_id=variant.pk+ ).values_list("id", flat=True)+ preorder_allocations_before = PreorderAllocation.objects.filter(+ product_variant_channel_listing_id__in=channel_listings_id+ ).count()+ assert preorder_allocations_before > 0++ allocations_before = Allocation.objects.filter(+ stock__product_variant_id=variant.pk+ ).count()++ deactivate_preorder_for_variant(variant)++ assert (+ PreorderAllocation.objects.filter(+ product_variant_channel_listing_id__in=channel_listings_id+ ).count()+ == 0+ )+ assert (+ Allocation.objects.filter(stock__product_variant_id=variant.pk).count()+ == allocations_before + preorder_allocations_before+ )+++def test_deactivate_preorder_for_variant_existing_stock(+ preorder_variant_global_and_channel_threshold,+ preorder_allocation,+ shipping_method_channel_PLN,+ warehouse,+):+ variant = preorder_variant_global_and_channel_threshold+ order = preorder_allocation.order_line.order+ order.shipping_method = shipping_method_channel_PLN+ order.save(update_fields=["shipping_method"])++ Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=0)++ channel_listings_id = ProductVariantChannelListing.objects.filter(+ variant_id=variant.pk+ ).values_list("id", flat=True)+ preorder_allocations_before = PreorderAllocation.objects.filter(+ product_variant_channel_listing_id__in=channel_listings_id+ ).count()+ assert preorder_allocations_before > 0++ allocations_before = Allocation.objects.filter(+ stock__product_variant_id=variant.pk+ ).count()++ # Existing stock will be used+ assert variant.stocks.count() > 0++ deactivate_preorder_for_variant(variant)++ assert (+ PreorderAllocation.objects.filter(+ product_variant_channel_listing_id__in=channel_listings_id+ ).count()+ == 0+ )+ assert (+ Allocation.objects.filter(stock__product_variant_id=variant.pk).count()+ == allocations_before + preorder_allocations_before+ )diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.pyindex 3ac5f15f22..5fc67f1788 100644--- a/saleor/warehouse/tests/test_stock_management.py+++ b/saleor/warehouse/tests/test_stock_management.py@@ -11,6 +11,7 @@ from ...plugins.manager import get_plugins_managerfrom ...tests.utils import flush_post_commit_hooksfrom ...warehouse.models import Stockfrom ..management import (+ allocate_preorders,allocate_stocks,deallocate_stock,deallocate_stock_for_order,@@ -18,7 +19,7 @@ from ..management import (increase_allocations,increase_stock,)-from ..models import Allocation+from ..models import Allocation, PreorderAllocationCOUNTRY_CODE = "US"@@ -719,3 +720,100 @@ def test_decrease_stock_with_out_of_stock_webhook_triggered(flush_post_commit_hooks()product_variant_out_of_stock_webhook_mock.assert_called_once()+++def test_allocate_preorders(+ order_line, preorder_variant_channel_threshold, channel_USD+):+ variant = preorder_variant_channel_threshold+ channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)+ channel_listing.preorder_quantity_threshold = 100+ channel_listing.save(update_fields=["preorder_quantity_threshold"])++ line_data = OrderLineData(line=order_line, variant=variant, quantity=50)++ allocate_preorders([line_data], channel_USD.slug)++ channel_listing.refresh_from_db()+ assert channel_listing.preorder_quantity_threshold == 100+ allocation = PreorderAllocation.objects.get(+ order_line=order_line,+ product_variant_channel_listing=channel_listing,+ )+ assert allocation.quantity == 50+++def test_allocate_preorders_with_allocation(+ order_line,+ preorder_variant_global_and_channel_threshold,+ preorder_allocation,+ channel_USD,+):+ variant = preorder_variant_global_and_channel_threshold+ channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)+ channel_listing.preorder_quantity_threshold = 10+ channel_listing.save(update_fields=["preorder_quantity_threshold"])++ quantity_to_allocate = 2+ line_data = OrderLineData(+ line=order_line, variant=variant, quantity=quantity_to_allocate+ )++ allocate_preorders([line_data], channel_USD.slug)++ channel_listing.refresh_from_db()+ assert channel_listing.preorder_quantity_threshold == 10+ allocation = PreorderAllocation.objects.get(+ order_line=order_line,+ product_variant_channel_listing=channel_listing,+ )+ assert allocation.quantity == quantity_to_allocate+++def test_allocate_preorders_insufficient_stocks_channel_threshold(+ order_line, preorder_variant_channel_threshold, channel_USD+):+ variant = preorder_variant_channel_threshold+ channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)+ channel_listings = variant.channel_listings.all()++ line_data = OrderLineData(+ line=order_line,+ variant=variant,+ quantity=channel_listing.preorder_quantity_threshold + 1,+ )+ with pytest.raises(InsufficientStock):+ allocate_preorders([line_data], channel_USD.slug)++ assert not PreorderAllocation.objects.filter(+ order_line=order_line,+ product_variant_channel_listing__in=channel_listings,+ ).exists()+++def test_allocate_preorders_insufficient_stocks_global_threshold(+ order_line, preorder_variant_global_threshold, channel_USD+):+ variant = preorder_variant_global_threshold+ channel_listings = variant.channel_listings.all()+ global_allocation = sum(+ channel_listings.annotate(+ allocated_preorder_quantity=Coalesce(+ Sum("preorder_allocations__quantity"), 0+ )+ ).values_list("allocated_preorder_quantity", flat=True)+ )+ available_preorder_quantity = variant.preorder_global_threshold - global_allocation++ line_data = OrderLineData(+ line=order_line,+ variant=variant,+ quantity=available_preorder_quantity + 1,+ )+ with pytest.raises(InsufficientStock):+ allocate_preorders([line_data], channel_USD.slug)++ assert not PreorderAllocation.objects.filter(+ order_line=order_line,+ product_variant_channel_listing__in=channel_listings,+ ).exists()