Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Click and collect (#7673)
Paweł Kucharskid9c6071cb730
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ff31f4e822..655074171a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,8 @@ All notable, unreleased changes to this project will be documented in this file.# 3.1.0 [Unreleased]- Extend app by `AppExtension` - #7701 by @korycins+- Add Click&Collect feature - #7673 by @kuchichan+# 3.0.0 [Unreleased]- Extend editorjs validator to accept blocks different than text - #SALEOR-3354 by @mociepkadiff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.pyindex 596f96e4e8..f438352bd1 100644--- a/saleor/checkout/base_calculations.py+++ b/saleor/checkout/base_calculations.py@@ -12,7 +12,7 @@ from prices import TaxedMoneyfrom ..core.prices import quantize_pricefrom ..core.taxes import zero_taxed_moneyfrom ..discount import DiscountInfo-from .fetch import CheckoutLineInfo+from .fetch import CheckoutLineInfo, ShippingMethodInfoif TYPE_CHECKING:from ..channel.models import Channel@@ -22,10 +22,23 @@ if TYPE_CHECKING:def base_checkout_shipping_price(checkout_info: "CheckoutInfo", lines=None+) -> TaxedMoney:+ delivery_method_info = checkout_info.delivery_method_info++ if isinstance(delivery_method_info, ShippingMethodInfo):+ return calculate_price_for_shipping_method(+ checkout_info, delivery_method_info, lines+ )++ return zero_taxed_money(checkout_info.checkout.currency)+++def calculate_price_for_shipping_method(+ checkout_info: "CheckoutInfo", shipping_method_info: ShippingMethodInfo, lines=None) -> TaxedMoney:"""Return checkout shipping price."""# FIXME: Optimize checkout.is_shipping_required- shipping_method = checkout_info.shipping_method+ shipping_method = shipping_method_info.delivery_methodif lines is not None and all(isinstance(line, CheckoutLineInfo) for line in lines):from .utils import is_shipping_requireddiff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.pyindex ff68153870..b7bfeaf0aa 100644--- a/saleor/checkout/checkout_cleaner.py+++ b/saleor/checkout/checkout_cleaner.py@@ -8,7 +8,7 @@ from ..payment import models as payment_modelsfrom ..payment.error_codes import PaymentErrorCodefrom ..plugins.manager import PluginsManagerfrom .error_codes import CheckoutErrorCode-from .utils import is_fully_paid, is_shipping_required, is_valid_shipping_method+from .utils import clear_delivery_method, is_fully_paid, is_shipping_requiredif TYPE_CHECKING:from .fetch import CheckoutInfo, CheckoutLineInfo@@ -19,8 +19,10 @@ def clean_checkout_shipping(lines: Iterable["CheckoutLineInfo"],error_code: Union[Type[CheckoutErrorCode], Type[PaymentErrorCode]],):+ delivery_method_info = checkout_info.delivery_method_info+if is_shipping_required(lines):- if not checkout_info.shipping_method:+ if not delivery_method_info.delivery_method:raise ValidationError({"shipping_method": ValidationError(@@ -29,7 +31,7 @@ def clean_checkout_shipping()})- if not checkout_info.shipping_address:+ if not delivery_method_info.is_valid_delivery_method():raise ValidationError({"shipping_address": ValidationError(@@ -38,11 +40,12 @@ def clean_checkout_shipping()})- if not is_valid_shipping_method(checkout_info):+ if not delivery_method_info.is_method_in_valid_methods(checkout_info):+ clear_delivery_method(checkout_info)raise ValidationError({"shipping_method": ValidationError(- "Shipping method is not valid for your shipping address",+ "Delivery method is not valid for your shipping address",code=error_code.INVALID_SHIPPING_METHOD.value,)}diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 1bdf09c247..f817451086 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -1,10 +1,9 @@from datetime import date-from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuplefrom django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom django.db import transaction-from django.utils.encoding import smart_textfrom prices import TaxedMoneyfrom ..account.error_codes import AccountErrorCode@@ -79,9 +78,14 @@ def _process_shipping_data_for_order(shipping_price: TaxedMoney,manager: "PluginsManager",lines: Iterable["CheckoutLineInfo"],-) -> dict:+) -> Dict[str, Any]:"""Fetch, process and return shipping data from checkout."""- shipping_address = checkout_info.shipping_address+ delivery_method_info = checkout_info.delivery_method_info+ shipping_address = delivery_method_info.shipping_address++ delivery_method_dict = {+ delivery_method_info.order_key: delivery_method_info.delivery_method+ }if checkout_info.user and shipping_address:store_user_address(@@ -90,13 +94,15 @@ def _process_shipping_data_for_order(if checkout_info.user.addresses.filter(pk=shipping_address.pk).exists():shipping_address = shipping_address.get_copy()- return {+ result: Dict[str, Any] = {"shipping_address": shipping_address,- "shipping_method": checkout_info.shipping_method,- "shipping_method_name": smart_text(checkout_info.shipping_method),"shipping_price": shipping_price,"weight": checkout_info.checkout.get_total_weight(lines),}+ result.update(delivery_method_dict)+ result.update(delivery_method_info.delivery_method_name)++ return resultdef _process_user_data_for_order(checkout_info: "CheckoutInfo", manager):@@ -196,8 +202,12 @@ def _create_line_for_order(total_price=total_line_price,tax_rate=tax_rate,)-- line_info = OrderLineData(line=line, quantity=quantity, variant=variant)+ line_info = OrderLineData(+ line=line,+ quantity=quantity,+ variant=variant,+ warehouse_pk=checkout_info.delivery_method_info.warehouse_pk,+ )return line_info@@ -239,8 +249,15 @@ def _create_lines_for_order(for variant_translation in variants_translation}+ additional_warehouse_lookup = (+ checkout_info.delivery_method_info.get_warehouse_filter_lookup()+ )check_stock_quantity_bulk(- variants, country_code, quantities, checkout_info.channel.slug+ variants,+ country_code,+ quantities,+ checkout_info.channel.slug,+ additional_warehouse_lookup,)return [@@ -399,7 +416,16 @@ def _create_order(OrderLine.objects.bulk_create(order_lines)country_code = checkout_info.get_country()- allocate_stocks(order_lines_info, country_code, checkout_info.channel.slug, manager)+ additional_warehouse_lookup = (+ checkout_info.delivery_method_info.get_warehouse_filter_lookup()+ )+ allocate_stocks(+ order_lines_info,+ country_code,+ checkout_info.channel.slug,+ manager,+ additional_warehouse_lookup,+ )# Add gift cards to the orderfor gift_card in checkout.gift_cards.select_for_update():diff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.pyindex 43aa04ff25..6664c406fc 100644--- a/saleor/checkout/error_codes.py+++ b/saleor/checkout/error_codes.py@@ -16,6 +16,7 @@ class CheckoutErrorCode(Enum):REQUIRED = "required"SHIPPING_ADDRESS_NOT_SET = "shipping_address_not_set"SHIPPING_METHOD_NOT_APPLICABLE = "shipping_method_not_applicable"+ DELIVERY_METHOD_NOT_APPLICABLE = "delivery_method_not_applicable"SHIPPING_METHOD_NOT_SET = "shipping_method_not_set"SHIPPING_NOT_REQUIRED = "shipping_not_required"TAX_ERROR = "tax_error"diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 8d75546109..e2b2bc53e9 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -1,7 +1,13 @@+import itertoolsfrom dataclasses import dataclass-from typing import TYPE_CHECKING, Iterable, List, Optional+from functools import singledispatch+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union-from ..shipping.models import ShippingMethodChannelListing+from django.utils.encoding import smart_text++from ..shipping.models import ShippingMethod, ShippingMethodChannelListing+from ..warehouse import WarehouseClickAndCollectOption+from ..warehouse.models import Warehouseif TYPE_CHECKING:from ..account.models import Address, User@@ -15,7 +21,6 @@ if TYPE_CHECKING:ProductVariant,ProductVariantChannelListing,)- from ..shipping.models import ShippingMethodfrom .models import Checkout, CheckoutLine@@ -36,10 +41,17 @@ class CheckoutInfo:channel: "Channel"billing_address: Optional["Address"]shipping_address: Optional["Address"]- shipping_method: Optional["ShippingMethod"]+ delivery_method_info: "DeliveryMethodBase"valid_shipping_methods: List["ShippingMethod"]+ valid_pick_up_points: List["Warehouse"]shipping_method_channel_listings: Optional[ShippingMethodChannelListing]+ @property+ def valid_delivery_methods(self) -> List[Union["ShippingMethod", "Warehouse"]]:+ return list(+ itertools.chain(self.valid_shipping_methods, self.valid_pick_up_points)+ )+def get_country(self) -> str:address = self.shipping_address or self.billing_addressif address is None or not address.country:@@ -50,6 +62,120 @@ class CheckoutInfo:return self.user.email if self.user else self.checkout.email+@dataclass(frozen=True)+class DeliveryMethodBase:+ delivery_method: Optional[Union["ShippingMethod", "Warehouse"]] = None+ shipping_address: Optional["Address"] = None+ order_key: str = "shipping_method"++ @property+ def warehouse_pk(self) -> Optional[str]:+ pass++ @property+ def is_local_collection_point(self) -> bool:+ return False++ @property+ def delivery_method_name(self) -> Dict[str, Optional[str]]:+ return {"shipping_method_name": None}++ def get_warehouse_filter_lookup(self) -> Dict[str, Any]:+ return {}++ def is_valid_delivery_method(self) -> bool:+ return False++ def is_method_in_valid_methods(self, checkout_info: "CheckoutInfo") -> bool:+ return False++ def update_channel_listings(self, checkout_info: "CheckoutInfo") -> None:+ checkout_info.shipping_method_channel_listings = None+++@dataclass(frozen=True)+class ShippingMethodInfo(DeliveryMethodBase):+ delivery_method: "ShippingMethod"+ shipping_address: Optional["Address"]+ order_key: str = "shipping_method"++ @property+ def delivery_method_name(self) -> Dict[str, Optional[str]]:+ return {"shipping_method_name": smart_text(self.delivery_method)}++ def is_valid_delivery_method(self) -> bool:+ return bool(self.shipping_address)++ def is_method_in_valid_methods(self, checkout_info: "CheckoutInfo") -> bool:+ valid_delivery_methods = checkout_info.valid_delivery_methods+ return bool(+ valid_delivery_methods and self.delivery_method in valid_delivery_methods+ )++ def update_channel_listings(self, checkout_info: "CheckoutInfo") -> None:+ checkout_info.shipping_method_channel_listings = (+ ShippingMethodChannelListing.objects.filter(+ shipping_method=self.delivery_method, channel=checkout_info.channel+ ).first()+ )+++@dataclass(frozen=True)+class CollectionPointInfo(DeliveryMethodBase):+ delivery_method: "Warehouse"+ shipping_address: Optional["Address"]+ order_key: str = "collection_point"++ @property+ def warehouse_pk(self):+ return self.delivery_method.pk++ @property+ def is_local_collection_point(self):+ return (+ self.delivery_method.click_and_collect_option+ == WarehouseClickAndCollectOption.LOCAL_STOCK+ )++ @property+ def delivery_method_name(self) -> Dict[str, Optional[str]]:+ return {"collection_point_name": smart_text(self.delivery_method)}++ def get_warehouse_filter_lookup(self) -> Dict[str, Any]:+ return (+ {"warehouse_id": self.delivery_method.pk}+ if self.is_local_collection_point+ else {}+ )++ def is_valid_delivery_method(self) -> bool:+ return (+ self.shipping_address is not None+ and self.shipping_address == self.delivery_method.address+ )++ def is_method_in_valid_methods(self, checkout_info) -> bool:+ valid_delivery_methods = checkout_info.valid_delivery_methods+ return bool(+ valid_delivery_methods and self.delivery_method in valid_delivery_methods+ )+++@singledispatch+def get_delivery_method_info(+ delivery_method: Optional[Union["ShippingMethod", "Warehouse"]],+ address=Optional["Address"],+) -> DeliveryMethodBase:+ if delivery_method is None:+ return DeliveryMethodBase()+ if isinstance(delivery_method, ShippingMethod):+ return ShippingMethodInfo(delivery_method, address)+ if isinstance(delivery_method, Warehouse):+ return CollectionPointInfo(delivery_method, delivery_method.address)++ raise NotImplementedError()++def fetch_checkout_lines(checkout: "Checkout") -> Iterable[CheckoutLineInfo]:"""Fetch checkout lines as CheckoutLineInfo objects."""lines = checkout.lines.prefetch_related(@@ -102,20 +228,29 @@ def fetch_checkout_info(shipping_channel_listings = ShippingMethodChannelListing.objects.filter(shipping_method=shipping_method, channel=channel).first()+ delivery_method = checkout.collection_point or shipping_method+ delivery_method_info = get_delivery_method_info(delivery_method, shipping_address)checkout_info = CheckoutInfo(checkout=checkout,user=checkout.user,channel=channel,billing_address=checkout.billing_address,shipping_address=shipping_address,- shipping_method=shipping_method,+ delivery_method_info=delivery_method_info,shipping_method_channel_listings=shipping_channel_listings,valid_shipping_methods=[],+ valid_pick_up_points=[],)+valid_shipping_methods = get_valid_shipping_method_list_for_checkout_info(checkout_info, shipping_address, lines, discounts, manager)+ valid_pick_up_points = get_valid_collection_points_for_checkout_info(+ checkout_info, shipping_address, lines+ )checkout_info.valid_shipping_methods = valid_shipping_methods+ checkout_info.valid_pick_up_points = valid_pick_up_points+ checkout_info.delivery_method_info = delivery_method_inforeturn checkout_info@@ -132,6 +267,10 @@ def update_checkout_info_shipping_address(checkout_info, address, lines, discounts, manager)checkout_info.valid_shipping_methods = valid_methods+ delivery_method = checkout_info.delivery_method_info.delivery_method+ checkout_info.delivery_method_info = get_delivery_method_info(+ delivery_method, address+ )def get_valid_shipping_method_list_for_checkout_info(@@ -157,16 +296,25 @@ def get_valid_shipping_method_list_for_checkout_info(return valid_shipping_method-def update_checkout_info_shipping_method(- checkout_info: CheckoutInfo, shipping_method: Optional["ShippingMethod"]+def get_valid_collection_points_for_checkout_info(+ checkout_info: "CheckoutInfo",+ shipping_address: Optional["Address"],+ lines: Iterable[CheckoutLineInfo],):- checkout_info.shipping_method = shipping_method- checkout_info.shipping_method_channel_listings = (- (- ShippingMethodChannelListing.objects.filter(- shipping_method=shipping_method, channel=checkout_info.channel- ).first()- )- if shipping_method- else None+ from .utils import get_valid_collection_points_for_checkout++ country_code = shipping_address.country.code if shipping_address else None+ valid_collection_points = get_valid_collection_points_for_checkout(+ lines, checkout_info, country_code=country_code, quantity_check=False+ )+ return list(valid_collection_points)+++def update_checkout_info_delivery_method(+ checkout_info: CheckoutInfo,+ delivery_method: Optional[Union["ShippingMethod", "Warehouse"]],+):+ checkout_info.delivery_method_info = get_delivery_method_info(+ delivery_method, checkout_info.shipping_address)+ checkout_info.delivery_method_info.update_channel_listings(checkout_info)diff --git a/saleor/checkout/migrations/0035_checkout_collection_point.py b/saleor/checkout/migrations/0035_checkout_collection_point.pynew file mode 100644index 0000000000..64b64c2178--- /dev/null+++ b/saleor/checkout/migrations/0035_checkout_collection_point.py@@ -0,0 +1,26 @@+# Generated by Django 3.2.2 on 2021-07-13 09:04++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("warehouse", "0015_auto_20210713_0904"),+ ("checkout", "0034_remove_checkout_quantity"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkout",+ name="collection_point",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="checkouts",+ to="warehouse.warehouse",+ ),+ ),+ ]diff --git a/saleor/checkout/migrations/0036_merge_20210824_1103.py b/saleor/checkout/migrations/0036_merge_20210824_1103.pynew file mode 100644index 0000000000..a6481f7f45--- /dev/null+++ b/saleor/checkout/migrations/0036_merge_20210824_1103.py@@ -0,0 +1,13 @@+# Generated by Django 3.2.6 on 2021-08-24 11:03++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("checkout", "0035_alter_checkout_language_code"),+ ("checkout", "0035_checkout_collection_point"),+ ]++ operations = []diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex 18d89a9a70..ed3da4ce7f 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -6,6 +6,7 @@ from uuid import uuid4from django.conf import settingsfrom django.core.validators import MinValueValidatorfrom django.db import models+from django.db.models.deletion import SET_NULLfrom django.utils.encoding import smart_strfrom django_countries.fields import Country, CountryFieldfrom django_prices.models import MoneyField@@ -72,6 +73,13 @@ class Checkout(ModelWithMetadata):related_name="checkouts",on_delete=models.SET_NULL,)+ collection_point = models.ForeignKey(+ "warehouse.Warehouse",+ blank=True,+ null=True,+ related_name="checkouts",+ on_delete=models.SET_NULL,+ )note = models.TextField(blank=True, default="")currency = models.CharField(diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex 0380c0ea07..525e42a8c6 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -15,13 +15,15 @@ from ...discount import DiscountValueType, VoucherTypefrom ...discount.models import NotApplicable, Voucher, VoucherChannelListingfrom ...payment.models import Paymentfrom ...plugins.manager import get_plugins_manager-from ...shipping.models import ShippingZone+from ...shipping.models import ShippingMethod, ShippingZonefrom .. import AddressType, calculationsfrom ..fetch import (CheckoutInfo,CheckoutLineInfo,+ DeliveryMethodBase,fetch_checkout_info,fetch_checkout_lines,+ get_delivery_method_info,)from ..models import Checkoutfrom ..utils import (@@ -30,49 +32,51 @@ from ..utils import (cancel_active_payments,change_billing_address_in_checkout,change_shipping_address_in_checkout,- clear_shipping_method,+ clear_delivery_method,get_voucher_discount_for_checkout,get_voucher_for_checkout,is_fully_paid,- is_valid_shipping_method,recalculate_checkout_discount,remove_voucher_from_checkout,)-def test_is_valid_shipping_method(checkout_with_item, address, shipping_zone):+def test_is_valid_delivery_method(checkout_with_item, address, shipping_zone):checkout = checkout_with_itemcheckout.shipping_address = addresscheckout.save()manager = get_plugins_manager()lines = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ delivery_method_info = checkout_info.delivery_method_info# no shipping method assigned- assert not is_valid_shipping_method(checkout_info)+ assert not delivery_method_info.is_valid_delivery_method()shipping_method = shipping_zone.shipping_methods.first()checkout.shipping_method = shipping_methodcheckout.save()checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ delivery_method_info = checkout_info.delivery_method_info- assert is_valid_shipping_method(checkout_info)+ assert delivery_method_info.is_valid_delivery_method()zone = ShippingZone.objects.create(name="DE", countries=["DE"])shipping_method.shipping_zone = zoneshipping_method.save()checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ delivery_method_info = checkout_info.delivery_method_info- assert not is_valid_shipping_method(checkout_info)+ assert not delivery_method_info.is_method_in_valid_methods(checkout_info)-def test_clear_shipping_method(checkout, shipping_method):+def test_clear_delivery_method(checkout, shipping_method):checkout.shipping_method = shipping_methodcheckout.save()manager = get_plugins_manager()checkout_info = fetch_checkout_info(checkout, [], [], manager)- clear_shipping_method(checkout_info)+ clear_delivery_method(checkout_info)checkout.refresh_from_db()assert not checkout.shipping_method- assert not checkout_info.shipping_method+ assert isinstance(checkout_info.delivery_method_info, DeliveryMethodBase)assert not checkout_info.shipping_method_channel_listings@@ -141,13 +145,14 @@ def test_get_discount_for_checkout_value_voucher()checkout_info = CheckoutInfo(checkout=checkout,- shipping_method=None,shipping_address=None,billing_address=None,channel=channel_USD,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],+ delivery_method_info=get_delivery_method_info(None, None),)lines = [CheckoutLineInfo(@@ -235,13 +240,14 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable()checkout_info = CheckoutInfo(checkout=checkout,- shipping_method=None,+ delivery_method_info=None,shipping_address=None,billing_address=None,channel=channel_USD,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)manager = get_plugins_manager()with pytest.raises(NotApplicable):@@ -348,13 +354,14 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(checkout = Mock(quantity=total_quantity, spec=Checkout, channel=channel_USD)checkout_info = CheckoutInfo(checkout=checkout,- shipping_method=None,+ delivery_method_info=get_delivery_method_info(None, None),shipping_address=None,billing_address=None,channel=channel_USD,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)with pytest.raises(NotApplicable):get_voucher_discount_for_checkout(@@ -417,16 +424,21 @@ def test_get_discount_for_checkout_shipping_voucher(channel=channel_USD,discount=Money(discount_value, channel_USD.currency_code),)+ shipping_address = Mock(spec=Address, country=Mock(code="PL"))checkout_info = CheckoutInfo(checkout=checkout,- shipping_method=shipping_method,- shipping_address=Mock(spec=Address, country=Mock(code="PL")),+ shipping_address=shipping_address,+ delivery_method_info=get_delivery_method_info(+ shipping_method, shipping_address+ ),billing_address=None,channel=channel_USD,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)+discount = get_voucher_discount_for_checkout(manager, voucher, checkout_info, [], None, None)@@ -477,13 +489,14 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries(manager = get_plugins_manager()checkout_info = CheckoutInfo(checkout=checkout,- shipping_method=shipping_method,+ delivery_method_info=get_delivery_method_info(shipping_method, None),shipping_address=Mock(spec=Address, country=Mock(code="PL")),billing_address=None,channel=channel_USD,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)discount = get_voucher_discount_for_checkout(manager, voucher, checkout_info, [], None, None@@ -522,13 +535,14 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(checkout_info = CheckoutInfo(checkout=checkout,- shipping_method=None,+ delivery_method_info=get_delivery_method_info(None, None),shipping_address=Mock(spec=Address, country=Mock(code="PL")),billing_address=None,channel=channel_USD,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)manager = get_plugins_manager()with pytest.raises(NotApplicable):@@ -543,6 +557,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries((True,Mock(+ spec=ShippingMethod,get_total=Mock(return_value=Money(10, "USD")),shipping_zone=Mock(countries=["PL"]),),@@ -565,7 +580,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(None,TaxedMoney(Money(10, "USD"), Money(10, "USD")),10,- "Please select a shipping method first.",+ "Please select a delivery method first.",),(False,@@ -581,7 +596,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(),(True,- Mock(price=Money(10, "USD")),+ Mock(spec=ShippingMethod, price=Money(10, "USD")),10,DiscountValueType.FIXED,[],@@ -593,7 +608,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(),(True,- Mock(price=Money(10, "USD")),+ Mock(spec=ShippingMethod, price=Money(10, "USD")),10,DiscountValueType.FIXED,[],@@ -605,7 +620,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(),(True,- Mock(price=Money(10, "USD")),+ Mock(spec=ShippingMethod, price=Money(10, "USD")),10,DiscountValueType.FIXED,[],@@ -667,13 +682,14 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable()checkout_info = CheckoutInfo(checkout=checkout,- shipping_method=shipping_method,+ delivery_method_info=get_delivery_method_info(shipping_method),shipping_address=Mock(spec=Address, country=Mock(code="PL")),billing_address=None,channel=channel_USD,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)with pytest.raises(NotApplicable) as e:get_voucher_discount_for_checkout(@@ -1207,3 +1223,18 @@ def test_cancel_active_payments(checkout_with_payments):# thenassert checkout.payments.filter(is_active=True).count() == 0+++def test_chckout_without_delivery_method_creates_empty_delivery_method(+ checkout_with_item,+):+ checkout = checkout_with_item+ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ delivery_method_info = checkout_info.delivery_method_info++ assert isinstance(delivery_method_info, DeliveryMethodBase)+ assert not delivery_method_info.is_valid_delivery_method()+ assert not delivery_method_info.is_local_collection_point+ assert not delivery_method_info.is_method_in_valid_methods(checkout_info)diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex e0890337b2..8e6c190af7 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -28,11 +28,12 @@ from ..plugins.manager import PluginsManagerfrom ..product import models as product_modelsfrom ..shipping.models import ShippingMethodfrom ..warehouse.availability import check_stock_quantity, check_stock_quantity_bulk+from ..warehouse.models import Warehousefrom . import AddressType, calculationsfrom .error_codes import CheckoutErrorCodefrom .fetch import (+ update_checkout_info_delivery_method,update_checkout_info_shipping_address,- update_checkout_info_shipping_method,)from .models import Checkout, CheckoutLine@@ -255,9 +256,9 @@ def _get_shipping_voucher_discount_for_checkout(if not is_shipping_required(lines):msg = "Your order does not require shipping."raise NotApplicable(msg)- shipping_method = checkout_info.shipping_method+ shipping_method = checkout_info.delivery_method_info.delivery_methodif not shipping_method:- msg = "Please select a shipping method first."+ msg = "Please select a delivery method first."raise NotApplicable(msg)# check if voucher is limited to specified countries@@ -603,25 +604,41 @@ def get_valid_shipping_methods_for_checkout()-def is_valid_shipping_method(checkout_info: "CheckoutInfo"):- """Check if shipping method is valid and remove (if not)."""- if not checkout_info.shipping_method:- return False- if not checkout_info.shipping_address:- return False+def get_valid_collection_points_for_checkout(+ lines: Iterable["CheckoutLineInfo"],+ checkout_info: "CheckoutInfo",+ country_code: Optional[str] = None,+ quantity_check: bool = True,+):+ """Return a collection of `Warehouse`s that can be used as a collection point.- valid_methods = checkout_info.valid_shipping_methods- if valid_methods is None or checkout_info.shipping_method not in valid_methods:- clear_shipping_method(checkout_info)- return False- return True+ Note that `quantity_check=False` should be used, when stocks quantity will+ be validated in further steps (checkout completion) in order to raise+ 'InsufficientProductStock' error instead of 'InvalidShippingError'.+ """++ if not is_shipping_required(lines):+ return []+ if not checkout_info.shipping_address:+ return []+ line_ids = [line_info.line.id for line_info in lines]+ lines = CheckoutLine.objects.filter(id__in=line_ids)++ return (+ Warehouse.objects.applicable_for_click_and_collect(lines, country_code)+ if quantity_check+ else Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(+ lines, country_code+ )+ )-def clear_shipping_method(checkout_info: "CheckoutInfo"):+def clear_delivery_method(checkout_info: "CheckoutInfo"):checkout = checkout_info.checkout+ checkout.collection_point = Nonecheckout.shipping_method = None- update_checkout_info_shipping_method(checkout_info, None)- checkout.save(update_fields=["shipping_method", "last_change"])+ update_checkout_info_delivery_method(checkout_info, None)+ checkout.save(update_fields=["shipping_method", "collection_point", "last_change"])def is_fully_paid(diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex e1f8389476..2376ffa228 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -82,6 +82,7 @@ from ...shipping.models import (ShippingMethodType,ShippingZone,)+from ...warehouse import WarehouseClickAndCollectOptionfrom ...warehouse.management import increase_stockfrom ...warehouse.models import Stock, Warehouse@@ -1202,16 +1203,47 @@ def create_shipping_zones():)+def create_additional_cc_warehouse():+ shipping_zone = ShippingZone.objects.first()+ warehouse_name = f"{shipping_zone.name} for click and collect"+ warehouse, _ = Warehouse.objects.update_or_create(+ name=warehouse_name,+ slug=slugify(warehouse_name),+ defaults={+ "address": create_address(),+ "is_private": False,+ "click_and_collect_option": WarehouseClickAndCollectOption.LOCAL_STOCK,+ },+ )+ warehouse.shipping_zones.add(shipping_zone)++def create_warehouses():for shipping_zone in ShippingZone.objects.all():shipping_zone_name = shipping_zone.name+ is_private = random.choice([True, False])+ cc_option = random.choice(+ [+ option[0]+ for option in WarehouseClickAndCollectOption.CHOICES+ if not (+ is_private and option == WarehouseClickAndCollectOption.LOCAL_STOCK+ )+ ]+ )warehouse, _ = Warehouse.objects.update_or_create(name=shipping_zone_name,slug=slugify(shipping_zone_name),- defaults={"address": create_address(company_name=fake.company())},+ defaults={+ "address": create_address(company_name=fake.company()),+ "is_private": is_private,+ "click_and_collect_option": cc_option,+ },)warehouse.shipping_zones.add(shipping_zone)+ create_additional_cc_warehouse()+def create_vouchers():channels = list(Channel.objects.all())diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex c2b50d7563..a2fa9cde5f 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -3,7 +3,7 @@ from collections import defaultdictfrom django.db.models import Ffrom promise import Promise-from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo+from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo, get_delivery_method_infofrom ...checkout.models import Checkout, CheckoutLinefrom ..account.dataloaders import AddressByIdLoader, UserByUserIdLoaderfrom ..core.dataloaders import DataLoader@@ -18,6 +18,7 @@ from ..shipping.dataloaders import (ShippingMethodByIdLoader,ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader,)+from ..warehouse.dataloaders import WarehouseByIdLoaderclass CheckoutByTokenLoader(DataLoader):@@ -187,6 +188,14 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):self.context).load_many(shipping_method_ids_channel_slugs))+ collection_point_ids = [+ checkout.collection_point_id+ for checkout in checkouts+ if checkout.collection_point_id+ ]+ collection_points = WarehouseByIdLoader(self.context).load_many(+ collection_point_ids+ )def with_checkout_info(results):(@@ -194,6 +203,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):users,shipping_methods,channel_listings,+ collection_points,) = resultsaddress_map = {address.id: address for address in addresses}user_map = {user.id: user for user in users}@@ -207,8 +217,23 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):if listing}+ collection_points_map = {+ collection_point.id: collection_point+ for collection_point in collection_points+ }+checkout_info_map = {}for key, checkout, channel in zip(keys, checkouts, channels):+ delivery_method = shipping_method_map.get(+ checkout.shipping_method_id+ ) or collection_points_map.get(checkout.collection_point_id)+ shipping_address = (+ address_map.get(checkout.shipping_address_id),+ )+ delivery_method_info = get_delivery_method_info(+ delivery_method, shipping_address+ )+checkout_info_map[key] = CheckoutInfo(checkout=checkout,user=user_map.get(checkout.user_id),@@ -219,16 +244,16 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):shipping_address=address_map.get(checkout.shipping_address_id),- shipping_method=shipping_method_map.get(- checkout.shipping_method_id- ),+ delivery_method_info=delivery_method_info,valid_shipping_methods=[],+ valid_pick_up_points=[],shipping_method_channel_listings=(shipping_method_channel_listing_map.get((checkout.shipping_method_id, channel.id))),)+return [checkout_info_map[key] for key in keys]return Promise.all(@@ -237,6 +262,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):users,shipping_methods,shipping_method_channel_listings,+ collection_points,]).then(with_checkout_info)diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 06d2d90395..6672e46983 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -1,6 +1,6 @@import datetimeimport uuid-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple+from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Unionimport graphenefrom django.conf import settings@@ -14,6 +14,7 @@ from ...checkout.fetch import (CheckoutLineInfo,fetch_checkout_info,fetch_checkout_lines,+ get_valid_collection_points_for_checkout_info,get_valid_shipping_method_list_for_checkout_info,)from ...checkout.utils import (@@ -22,7 +23,7 @@ from ...checkout.utils import (calculate_checkout_quantity,change_billing_address_in_checkout,change_shipping_address_in_checkout,- clear_shipping_method,+ clear_delivery_method,is_shipping_required,recalculate_checkout_discount,remove_promo_code_from_checkout,@@ -36,15 +37,21 @@ from ...order import models as order_modelsfrom ...product import models as product_modelsfrom ...product.models import ProductChannelListingfrom ...shipping import models as shipping_models+from ...warehouse import models as warehouse_modelsfrom ...warehouse.availability import check_stock_quantity_bulkfrom ..account.i18n import I18nMixinfrom ..account.types import AddressInputfrom ..channel.utils import clean_channel-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 LanguageCodeEnumfrom ..core.mutations import BaseMutation, ModelMutationfrom ..core.scalars import UUIDfrom ..core.types.common import CheckoutError+from ..core.utils import from_global_id_or_errorfrom ..core.validators import (validate_one_of_args_is_in_mutation,validate_variants_available_in_channel,@@ -52,6 +59,7 @@ from ..core.validators import (from ..order.types import Orderfrom ..product.types import ProductVariantfrom ..shipping.types import ShippingMethod+from ..warehouse.types import Warehousefrom .types import Checkout, CheckoutLinefrom .utils import prepare_insufficient_stock_checkout_validation_error@@ -63,10 +71,10 @@ if TYPE_CHECKING:from ...checkout.fetch import CheckoutInfo-def clean_shipping_method(+def clean_delivery_method(checkout_info: "CheckoutInfo",lines: Iterable[CheckoutLineInfo],- method: Optional[models.ShippingMethod],+ method: Optional[Union[models.ShippingMethod, warehouse_models.Warehouse]],) -> bool:"""Check if current shipping method is valid."""@@ -86,7 +94,7 @@ def clean_shipping_method(code=CheckoutErrorCode.SHIPPING_ADDRESS_NOT_SET.value,)- valid_methods = checkout_info.valid_shipping_methods+ valid_methods = checkout_info.valid_delivery_methodsreturn method in valid_methods@@ -97,17 +105,16 @@ def update_checkout_shipping_method_if_invalid(# remove shipping method when empty checkoutif quantity == 0 or not is_shipping_required(lines):- clear_shipping_method(checkout_info)+ clear_delivery_method(checkout_info)- is_valid = clean_shipping_method(+ is_valid = clean_delivery_method(checkout_info=checkout_info,lines=lines,- method=checkout_info.shipping_method,+ method=checkout_info.delivery_method_info.delivery_method,)if not is_valid:- # remove shipping method when it is no longer valid- clear_shipping_method(checkout_info)+ clear_delivery_method(checkout_info)def check_lines_quantity(@@ -475,6 +482,11 @@ class CheckoutLinesAdd(BaseMutation):checkout_info, checkout_info.shipping_address, lines, discounts, manager))+ checkout_info.valid_pick_up_points = (+ get_valid_collection_points_for_checkout_info(+ checkout_info, checkout_info.shipping_address, lines+ )+ )@classmethoddef perform_mutation(@@ -511,6 +523,11 @@ class CheckoutLinesAdd(BaseMutation):checkout_info, checkout_info.shipping_address, lines, discounts, manager))+ checkout_info.valid_pick_up_points = (+ get_valid_collection_points_for_checkout_info(+ checkout_info, checkout_info.shipping_address, lines+ )+ )update_checkout_shipping_method_if_invalid(checkout_info, lines)recalculate_checkout_discount(@@ -807,7 +824,8 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):checkout_id = graphene.ID(required=False,description=(- f"The ID of the checkout. {DEPRECATED_IN_3X_INPUT} Use token instead."+ f"The ID of the checkout. {DEPRECATED_IN_3X_INPUT} "+ "Use token instead."),)token = UUID(description="Checkout token.", required=False)@@ -991,7 +1009,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):),)- shipping_method_is_valid = clean_shipping_method(+ shipping_method_is_valid = clean_delivery_method(checkout_info=checkout_info,lines=lines,method=shipping_method,@@ -1015,6 +1033,174 @@ class CheckoutShippingMethodUpdate(BaseMutation):return CheckoutShippingMethodUpdate(checkout=checkout)+class CheckoutDeliveryMethodUpdate(BaseMutation):+ checkout = graphene.Field(Checkout, description="An updated checkout.")++ class Arguments:+ token = UUID(description="Checkout token.", required=False)+ delivery_method_id = graphene.ID(+ description="Delivery Method ID (`Warehouse` ID or `ShippingMethod` ID).",+ required=False,+ )++ class Meta:+ description = (+ f"{ADDED_IN_31} Updates the delivery method "+ "(shipping method or pick up point) of the checkout."+ )+ error_type_class = CheckoutError++ @classmethod+ def perform_on_shipping_method(+ cls, info, shipping_method_id, checkout_info, lines, checkout, manager+ ):+ shipping_method = cls.get_node_or_error(+ info,+ shipping_method_id,+ only_type=ShippingMethod,+ field="delivery_method_id",+ qs=shipping_models.ShippingMethod.objects.prefetch_related(+ "postal_code_rules"+ ),+ )++ cls._check_delivery_method(+ checkout_info, lines, shipping_method=shipping_method, collection_point=None+ )++ cls._update_delivery_method(+ manager,+ checkout,+ shipping_method=shipping_method,+ collection_point=None,+ )+ recalculate_checkout_discount(+ manager, checkout_info, lines, info.context.discounts+ )+ return CheckoutDeliveryMethodUpdate(checkout=checkout)++ @classmethod+ def perform_on_collection_point(+ cls, info, collection_point_id, checkout_info, lines, checkout, manager+ ):+ collection_point = cls.get_node_or_error(+ info,+ collection_point_id,+ only_type=Warehouse,+ field="delivery_method_id",+ qs=warehouse_models.Warehouse.objects.select_related("address"),+ )+ cls._check_delivery_method(+ checkout_info,+ lines,+ shipping_method=None,+ collection_point=collection_point,+ )+ cls._update_delivery_method(+ manager, checkout, shipping_method=None, collection_point=collection_point+ )+ return CheckoutDeliveryMethodUpdate(checkout=checkout)++ @staticmethod+ def _check_delivery_method(+ checkout_info,+ lines,+ *,+ shipping_method: Optional[ShippingMethod],+ collection_point: Optional[Warehouse]+ ) -> None:+ delivery_method = shipping_method+ error_msg = "This shipping method is not applicable."++ if collection_point is not None:+ delivery_method = collection_point+ error_msg = "This pick up point is not applicable."++ delivery_method_is_valid = clean_delivery_method(+ checkout_info=checkout_info, lines=lines, method=delivery_method+ )+ if not delivery_method_is_valid:+ raise ValidationError(+ {+ "delivery_method_id": ValidationError(+ error_msg,+ code=CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.value,+ )+ }+ )++ @staticmethod+ def _update_delivery_method(+ manager,+ checkout: Checkout,+ *,+ shipping_method: Optional[ShippingMethod],+ collection_point: Optional[Warehouse]+ ) -> None:+ checkout.shipping_method = shipping_method+ checkout.collection_point = collection_point+ checkout.save(+ update_fields=["shipping_method", "collection_point", "last_change"]+ )+ manager.checkout_updated(checkout)++ @staticmethod+ def _resolve_delivery_method_type(id_) -> Optional[str]:+ if id_ is None:+ return None++ possible_types = ("Warehouse", "ShippingMethod")+ type_, id_ = from_global_id_or_error(id_)+ str_type = str(type_)++ if str_type not in possible_types:+ raise ValidationError(+ {+ "delivery_method_id": ValidationError(+ "ID does not belong to Warehouse or ShippingMethod",+ code=CheckoutErrorCode.INVALID.value,+ )+ }+ )++ return str_type++ @classmethod+ def perform_mutation(+ cls,+ _,+ info,+ token,+ delivery_method_id=None,+ ):++ checkout = get_checkout_by_token(token)++ manager = info.context.plugins+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(+ checkout, lines, info.context.discounts, manager+ )+ if not is_shipping_required(lines):+ raise ValidationError(+ {+ "delivery_method": ValidationError(+ ERROR_DOES_NOT_SHIP,+ code=CheckoutErrorCode.SHIPPING_NOT_REQUIRED,+ )+ }+ )+ type_name = cls._resolve_delivery_method_type(delivery_method_id)++ if type_name == "Warehouse":+ return cls.perform_on_collection_point(+ info, delivery_method_id, checkout_info, lines, checkout, manager+ )+ return cls.perform_on_shipping_method(+ info, delivery_method_id, checkout_info, lines, checkout, manager+ )++class CheckoutComplete(BaseMutation):order = graphene.Field(Order, description="Placed order.")confirmation_needed = graphene.Boolean(diff --git a/saleor/graphql/checkout/schema.py b/saleor/graphql/checkout/schema.pyindex 948c48f4a3..85ca102fc7 100644--- a/saleor/graphql/checkout/schema.py+++ b/saleor/graphql/checkout/schema.py@@ -1,6 +1,7 @@import graphenefrom ...core.permissions import CheckoutPermissions+from ..core.descriptions import DEPRECATED_IN_3X_FIELDfrom ..core.fields import BaseDjangoConnectionField, PrefetchingConnectionFieldfrom ..core.scalars import UUIDfrom ..decorators import permission_required@@ -12,6 +13,7 @@ from .mutations import (CheckoutCreate,CheckoutCustomerAttach,CheckoutCustomerDetach,+ CheckoutDeliveryMethodUpdate,CheckoutEmailUpdate,CheckoutLanguageCodeUpdate,CheckoutLineDelete,@@ -69,5 +71,10 @@ class CheckoutMutations(graphene.ObjectType):checkout_remove_promo_code = CheckoutRemovePromoCode.Field()checkout_payment_create = CheckoutPaymentCreate.Field()checkout_shipping_address_update = CheckoutShippingAddressUpdate.Field()- checkout_shipping_method_update = CheckoutShippingMethodUpdate.Field()+ checkout_shipping_method_update = CheckoutShippingMethodUpdate.Field(+ deprecation_reason=(+ f"{DEPRECATED_IN_3X_FIELD} " "Use `checkoutDeliveryMethodUpdate` instead."+ )+ )+ checkout_delivery_method_update = CheckoutDeliveryMethodUpdate.Field()checkout_language_code_update = CheckoutLanguageCodeUpdate.Field()diff --git a/saleor/graphql/checkout/tests/benchmark/conftest.py b/saleor/graphql/checkout/tests/benchmark/conftest.pyindex d70a609e16..b8549835ba 100644--- a/saleor/graphql/checkout/tests/benchmark/conftest.py+++ b/saleor/graphql/checkout/tests/benchmark/conftest.py@@ -40,6 +40,20 @@ def checkout_with_variants(return checkout+def checkout_with_variants_for_cc(+ checkout, stocks_for_cc, product_variant_list, product_with_two_variants+):+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())++ add_variant_to_checkout(checkout_info, product_variant_list[0], 3)+ add_variant_to_checkout(checkout_info, product_variant_list[1], 10)+ add_variant_to_checkout(checkout_info, product_with_two_variants.variants.last(), 5)++ checkout.save()+ return checkout++@pytest.fixture()def checkout_with_shipping_address(checkout_with_variants, address):checkout = checkout_with_variants@@ -50,6 +64,16 @@ def checkout_with_shipping_address(checkout_with_variants, address):return checkout+def checkout_with_shipping_address_for_cc(checkout_with_variants_for_cc, address):+ checkout = checkout_with_variants_for_cc++ checkout.shipping_address = address.get_copy()+ checkout.save()++ return checkout++@pytest.fixture()def checkout_with_shipping_method(checkout_with_shipping_address, shipping_method):checkout = checkout_with_shipping_address@@ -60,6 +84,18 @@ def checkout_with_shipping_method(checkout_with_shipping_address, shipping_methoreturn checkout+def checkout_with_delivery_method_for_cc(+ warehouses_for_cc, checkout_with_shipping_address_for_cc+):+ checkout = checkout_with_shipping_address_for_cc+ checkout.collection_point = warehouses_for_cc[1]++ checkout.save()++ return checkout++@pytest.fixture()def checkout_with_billing_address(checkout_with_shipping_method, address):checkout = checkout_with_shipping_method@@ -70,6 +106,16 @@ def checkout_with_billing_address(checkout_with_shipping_method, address):return checkout+def checkout_with_billing_address_for_cc(checkout_with_delivery_method_for_cc, address):+ checkout = checkout_with_delivery_method_for_cc++ checkout.billing_address = address+ checkout.save()++ return checkout++@pytest.fixture()def checkout_with_voucher(checkout_with_billing_address, voucher):checkout = checkout_with_billing_address@@ -113,3 +159,38 @@ def checkout_with_charged_payment(checkout_with_voucher):)return checkout+++def checkout_with_charged_payment_for_cc(checkout_with_billing_address_for_cc):+ checkout = checkout_with_billing_address_for_cc+ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ 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 979d277bb7..269e82f4c6 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -102,6 +102,18 @@ FRAGMENT_SHIPPING_METHOD = """}"""+FRAGMENT_COLLECTION_POINT = """+ fragment CollectionPoint on Warehouse {+ id+ name+ isPrivate+ clickAndCollectOption+ address {+ streetAddress1+ }+ }+"""+FRAGMENT_CHECKOUT = (FRAGMENT_CHECKOUT_LINE@@ -156,6 +168,69 @@ FRAGMENT_CHECKOUT = (""")+FRAGMENT_CHECKOUT_FOR_CC = (+ FRAGMENT_CHECKOUT_LINE+ + FRAGMENT_ADDRESS+ + FRAGMENT_SHIPPING_METHOD+ + FRAGMENT_COLLECTION_POINT+ + """+ fragment Checkout on Checkout {+ availablePaymentGateways {+ id+ name+ config {+ field+ value+ }+ }+ token+ id+ totalPrice {+ ...Price+ }+ subtotalPrice {+ ...Price+ }+ billingAddress {+ ...Address+ }+ shippingAddress {+ ...Address+ }+ availableShippingMethods {+ ...ShippingMethod+ }+ availableCollectionPoints {+ ...CollectionPoint+ }+ deliveryMethod {+ __typename+ ... on ShippingMethod {+ ...ShippingMethod+ }+ ... on Warehouse {+ ...CollectionPoint+ }+ }+ shippingPrice {+ ...Price+ }+ lines {+ ...CheckoutLine+ }+ isShippingRequired+ discount {+ currency+ amount+ }+ discountName+ translatedDiscountName+ voucherCode+ }+ """+)+@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)@@ -233,6 +308,66 @@ def test_create_checkout(assert checkout_counts + 1 == Checkout.objects.count()[email protected]_queries(autouse=False)+def test_create_checkout_for_cc(+ api_client,+ graphql_address_data,+ channel_USD,+ stocks_for_cc,+ product_variant_list,+ count_queries,+):+ query = (+ FRAGMENT_CHECKOUT_FOR_CC+ + """+ mutation CreateCheckout($checkoutInput: CheckoutCreateInput!) {+ checkoutCreate(input: $checkoutInput) {+ errors {+ field+ message+ }+ checkout {+ ...Checkout+ }+ }+ }+ """+ )+ checkout_counts = Checkout.objects.count()+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "email": "[email protected]",+ "shippingAddress": graphql_address_data,+ "lines": [+ {+ "quantity": 1,+ "variantId": Node.to_global_id(+ "ProductVariant", stocks_for_cc[0].product_variant.pk+ ),+ },+ {+ "quantity": 2,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_variant_list[0].pk,+ ),+ },+ {+ "quantity": 5,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_variant_list[1].pk,+ ),+ },+ ],+ }+ }+ get_graphql_content(api_client.post_graphql(query, variables))+ assert checkout_counts + 1 == Checkout.objects.count()++@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)def test_add_shipping_to_checkout(@@ -269,6 +404,42 @@ def test_add_shipping_to_checkout(assert not response["data"]["checkoutShippingMethodUpdate"]["errors"][email protected]_queries(autouse=False)+def test_add_delivery_to_checkout(+ api_client,+ checkout_with_shipping_address_for_cc,+ warehouses_for_cc,+ count_queries,+):+ query = (+ FRAGMENT_CHECKOUT+ + """+ mutation updateCheckoutDeliveryOptions(+ $token: UUID, $deliveryMethodId: ID+ ) {+ checkoutDeliveryMethodUpdate(+ token: $token, deliveryMethodId: $deliveryMethodId+ ) {+ errors {+ field+ message+ }+ checkout {+ ...Checkout+ }+ }+ }+ """+ )+ variables = {+ "token": checkout_with_shipping_address_for_cc.token,+ "deliveryMethodId": Node.to_global_id("Warehouse", warehouses_for_cc[1].pk),+ }+ response = get_graphql_content(api_client.post_graphql(query, variables))+ assert not response["data"]["checkoutDeliveryMethodUpdate"]["errors"]++@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)def test_add_billing_address_to_checkout(@@ -663,10 +834,72 @@ FRAGMENT_ORDER_DETAIL = (""")--COMPLETE_CHECKOUT_MUTATION = (- FRAGMENT_ORDER_DETAIL+FRAGMENT_ORDER_DETAIL_FOR_CC = (+ FRAGMENT_ADDRESS+ + FRAGMENT_PRODUCT_VARIANT+ + ORDER_PRICE_FRAGMENT+ + FRAGMENT_COLLECTION_POINT+ + FRAGMENT_SHIPPING_METHOD+ """+ fragment OrderDetail on Order {+ userEmail+ paymentStatus+ paymentStatusDisplay+ status+ statusDisplay+ id+ token+ number+ shippingAddress {+ ...Address+ __typename+ }+ deliveryMethod {+ __typename+ ... on ShippingMethod {+ ...ShippingMethod+ }+ ... on Warehouse {+ ...CollectionPoint+ }+ }+ lines {+ productName+ quantity+ variant {+ ...ProductVariant+ __typename+ }+ unitPrice {+ currency+ ...OrderPrice+ __typename+ }+ totalPrice {+ currency+ ...OrderPrice+ __typename+ }+ __typename+ }+ subtotal {+ ...OrderPrice+ __typename+ }+ total {+ ...OrderPrice+ __typename+ }+ shippingPrice {+ ...OrderPrice+ __typename+ }+ __typename+ }+ """+)++COMPLETE_CHECKOUT_MUTATION_PART = """mutation completeCheckout($token: UUID) {checkoutComplete(token: $token) {errors {@@ -683,6 +916,12 @@ COMPLETE_CHECKOUT_MUTATION = (}}"""+++COMPLETE_CHECKOUT_MUTATION = FRAGMENT_ORDER_DETAIL + COMPLETE_CHECKOUT_MUTATION_PART++COMPLETE_CHECKOUT_MUTATION_FOR_CC = (+ FRAGMENT_ORDER_DETAIL_FOR_CC + COMPLETE_CHECKOUT_MUTATION_PART)@@ -754,3 +993,20 @@ def test_customer_complete_checkout(response = get_graphql_content(api_client.post_graphql(query, variables))assert not response["data"]["checkoutComplete"]["errors"]++[email protected]_queries(autouse=False)+def test_customer_complete_checkout_for_cc(+ api_client, checkout_with_charged_payment_for_cc, count_queries, customer_user+):+ query = COMPLETE_CHECKOUT_MUTATION_FOR_CC+ checkout = checkout_with_charged_payment_for_cc+ checkout.user = customer_user+ checkout.save()+ variables = {+ "token": checkout.token,+ }++ response = get_graphql_content(api_client.post_graphql(query, variables))+ assert not response["data"]["checkoutComplete"]["errors"]diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.pyindex cf7ca6c148..e704d2db15 100644--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py@@ -3,7 +3,11 @@ from unittest.mock import patchimport graphenefrom .....checkout.error_codes import CheckoutErrorCode-from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from .....checkout.fetch import (+ fetch_checkout_info,+ fetch_checkout_lines,+ get_delivery_method_info,+)from .....plugins.manager import get_plugins_managerfrom ....tests.utils import get_graphql_content@@ -29,7 +33,7 @@ MUTATION_UPDATE_SHIPPING_METHOD = """"""-@patch("saleor.graphql.checkout.mutations.clean_shipping_method")+@patch("saleor.graphql.checkout.mutations.clean_delivery_method")def test_checkout_shipping_method_update_by_id(mock_clean_shipping,staff_api_client,@@ -54,7 +58,9 @@ def test_checkout_shipping_method_update_by_id(manager = get_plugins_manager()lines = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, [], manager)- checkout_info.shipping_method = old_shipping_method+ checkout_info.delivery_method_info = get_delivery_method_info(+ old_shipping_method, None+ )checkout_info.shipping_method_channel_listings = Nonemock_clean_shipping.assert_called_once_with(checkout_info=checkout_info, lines=lines, method=shipping_method@@ -65,7 +71,7 @@ def test_checkout_shipping_method_update_by_id(assert checkout.shipping_method == shipping_method-@patch("saleor.graphql.checkout.mutations.clean_shipping_method")+@patch("saleor.graphql.checkout.mutations.clean_delivery_method")def test_checkout_shipping_method_update_by_token(mock_clean_shipping,staff_api_client,@@ -90,7 +96,9 @@ def test_checkout_shipping_method_update_by_token(manager = get_plugins_manager()lines = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, [], manager)- checkout_info.shipping_method = old_shipping_method+ checkout_info.delivery_method_info = get_delivery_method_info(+ old_shipping_method, None+ )checkout_info.shipping_method_channel_listings = Nonemock_clean_shipping.assert_called_once_with(checkout_info=checkout_info, lines=lines, method=shipping_method@@ -101,7 +109,7 @@ def test_checkout_shipping_method_update_by_token(assert checkout.shipping_method == shipping_method-@patch("saleor.graphql.checkout.mutations.clean_shipping_method")+@patch("saleor.graphql.checkout.mutations.clean_delivery_method")def test_checkout_shipping_method_update_neither_token_and_id_given(mock_clean_shipping, staff_api_client, checkout_with_item, shipping_method):@@ -117,7 +125,7 @@ def test_checkout_shipping_method_update_neither_token_and_id_given(assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name-@patch("saleor.graphql.checkout.mutations.clean_shipping_method")+@patch("saleor.graphql.checkout.mutations.clean_delivery_method")def test_checkout_shipping_method_update_both_token_and_id_given(mock_clean_shipping, staff_api_client, checkout_with_item, shipping_method):diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex c401f3ab38..ca64bd39cc 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -8,6 +8,7 @@ from unittest.mock import patchimport grapheneimport pytestfrom django.core.exceptions import ValidationError+from django.db.models import Sumfrom django.test import override_settingsfrom django_countries.fields import Countryfrom measurement.measures import Weight@@ -21,7 +22,11 @@ from ....checkout.checkout_cleaner import (clean_checkout_shipping,)from ....checkout.error_codes import CheckoutErrorCode-from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from ....checkout.fetch import (+ fetch_checkout_info,+ fetch_checkout_lines,+ get_delivery_method_info,+)from ....checkout.models import Checkoutfrom ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantityfrom ....core.payments import PaymentInterface@@ -34,12 +39,12 @@ from ....shipping import models as shipping_modelsfrom ....warehouse.models import Stockfrom ...tests.utils import assert_no_permission, get_graphql_contentfrom ..mutations import (- clean_shipping_method,+ clean_delivery_method,update_checkout_shipping_method_if_invalid,)-def test_clean_shipping_method_after_shipping_address_changes_stay_the_same(+def test_clean_delivery_method_after_shipping_address_changes_stay_the_same(checkout_with_single_item, address, shipping_method, other_shipping_method):"""Ensure the current shipping method applies to new address.@@ -53,11 +58,11 @@ def test_clean_shipping_method_after_shipping_address_changes_stay_the_same(manager = get_plugins_manager()lines = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, [], manager)- is_valid_method = clean_shipping_method(checkout_info, lines, shipping_method)+ is_valid_method = clean_delivery_method(checkout_info, lines, shipping_method)assert is_valid_method is True-def test_clean_shipping_method_does_nothing_if_no_shipping_method(+def test_clean_delivery_method_does_nothing_if_no_shipping_method(checkout_with_single_item, address, other_shipping_method):"""If no shipping method was selected, it shouldn't return an error."""@@ -67,7 +72,7 @@ def test_clean_shipping_method_does_nothing_if_no_shipping_method(manager = get_plugins_manager()lines = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, [], manager)- is_valid_method = clean_shipping_method(checkout_info, lines, None)+ is_valid_method = clean_delivery_method(checkout_info, lines, None)assert is_valid_method is True@@ -93,7 +98,7 @@ def test_update_checkout_shipping_method_if_invalid(update_checkout_shipping_method_if_invalid(checkout_info, lines)assert checkout.shipping_method is None- assert checkout_info.shipping_method is None+ assert checkout_info.delivery_method_info.delivery_method is Noneassert checkout_info.shipping_method_channel_listings is None# Ensure the checkout's shipping method was saved@@ -1449,6 +1454,99 @@ def test_checkout_no_available_shipping_methods_without_lines(api_client, checkoassert data["availableShippingMethods"] == []+GET_CHECKOUT_AVAILABLE_COLLECTION_POINTS = """+query getCheckout($token: UUID!) {+ checkout(token: $token) {+ availableCollectionPoints {+ name+ address {+ streetAddress1+ }+ }+ }+}+"""+++def test_checkout_available_collection_points_with_lines_avail_in_1_local_and_1_all(+ api_client, checkout_with_items_for_cc, stocks_for_cc+):+ expected_collection_points = [+ {"address": {"streetAddress1": "Tęczowa 7"}, "name": "Warehouse4"},+ {"address": {"streetAddress1": "Tęczowa 7"}, "name": "Warehouse2"},+ ]++ query = GET_CHECKOUT_AVAILABLE_COLLECTION_POINTS+ variables = {"token": checkout_with_items_for_cc.token}+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ received_collection_points = content["data"]["checkout"][+ "availableCollectionPoints"+ ]++ assert len(received_collection_points) == len(expected_collection_points)+ assert all(c in expected_collection_points for c in received_collection_points)+++def test_checkout_available_collection_points_with_line_avail_in_2_local_and_1_all(+ api_client, checkout_with_item_for_cc, stocks_for_cc+):+ expected_collection_points = [+ {"address": {"streetAddress1": "Tęczowa 7"}, "name": "Warehouse4"},+ {"address": {"streetAddress1": "Tęczowa 7"}, "name": "Warehouse3"},+ {"address": {"streetAddress1": "Tęczowa 7"}, "name": "Warehouse2"},+ ]++ query = GET_CHECKOUT_AVAILABLE_COLLECTION_POINTS+ variables = {"token": checkout_with_item_for_cc.token}+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ received_collection_points = content["data"]["checkout"][+ "availableCollectionPoints"+ ]++ assert len(received_collection_points) == len(expected_collection_points)+ assert all(c in expected_collection_points for c in received_collection_points)+++def test_checkout_avail_collect_points_exceeded_quantity_shows_only_all_warehouse(+ api_client, checkout_with_items_for_cc, stocks_for_cc+):+ query = GET_CHECKOUT_AVAILABLE_COLLECTION_POINTS+ line = checkout_with_items_for_cc.lines.last()+ line.quantity = (+ Stock.objects.filter(product_variant=line.variant)+ .aggregate(total_quantity=Sum("quantity"))+ .get("total_quantity")+ + 1+ )+ line.save(update_fields=["quantity"])+ checkout_with_items_for_cc.refresh_from_db()++ variables = {"token": checkout_with_items_for_cc.token}+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ assert data["availableCollectionPoints"] == [+ {"address": {"streetAddress1": "Tęczowa 7"}, "name": "Warehouse2"}+ ]+++def test_checkout_avail_collect_points_returns_empty_list_when_not_in_shipping_zone(+ api_client, warehouse_for_cc, checkout_with_items_for_cc+):+ query = GET_CHECKOUT_AVAILABLE_COLLECTION_POINTS+ warehouse_for_cc.shipping_zones.filter(name="Poland").delete()++ variables = {"token": checkout_with_items_for_cc.token}+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ assert not data["availableCollectionPoints"]++def test_create_checkout_with_unpublished_product(user_api_client, checkout_with_item, stock, channel_USD):@@ -2278,9 +2376,39 @@ MUTATION_UPDATE_SHIPPING_METHOD = """}"""+MUTATION_UPDATE_DELIVERY_METHOD = """+ mutation checkoutDeliveryMethodUpdate(+ $token: UUID, $deliveryMethodId: ID) {+ checkoutDeliveryMethodUpdate(+ token: $token,+ deliveryMethodId: $deliveryMethodId) {+ checkout {+ id+ deliveryMethod {+ __typename+ ... on ShippingMethod {+ name+ id+ }+ ... on Warehouse {+ name+ id+ }+ }+ }+ errors {+ field+ message+ code+ }+ }+}+"""++# TODO: Deprecated@pytest.mark.parametrize("is_valid_shipping_method", (True, False))-@patch("saleor.graphql.checkout.mutations.clean_shipping_method")+@patch("saleor.graphql.checkout.mutations.clean_delivery_method")def test_checkout_shipping_method_update(mock_clean_shipping,staff_api_client,@@ -2299,13 +2427,14 @@ def test_checkout_shipping_method_update(query, {"token": checkout_with_item.token, "shippingMethodId": method_id})data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]-checkout.refresh_from_db()manager = get_plugins_manager()lines = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, [], manager)- checkout_info.shipping_method = old_shipping_method+ checkout_info.delivery_method_info = get_delivery_method_info(+ old_shipping_method, None+ )checkout_info.shipping_method_channel_listings = Nonemock_clean_shipping.assert_called_once_with(checkout_info=checkout_info, lines=lines, method=shipping_method@@ -2324,6 +2453,123 @@ def test_checkout_shipping_method_update(assert checkout.shipping_method is None[email protected]("is_valid_delivery_method", (True, False))+ "delivery_method, node_name, attribute_name",+ [+ ("warehouse", "Warehouse", "collection_point"),+ ("shipping_method", "ShippingMethod", "shipping_method"),+ ],+ indirect=("delivery_method",),+)+@patch("saleor.graphql.checkout.mutations.clean_delivery_method")+def test_checkout_delivery_method_update(+ mock_clean_delivery,+ api_client,+ delivery_method,+ node_name,+ attribute_name,+ checkout_with_item_for_cc,+ is_valid_delivery_method,+):+ checkout = checkout_with_item_for_cc+ old_delivery_method = getattr(checkout, attribute_name)+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_clean_delivery.return_value = is_valid_delivery_method++ method_id = graphene.Node.to_global_id(node_name, delivery_method.id)++ response = api_client.post_graphql(+ query, {"token": checkout.token, "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]+ checkout.refresh_from_db()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ checkout_info.delivery_method_info = get_delivery_method_info(+ old_delivery_method, None+ )+ checkout_info.shipping_method_channel_listings = None+ mock_clean_delivery.assert_called_once_with(+ checkout_info=checkout_info, lines=lines, method=delivery_method+ )+ errors = data["errors"]+ if is_valid_delivery_method:+ assert not errors+ assert getattr(checkout, attribute_name) == delivery_method+ else:+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert (+ errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name+ )+ assert checkout.shipping_method is None+++@patch("saleor.graphql.checkout.mutations.clean_delivery_method")+def test_checkout_delivery_method_update_with_id_of_different_type_causes_and_error(+ mock_clean_delivery,+ api_client,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_clean_delivery.return_value = True+ invalid_method_id = graphene.Node.to_global_id("Address", address.id)++ response = api_client.post_graphql(+ query,+ {+ "token": checkout.token,+ "deliveryMethodId": invalid_method_id,+ },+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]+ checkout.refresh_from_db()++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert errors[0]["code"] == CheckoutErrorCode.INVALID.name+ assert checkout.shipping_method is None+ assert checkout.collection_point is None+++@patch("saleor.graphql.checkout.mutations.clean_delivery_method")+def test_checkout_delivery_method_with_empty_fields_results_None(+ mock_clean_delivery,+ api_client,+ warehouse_for_cc,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_clean_delivery.return_value = True++ response = api_client.post_graphql(+ query,+ {+ "token": checkout.token,+ },+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]+ checkout.refresh_from_db()++ assert not data["errors"]+ assert data["checkout"]["deliveryMethod"] is None+ assert checkout.shipping_method is None+ assert checkout.collection_point is None+++# Deprecated@patch("saleor.shipping.postal_codes.is_shipping_method_applicable_for_postal_code")def test_checkout_shipping_method_update_excluded_postal_code(mock_is_shipping_method_available,@@ -2358,6 +2604,41 @@ def test_checkout_shipping_method_update_excluded_postal_code()+@patch("saleor.shipping.postal_codes.is_shipping_method_applicable_for_postal_code")+def test_checkout_delivery_method_update_excluded_postal_code(+ mock_is_shipping_method_available,+ staff_api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_is_shipping_method_available.return_value = False++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query, {"token": checkout.token, "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]++ checkout.refresh_from_db()++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name+ assert checkout.shipping_method is None+ assert (+ mock_is_shipping_method_available.call_count+ == shipping_models.ShippingMethod.objects.count()+ )+++# Deprecateddef test_checkout_shipping_method_update_shipping_zone_without_channel(staff_api_client,shipping_method,@@ -2386,6 +2667,35 @@ def test_checkout_shipping_method_update_shipping_zone_without_channel(assert checkout.shipping_method is None+def test_checkout_delivery_method_update_shipping_zone_without_channel(+ api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ shipping_method.shipping_zone.channels.clear()+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = api_client.post_graphql(+ query, {"token": checkout.token, "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]++ checkout.refresh_from_db()++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name+ assert checkout.shipping_method is None+++# Deprecateddef test_checkout_shipping_method_update_shipping_zone_with_channel(staff_api_client,shipping_method,@@ -2414,6 +2724,33 @@ def test_checkout_shipping_method_update_shipping_zone_with_channel(assert checkout.shipping_method == shipping_method+def test_checkout_delivery_method_update_shipping_zone_with_channel(+ staff_api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query, {"token": checkout.token, "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]++ checkout.refresh_from_db()++ checkout.refresh_from_db()+ errors = data["errors"]+ assert not errors++ assert checkout.shipping_method == shipping_method++def test_query_checkouts(checkout_with_item, staff_api_client, permission_manage_checkouts):@@ -2581,7 +2918,7 @@ def test_clean_checkout_invalid_shipping_method(with pytest.raises(ValidationError) as e:clean_checkout_shipping(checkout_info, lines, CheckoutErrorCode)- msg = "Shipping method is not valid for your shipping address"+ msg = "Delivery method is not valid for your shipping address"assert e.value.error_dict["shipping_method"][0].message == msgdiff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex 55a372b352..5af047176c 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -4,20 +4,21 @@ from unittest.mock import ANY, patchimport grapheneimport pytest+from django.db.models.aggregates import Sumfrom ....checkout import calculationsfrom ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.models import Checkoutfrom ....core.exceptions import InsufficientStock, InsufficientStockData-from ....core.taxes import zero_money+from ....core.taxes import zero_money, zero_taxed_moneyfrom ....order import OrderOrigin, OrderStatusfrom ....order.models import Orderfrom ....payment import ChargeStatus, PaymentError, TransactionKindfrom ....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPINGfrom ....payment.interface import GatewayResponsefrom ....plugins.manager import PluginsManager, get_plugins_manager-from ....warehouse.models import Stock+from ....warehouse.models import Stock, WarehouseClickAndCollectOptionfrom ....warehouse.tests.utils import get_available_quantity_for_stockfrom ...tests.utils import get_graphql_content@@ -1188,3 +1189,241 @@ def test_checkout_complete_0_total_value(assert not Checkout.objects.filter(pk=checkout.pk).exists(), "Checkout should have been deleted"+++def test_complete_checkout_for_click_and_collect(+ api_client, checkout_for_cc, payment_dummy, address, warehouse_for_cc+):+ order_count = Order.objects.count()+ checkout = checkout_for_cc+ variables = {"token": checkout.token, "redirectUrl": "https://www.example.com"}++ checkout.billing_address = address+ checkout.collection_point = warehouse_for_cc++ checkout.save(+ update_fields=["shipping_address", "billing_address", "collection_point"]+ )++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.checkout_total(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()++ assert not payment.transactions.exists()++ response = api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)["data"]["checkoutComplete"]++ assert not content["errors"]+ assert Order.objects.count() == order_count + 1++ order = Order.objects.first()++ assert order.collection_point == warehouse_for_cc+ assert order.shipping_method is None+ assert order.shipping_address == warehouse_for_cc.address+ assert order.shipping_price == zero_taxed_money(payment.currency)+++def test_complete_checkout_raises_ValidationError_for_local_stock(+ api_client, checkout_with_items_for_cc, payment_dummy, address, warehouse_for_cc+):+ initial_order_count = Order.objects.count()+ checkout = checkout_with_items_for_cc+ checkout_line = checkout.lines.first()+ stock = Stock.objects.get(product_variant=checkout_line.variant)+ quantity_available = get_available_quantity_for_stock(stock)+ checkout_line.quantity = quantity_available + 1+ checkout_line.save()++ variables = {"token": checkout.token, "rediirectUrl": "https://www.example.com"}++ checkout.collection_point = warehouse_for_cc+ checkout.billing_address = address+ checkout.save(+ update_fields=["collection_point", "shipping_address", "billing_address"]+ )++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.checkout_total(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()++ assert not payment.transactions.exists()++ response = api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)["data"]["checkoutComplete"]+ assert content["errors"][0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert Order.objects.count() == initial_order_count+++def test_comp_checkout_builds_order_for_ALL_warehouse_even_if_not_available_locally(+ stocks_for_cc,+ warehouse_for_cc,+ checkout_with_items_for_cc,+ address,+ api_client,+ payment_dummy,+):+ initial_order_count = Order.objects.count()+ checkout = checkout_with_items_for_cc+ checkout_line = checkout.lines.first()+ stock = Stock.objects.get(+ product_variant=checkout_line.variant, warehouse=warehouse_for_cc+ )+ quantity_available = get_available_quantity_for_stock(stock)+ checkout_line.quantity = quantity_available + 1+ checkout_line.save()++ warehouse_for_cc.click_and_collect_option = (+ WarehouseClickAndCollectOption.ALL_WAREHOUSES+ )+ warehouse_for_cc.save()++ variables = {"token": checkout.token, "rediirectUrl": "https://www.example.com"}++ checkout.collection_point = warehouse_for_cc+ checkout.save(update_fields=["collection_point"])++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.checkout_total(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()++ assert not payment.transactions.exists()++ response = api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)["data"]["checkoutComplete"]+ assert not content["errors"]+ assert Order.objects.count() == initial_order_count + 1+++def test_checkout_complete_raises_InsufficientStock_when_quantity_above_stock_sum(+ stocks_for_cc,+ warehouse_for_cc,+ checkout_with_items_for_cc,+ address,+ api_client,+ payment_dummy,+):+ initial_order_count = Order.objects.count()+ checkout = checkout_with_items_for_cc+ checkout_line = checkout.lines.first()+ overall_stock_quantity = (+ Stock.objects.filter(product_variant=checkout_line.variant).aggregate(+ Sum("quantity")+ )+ ).pop("quantity__sum")+ checkout_line.quantity = overall_stock_quantity + 1+ checkout_line.save()+ warehouse_for_cc.click_and_collect_option = (+ WarehouseClickAndCollectOption.ALL_WAREHOUSES+ )+ warehouse_for_cc.save()++ variables = {"token": checkout.token, "rediirectUrl": "https://www.example.com"}++ checkout.collection_point = warehouse_for_cc+ checkout.billing_address = address+ checkout.save(update_fields=["collection_point", "billing_address"])++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.checkout_total(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()++ assert not payment.transactions.exists()++ response = api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)["data"]["checkoutComplete"]+ assert content["errors"][0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert Order.objects.count() == initial_order_count+++def test_checkout_complete_raises_InvalidShippingMethod_when_warehouse_disabled(+ warehouse_for_cc,+ checkout_with_items_for_cc,+ address,+ api_client,+ payment_dummy,+):+ initial_order_count = Order.objects.count()+ checkout = checkout_with_items_for_cc+ variables = {"token": checkout.token, "redirectUrl": "https://www.example.com"}++ checkout.billing_address = address+ checkout.collection_point = warehouse_for_cc++ checkout.save(+ update_fields=["shipping_address", "billing_address", "collection_point"]+ )++ warehouse_for_cc.click_and_collect_option = WarehouseClickAndCollectOption.DISABLED+ warehouse_for_cc.save()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.checkout_total(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )++ assert not checkout_info.valid_pick_up_points+ assert not checkout_info.delivery_method_info.is_method_in_valid_methods(+ checkout_info+ )++ 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()++ response = api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)["data"]["checkoutComplete"]++ assert (+ content["errors"][0]["code"] == CheckoutErrorCode.INVALID_SHIPPING_METHOD.name+ )+ assert Order.objects.count() == initial_order_countdiff --git a/saleor/graphql/checkout/tests/test_checkout_lines.py b/saleor/graphql/checkout/tests/test_checkout_lines.pyindex e02cf40eb9..15ac368eac 100644--- a/saleor/graphql/checkout/tests/test_checkout_lines.py+++ b/saleor/graphql/checkout/tests/test_checkout_lines.py@@ -3,12 +3,14 @@ import uuidfrom unittest import mockimport graphene+import pytestfrom ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.utils import calculate_checkout_quantityfrom ....plugins.manager import get_plugins_managerfrom ....product.models import ProductChannelListing+from ....warehouse import WarehouseClickAndCollectOptionfrom ...tests.utils import get_graphql_contentfrom ..mutations import update_checkout_shipping_method_if_invalid@@ -135,6 +137,40 @@ def test_checkout_lines_add_with_insufficient_stock(assert errors[0]["field"] == "quantity"+ "cc_option",+ [+ WarehouseClickAndCollectOption.ALL_WAREHOUSES,+ WarehouseClickAndCollectOption.LOCAL_STOCK,+ ],+)+def test_checkout_lines_for_click_and_collect_insufficient_stock(+ user_api_client, checkout_with_item_for_cc, warehouse_for_cc, cc_option+):+ checkout = checkout_with_item_for_cc+ checkout.collection_point = warehouse_for_cc++ warehouse_for_cc.click_and_collect_option = cc_option+ warehouse_for_cc.save(update_fields=["click_and_collect_option"])+ checkout.refresh_from_db()++ variant = checkout.lines.last().variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "token": checkout.token,+ "lines": [{"variantId": variant_id, "quantity": 42}],+ "channelSlug": checkout.channel.slug,+ }++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesAdd"]["errors"]++ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"++def test_checkout_lines_add_with_zero_quantity(user_api_client, checkout_with_item, stock):diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 3cf9619c02..9700d8e224 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -2,7 +2,10 @@ import graphenefrom promise import Promisefrom ...checkout import calculations, models-from ...checkout.utils import get_valid_shipping_methods_for_checkout+from ...checkout.utils import (+ get_valid_collection_points_for_checkout,+ get_valid_shipping_methods_for_checkout,+)from ...core.exceptions import PermissionDeniedfrom ...core.permissions import AccountPermissionsfrom ...core.taxes import zero_taxed_money@@ -12,6 +15,7 @@ from ..account.utils import requestor_has_accessfrom ..channel import ChannelContextfrom ..channel.dataloaders import ChannelByCheckoutLineIDLoader, ChannelByIdLoaderfrom ..core.connection import CountableDjangoObjectType+from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELDfrom ..core.enums import LanguageCodeEnumfrom ..core.scalars import UUIDfrom ..core.types.money import TaxedMoney@@ -30,6 +34,8 @@ from ..shipping.dataloaders import ()from ..shipping.types import ShippingMethodfrom ..utils import get_user_or_app_from_context+from ..warehouse.dataloaders import WarehouseByIdLoader+from ..warehouse.types import Warehousefrom .dataloaders import (CheckoutByTokenLoader,CheckoutInfoByCheckoutTokenLoader,@@ -154,12 +160,33 @@ class CheckoutLine(CountableDjangoObjectType):)+class DeliveryMethod(graphene.Union):+ class Meta:+ description = (+ "Represents a delivery method chosen for the checkout. `Warehouse` "+ 'type is used when checkout is marked as "click and collect" and '+ "`ShippingMethod` otherwise."+ )+ types = (Warehouse, ShippingMethod)++ @classmethod+ def resolve_type(cls, instance, info):+ if isinstance(instance, ChannelContext):+ return ShippingMethod+ return super(DeliveryMethod, cls).resolve_type(instance, info)++class Checkout(CountableDjangoObjectType):available_shipping_methods = graphene.List(ShippingMethod,required=True,description="Shipping methods that can be used with this order.",)+ available_collection_points = graphene.List(+ graphene.NonNull(Warehouse),+ required=True,+ description=f"{ADDED_IN_31} Collection points that can be used for this order.",+ )available_payment_gateways = graphene.List(graphene.NonNull(PaymentGateway),description="List of available payment gateways.",@@ -187,7 +214,14 @@ class Checkout(CountableDjangoObjectType):shipping_method = graphene.Field(ShippingMethod,description="The shipping method related with checkout.",+ deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Use `deliveryMethod` instead."),+ )++ delivery_method = graphene.Field(+ DeliveryMethod,+ description=f"{ADDED_IN_31} The delivery method selected for this checkout.",)+subtotal_price = graphene.Field(TaxedMoney,description="The price of the checkout before shipping, with taxes included.",@@ -266,6 +300,14 @@ class Checkout(CountableDjangoObjectType):wrap_shipping_method_with_channel_context)+ @staticmethod+ def resolve_delivery_method(root: models.Checkout, info):+ if root.shipping_method_id:+ return Checkout.resolve_shipping_method(root, info)+ if root.collection_point_id:+ return WarehouseByIdLoader(info.context).load(root.collection_point_id)+ return None+@staticmethoddef resolve_quantity(root: models.Checkout, info):checkout_info = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(@@ -445,6 +487,27 @@ class Checkout(CountableDjangoObjectType):calculate_available_shipping_methods)+ @staticmethod+ @traced_resolver+ def resolve_available_collection_points(root: models.Checkout, info):+ def get_available_collection_points(data):+ address, lines, checkout_info = data+ return get_valid_collection_points_for_checkout(+ lines, checkout_info, country_code=address.country.code+ )++ lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token)+ checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(root.token)+ address = (+ AddressByIdLoader(info.context).load(root.shipping_address_id)+ if root.shipping_address_id+ else None+ )++ return Promise.all([address, lines, checkout_info]).then(+ get_available_collection_points+ )+@staticmethoddef resolve_available_payment_gateways(root: models.Checkout, info):return info.context.plugins.list_payment_gateways(diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 8a09b319ac..fe93303611 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -32,7 +32,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+from ....warehouse.models import Allocation, Stock, Warehousefrom ....warehouse.tests.utils import get_available_quantity_for_stockfrom ...order.mutations.orders import (clean_order_cancel,@@ -332,9 +332,22 @@ query OrdersQuery {}type}+ availableCollectionPoints {+ id+ name+ }shippingMethod{id}+ deliveryMethod {+ __typename+ ... on ShippingMethod {+ id+ }+ ... on Warehouse {+ id+ }+ }}}}@@ -394,18 +407,27 @@ def test_order_query(country_code=order.shipping_address.country.code,channel_id=order.channel_id,)+ expected_collection_points = Warehouse.objects.applicable_for_click_and_collect(+ lines_qs=order.lines, country=order.shipping_address.country.code+ )+assert len(order_data["availableShippingMethods"]) == (expected_methods.count())+ assert len(order_data["availableCollectionPoints"]) == (+ expected_collection_points.count()+ )method = order_data["availableShippingMethods"][0]expected_method = expected_methods.first()expected_shipping_price = expected_method.channel_listings.get(channel_id=order.channel_id)+assert float(expected_shipping_price.price.amount) == method["price"]["amount"]assert float(expected_shipping_price.minimum_order_price.amount) == (method["minimumOrderPrice"]["amount"])assert expected_method.type.upper() == method["type"]+ assert order_data["deliveryMethod"]["id"] == order_data["shippingMethod"]["id"]def test_order_query_shipping_method_channel_listing_does_not_exist(diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex a3aaf9b0d9..418e133b6c 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -1,6 +1,7 @@from decimal import Decimalfrom operator import attrgetterfrom typing import Optional+from uuid import UUIDimport grapheneimport prices@@ -21,11 +22,16 @@ from ...core.permissions import (from ...core.taxes import display_gross_pricesfrom ...core.tracing import traced_resolverfrom ...discount import OrderDiscountType+from ...graphql.checkout.types import DeliveryMethodfrom ...graphql.utils import get_user_or_app_from_contextfrom ...graphql.warehouse.dataloaders import WarehouseByIdLoaderfrom ...order import OrderStatus, modelsfrom ...order.models import FulfillmentStatus-from ...order.utils import get_order_country, get_valid_shipping_methods_for_order+from ...order.utils import (+ get_order_country,+ get_valid_collection_points_for_order,+ get_valid_shipping_methods_for_order,+)from ...payment import ChargeStatusfrom ...payment.dataloaders import PaymentsByOrderIdLoaderfrom ...payment.model_helpers import (@@ -315,7 +321,7 @@ class OrderEvent(CountableDjangoObjectType):@staticmethoddef resolve_warehouse(root: models.OrderEvent, info):if warehouse_pk := root.parameters.get("warehouse"):- return WarehouseByIdLoader(info.context).load(warehouse_pk)+ return WarehouseByIdLoader(info.context).load(UUID(warehouse_pk))return None@staticmethod@@ -614,6 +620,11 @@ class Order(CountableDjangoObjectType):required=False,description="Shipping methods that can be used with this order.",)+ available_collection_points = graphene.List(+ graphene.NonNull(Warehouse),+ required=True,+ description=f"{ADDED_IN_31} Collection points that can be used for this order.",+ )invoices = graphene.List(Invoice, required=False, description="List of order invoices.")@@ -638,6 +649,13 @@ class Order(CountableDjangoObjectType):undiscounted_total = graphene.Field(TaxedMoney, description="Undiscounted total amount of the order.", required=True)++ shipping_method = graphene.Field(+ ShippingMethod,+ description="The shipping method related with order.",+ deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} Use `deliveryMethod` instead."),+ )+shipping_price = graphene.Field(TaxedMoney, description="Total price of shipping.", required=True)@@ -675,6 +693,10 @@ class Order(CountableDjangoObjectType):is_shipping_required = graphene.Boolean(description="Returns True, if order requires shipping.", required=True)+ delivery_method = graphene.Field(+ DeliveryMethod,+ description=f"{ADDED_IN_31} The delivery method selected for this checkout.",+ )language_code = graphene.String(deprecation_reason=(f"{DEPRECATED_IN_3X_FIELD} "@@ -727,8 +749,8 @@ class Order(CountableDjangoObjectType):"gift_cards","id","shipping_address",- "shipping_method","shipping_method_name",+ "collection_point_name","shipping_price","shipping_tax_rate","status",@@ -1041,6 +1063,17 @@ class Order(CountableDjangoObjectType):wrap_shipping_method_with_channel_context)+ @classmethod+ def resolve_delivery_method(cls, root: models.Order, info):+ if root.shipping_method_id:+ return cls.resolve_shipping_method(root, info)+ if root.collection_point_id:+ collection_point = WarehouseByIdLoader(info.context).load(+ root.collection_point_id+ )+ return collection_point+ return None+@staticmethod@traced_resolver# TODO: We should optimize it in/after PR#5819@@ -1076,6 +1109,18 @@ class Order(CountableDjangoObjectType):return instances+ @classmethod+ @traced_resolver+ def resolve_available_collection_points(cls, root: models.Order, info):+ def get_available_collection_points(data):+ lines, address = data++ return get_valid_collection_points_for_order(lines, address)++ lines = cls.resolve_lines(root, info)+ address = cls.resolve_shipping_address(root, info)+ return Promise.all([lines, address]).then(get_available_collection_points)+@staticmethoddef resolve_invoices(root: models.Order, info):requester = get_user_or_app_from_context(info.context)diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.pyindex 418b168549..58dba8a6aa 100644--- a/saleor/graphql/product/tests/test_bulk_delete.py+++ b/saleor/graphql/product/tests/test_bulk_delete.py@@ -837,7 +837,7 @@ def test_delete_product_variants(content = get_graphql_content(response)flush_post_commit_hooks()- assert content["data"]["productVariantBulkDelete"]["count"] == 3+ assert content["data"]["productVariantBulkDelete"]["count"] == 4assert not ProductVariant.objects.filter(id__in=[variant.id for variant in product_variant_list]).exists()@@ -955,7 +955,7 @@ def test_delete_product_variants_with_images(content = get_graphql_content(response)flush_post_commit_hooks()- assert content["data"]["productVariantBulkDelete"]["count"] == 3+ assert content["data"]["productVariantBulkDelete"]["count"] == 4assert not ProductVariant.objects.filter(id__in=[variant.id for variant in product_variant_list]).exists()@@ -1004,7 +1004,7 @@ def test_delete_product_variants_with_file_attribute(content = get_graphql_content(response)flush_post_commit_hooks()- assert content["data"]["productVariantBulkDelete"]["count"] == 3+ assert content["data"]["productVariantBulkDelete"]["count"] == 4assert not ProductVariant.objects.filter(id__in=[variant.id for variant in product_variant_list]).exists()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 55e3634445..9392e2fbd3 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -997,13 +997,15 @@ type Checkout implements Node & ObjectWithMetadata {privateMetadata: [MetadataItem]!metadata: [MetadataItem]!availableShippingMethods: [ShippingMethod]!+ availableCollectionPoints: [Warehouse!]!availablePaymentGateways: [PaymentGateway!]!email: String!isShippingRequired: Boolean!quantity: Int!lines: [CheckoutLine]shippingPrice: TaxedMoney- shippingMethod: ShippingMethod+ shippingMethod: ShippingMethod @deprecated(reason: "This field will be removed in Saleor 4.0. Use `deliveryMethod` instead.")+ deliveryMethod: DeliveryMethodsubtotalPrice: TaxedMoneytoken: UUID!totalPrice: TaxedMoney@@ -1069,6 +1071,11 @@ type CheckoutCustomerDetach {errors: [CheckoutError!]!}+type CheckoutDeliveryMethodUpdate {+ checkout: Checkout+ errors: [CheckoutError!]!+}+type CheckoutEmailUpdate {checkout: CheckoutcheckoutErrors: [CheckoutError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")@@ -1098,6 +1105,7 @@ enum CheckoutErrorCode {REQUIREDSHIPPING_ADDRESS_NOT_SETSHIPPING_METHOD_NOT_APPLICABLE+ DELIVERY_METHOD_NOT_APPLICABLESHIPPING_METHOD_NOT_SETSHIPPING_NOT_REQUIREDTAX_ERROR@@ -1789,6 +1797,8 @@ type DeletePrivateMetadata {item: ObjectWithMetadata}+union DeliveryMethod = Warehouse | ShippingMethod+type DigitalContent implements Node & ObjectWithMetadata {useDefaultSettings: Boolean!automaticFulfillment: Boolean!@@ -3782,7 +3792,8 @@ type Mutation {checkoutRemovePromoCode(checkoutId: ID, promoCode: String!, token: UUID): CheckoutRemovePromoCodecheckoutPaymentCreate(checkoutId: ID, input: PaymentInput!, token: UUID): CheckoutPaymentCreatecheckoutShippingAddressUpdate(checkoutId: ID, shippingAddress: AddressInput!, token: UUID): CheckoutShippingAddressUpdate- checkoutShippingMethodUpdate(checkoutId: ID, shippingMethodId: ID!, token: UUID): CheckoutShippingMethodUpdate+ checkoutShippingMethodUpdate(checkoutId: ID, shippingMethodId: ID!, token: UUID): CheckoutShippingMethodUpdate @deprecated(reason: "This field will be removed in Saleor 4.0. Use `checkoutDeliveryMethodUpdate` instead.")+ checkoutDeliveryMethodUpdate(deliveryMethodId: ID, token: UUID): CheckoutDeliveryMethodUpdatecheckoutLanguageCodeUpdate(checkoutId: ID, languageCode: LanguageCodeEnum!, token: UUID): CheckoutLanguageCodeUpdatechannelCreate(input: ChannelCreateInput!): ChannelCreatechannelUpdate(id: ID!, input: ChannelUpdateInput!): ChannelUpdate@@ -3881,8 +3892,8 @@ type Order implements Node & ObjectWithMetadata {trackingClientId: String!billingAddress: AddressshippingAddress: Address- shippingMethod: ShippingMethodshippingMethodName: String+ collectionPointName: Stringchannel: Channel!shippingPrice: TaxedMoney!shippingTaxRate: Float!@@ -3899,6 +3910,7 @@ type Order implements Node & ObjectWithMetadata {lines: [OrderLine]!actions: [OrderAction]!availableShippingMethods: [ShippingMethod]+ availableCollectionPoints: [Warehouse!]!invoices: [Invoice]number: Stringoriginal: ID@@ -3909,6 +3921,7 @@ type Order implements Node & ObjectWithMetadata {payments: [Payment]total: TaxedMoney!undiscountedTotal: TaxedMoney!+ shippingMethod: ShippingMethod @deprecated(reason: "This field will be removed in Saleor 4.0. Use `deliveryMethod` instead.")subtotal: TaxedMoney!statusDisplay: StringcanFinalize: Boolean!@@ -3918,6 +3931,7 @@ type Order implements Node & ObjectWithMetadata {totalBalance: Money!userEmail: StringisShippingRequired: Boolean!+ deliveryMethod: DeliveryMethodlanguageCode: String! @deprecated(reason: "This field will be removed in Saleor 4.0. Use the `languageCodeEnum` field to fetch the language code. ")languageCodeEnum: LanguageCodeEnum!discount: Money @deprecated(reason: "This field will be removed in Saleor 4.0. Use discounts field.")@@ -6865,9 +6879,17 @@ type Warehouse implements Node & ObjectWithMetadata {shippingZones(before: String, after: String, first: Int, last: Int): ShippingZoneCountableConnection!address: Address!email: String!+ isPrivate: Boolean!privateMetadata: [MetadataItem]!metadata: [MetadataItem]!companyName: String! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `Address.companyName` instead.")+ clickAndCollectOption: WarehouseClickAndCollectOptionEnum!+}++enum WarehouseClickAndCollectOptionEnum {+ DISABLED+ LOCAL+ ALL}type WarehouseCountableConnection {@@ -6917,8 +6939,10 @@ enum WarehouseErrorCode {}input WarehouseFilterInput {+ clickAndCollectOption: WarehouseClickAndCollectOptionEnumsearch: Stringids: [ID]+ isPrivate: Boolean}type WarehouseShippingZoneAssign {@@ -6953,6 +6977,8 @@ input WarehouseUpdateInput {email: Stringname: Stringaddress: AddressInput+ clickAndCollectOption: WarehouseClickAndCollectOptionEnum+ isPrivate: Boolean}type Webhook implements Node {diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.pyindex 2d5c913a5a..6b58a18238 100644--- a/saleor/graphql/translations/types.py+++ b/saleor/graphql/translations/types.py@@ -43,7 +43,7 @@ def get_translatable_attribute_values(attributes: list) -> List[AttributeValue]:Return those which are translatable attributes."""- translatable_values = []+ translatable_values: List[AttributeValue] = []for assignment in attributes:attr = assignment["attribute"]if attr.input_type in AttributeInputType.TRANSLATABLE_ATTRIBUTES:diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex 2868137dfe..729f2e7d9e 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -209,6 +209,6 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(class WarehouseByIdLoader(DataLoader):context_key = "warehouse_by_id"- def batch_load(self, keys):+ def batch_load(self, keys: Iterable[UUID]) -> List[Optional[Warehouse]]:warehouses = Warehouse.objects.in_bulk(keys)- return [warehouses.get(UUID(warehouse_uuid)) for warehouse_uuid in keys]+ return [warehouses.get(warehouse_uuid) for warehouse_uuid in keys]diff --git a/saleor/graphql/warehouse/enums.py b/saleor/graphql/warehouse/enums.pynew file mode 100644index 0000000000..f800e0ef3f--- /dev/null+++ b/saleor/graphql/warehouse/enums.py@@ -0,0 +1,6 @@+from ...graphql.core.enums import to_enum+from ...warehouse import WarehouseClickAndCollectOption++WarehouseClickAndCollectOptionEnum = to_enum(+ WarehouseClickAndCollectOption, type_name="WarehouseClickAndCollectOptionEnum"+)diff --git a/saleor/graphql/warehouse/filters.py b/saleor/graphql/warehouse/filters.pyindex 30a1d5dc93..aebf4a6fb9 100644--- a/saleor/graphql/warehouse/filters.py+++ b/saleor/graphql/warehouse/filters.py@@ -1,9 +1,12 @@import django_filtersfrom graphene_django.filter import GlobalIDMultipleChoiceFilter+from ...warehouse import WarehouseClickAndCollectOptionfrom ...warehouse.models import Stock, Warehouse+from ..core.filters import EnumFilterfrom ..core.types import FilterInputObjectTypefrom ..utils.filters import filter_by_query_param+from ..warehouse.enums import WarehouseClickAndCollectOptionEnumdef prefech_qs_for_filter(qs):@@ -28,6 +31,20 @@ def filter_search_warehouse(qs, _, value):return qs+def filter_click_and_collect_option(qs, _, value):+ if value == WarehouseClickAndCollectOptionEnum.LOCAL.value:+ qs = qs.filter(+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK+ )+ elif value == WarehouseClickAndCollectOptionEnum.ALL.value:+ qs = qs.filter(+ click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES+ )+ elif value == WarehouseClickAndCollectOptionEnum.DISABLED.value:+ qs = qs.filter(click_and_collect_option=WarehouseClickAndCollectOption.DISABLED)+ return qs++def filter_search_stock(qs, _, value):search_fields = ["product_variant__product__name",@@ -46,10 +63,15 @@ def filter_search_stock(qs, _, value):class WarehouseFilter(django_filters.FilterSet):search = django_filters.CharFilter(method=filter_search_warehouse)ids = GlobalIDMultipleChoiceFilter(field_name="id")+ is_private = django_filters.BooleanFilter(field_name="is_private")+ click_and_collect_option = EnumFilter(+ input_class=WarehouseClickAndCollectOptionEnum,+ method=filter_click_and_collect_option,+ )class Meta:model = Warehouse- fields = []+ fields = ["click_and_collect_option"]class WarehouseFilterInput(FilterInputObjectType):diff --git a/saleor/graphql/warehouse/mutations.py b/saleor/graphql/warehouse/mutations.pyindex 41aae6bfda..89fc9a0dc3 100644--- a/saleor/graphql/warehouse/mutations.py+++ b/saleor/graphql/warehouse/mutations.py@@ -4,7 +4,7 @@ from django.db import transactionfrom ...core.permissions import ProductPermissionsfrom ...core.tracing import traced_atomic_transaction-from ...warehouse import models+from ...warehouse import WarehouseClickAndCollectOption, modelsfrom ...warehouse.error_codes import WarehouseErrorCodefrom ...warehouse.validation import validate_warehouse_count # type: ignorefrom ..account.i18n import I18nMixin@@ -54,6 +54,23 @@ class WarehouseMixin:raise ValidationError({"shipping_zones": msg}, code=WarehouseErrorCode.INVALID)++ click_and_collect_option = cleaned_input.get(+ "click_and_collect_option", instance.click_and_collect_option+ )+ is_private = cleaned_input.get("is_private", instance.is_private)+ if (+ click_and_collect_option == WarehouseClickAndCollectOption.LOCAL_STOCK+ and is_private+ ):+ msg = "Local warehouse can be toggled only for non-private warehouse stocks"+ raise ValidationError(+ {+ "click_and_collect_option": ValidationError(+ msg, code=WarehouseErrorCode.INVALID.value+ )+ },+ )return cleaned_input@classmethoddiff --git a/saleor/graphql/warehouse/tests/test_warehouse.py b/saleor/graphql/warehouse/tests/test_warehouse.pyindex 66af168cf1..123a37b602 100644--- a/saleor/graphql/warehouse/tests/test_warehouse.py+++ b/saleor/graphql/warehouse/tests/test_warehouse.py@@ -4,6 +4,7 @@ import grapheneimport pytestfrom ....account.models import Address+from ....warehouse import WarehouseClickAndCollectOptionfrom ....warehouse.error_codes import WarehouseErrorCodefrom ....warehouse.models import Stock, Warehousefrom ...tests.utils import (@@ -11,6 +12,7 @@ from ...tests.utils import (get_graphql_content,get_graphql_content_from_response,)+from ..enums import WarehouseClickAndCollectOptionEnumQUERY_WAREHOUSES = """query {@@ -140,6 +142,8 @@ mutation updateWarehouse($input: WarehouseUpdateInput!, $id: ID!) {nameslugcompanyName+ isPrivate+ clickAndCollectOptionaddress {idstreetAddress1@@ -481,6 +485,54 @@ def test_query_warehouse_with_filters_by_id(assert content_exists["data"]["warehouses"]["totalCount"] == 1+ "graphql_filter, db_filter", [("true", True), ("false", False)]+)+def test_query_warehouse_with_filters_by_is_private(+ staff_api_client,+ permission_manage_products,+ warehouses_for_cc,+ graphql_filter,+ db_filter,+):+ db_count = Warehouse.objects.filter(is_private=db_filter).count()+ variables_exists = {"filters": {"isPrivate": graphql_filter}}+ response_exists = staff_api_client.post_graphql(+ QUERY_WAREHOUSES_WITH_FILTERS,+ variables=variables_exists,+ permissions=[permission_manage_products],+ )+ content_exists = get_graphql_content(response_exists)++ assert content_exists["data"]["warehouses"]["totalCount"] == db_count+++ "db_option, graphql_option",+ [+ (WarehouseClickAndCollectOption.DISABLED, "DISABLED"),+ (WarehouseClickAndCollectOption.ALL_WAREHOUSES, "ALL"),+ (WarehouseClickAndCollectOption.LOCAL_STOCK, "LOCAL"),+ ],+)+def test_query_warehouse_with_filters_by_click_and_collect_option(+ staff_api_client,+ permission_manage_products,+ warehouses_for_cc,+ db_option,+ graphql_option,+):+ db_count = Warehouse.objects.filter(click_and_collect_option=db_option).count()+ variables_exists = {"filters": {"clickAndCollectOption": graphql_option}}+ response_exists = staff_api_client.post_graphql(+ QUERY_WAREHOUSES_WITH_FILTERS,+ variables=variables_exists,+ permissions=[permission_manage_products],+ )+ content_exists = get_graphql_content(response_exists)+ assert content_exists["data"]["warehouses"]["totalCount"] == db_count++def test_query_warehouses_with_filters_and_no_id(staff_api_client, permission_manage_products, warehouse):@@ -827,6 +879,92 @@ def test_update_warehouse_slug_and_name(assert errors[0]["code"] == WarehouseErrorCode.REQUIRED.name+ "expected_private, expected_cc_option",+ [+ (private, option)+ for private in (True, False)+ for option in [+ WarehouseClickAndCollectOptionEnum.ALL.name,+ WarehouseClickAndCollectOptionEnum.DISABLED.name,+ ]+ ]+ + [(False, WarehouseClickAndCollectOptionEnum.LOCAL.name)],+)+def test_update_click_and_collect_option(+ staff_api_client,+ warehouse,+ permission_manage_products,+ expected_private,+ expected_cc_option,+):+ query = MUTATION_UPDATE_WAREHOUSE++ assert warehouse.is_private+ assert warehouse.click_and_collect_option == WarehouseClickAndCollectOption.DISABLED++ node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)+ variables = {+ "input": {+ "isPrivate": expected_private,+ "clickAndCollectOption": expected_cc_option,+ },+ "id": node_id,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ warehouse.refresh_from_db()+ data = content["data"]["updateWarehouse"]+ errors = data["errors"]++ assert not errors+ assert data["warehouse"]["isPrivate"] == expected_private == warehouse.is_private+ assert (+ data["warehouse"]["clickAndCollectOption"]+ == expected_cc_option+ == warehouse.click_and_collect_option.upper()+ )+++def test_update_click_and_collect_option_invalid_input(+ staff_api_client, warehouse, permission_manage_products+):+ query = MUTATION_UPDATE_WAREHOUSE++ warehouse_is_private = warehouse.is_private+ warehouse_click_and_collect = warehouse.click_and_collect_option+ assert warehouse_is_private+ assert warehouse_click_and_collect == WarehouseClickAndCollectOption.DISABLED++ node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)+ variables = {+ "input": {+ "isPrivate": True,+ "clickAndCollectOption": WarehouseClickAndCollectOptionEnum.LOCAL.name,+ },+ "id": node_id,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)+ warehouse.refresh_from_db()+ data = content["data"]["updateWarehouse"]+ errors = data["errors"]++ assert len(errors) == 1+ assert (+ errors[0]["message"]+ == "Local warehouse can be toggled only for non-private warehouse stocks"+ )+ assert errors[0]["field"] == "clickAndCollectOption"++ assert warehouse.is_private == warehouse_is_private+ assert warehouse.click_and_collect_option == warehouse_click_and_collect++def test_delete_warehouse_mutation(staff_api_client, warehouse, permission_manage_products):diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.pyindex 38ef3333f8..2e3e650175 100644--- a/saleor/graphql/warehouse/types.py+++ b/saleor/graphql/warehouse/types.py@@ -7,9 +7,10 @@ from ...warehouse import modelsfrom ..account.dataloaders import AddressByIdLoaderfrom ..channel import ChannelContextfrom ..core.connection import CountableDjangoObjectType-from ..core.descriptions import DEPRECATED_IN_3X_FIELD+from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELDfrom ..decorators import one_of_permissions_requiredfrom ..meta.types import ObjectWithMetadata+from .enums import WarehouseClickAndCollectOptionEnumclass WarehouseInput(graphene.InputObjectType):@@ -36,6 +37,13 @@ class WarehouseUpdateInput(WarehouseInput):description="Address of the warehouse.",required=False,)+ click_and_collect_option = WarehouseClickAndCollectOptionEnum(+ description=f"{ADDED_IN_31} Click and collect options: local, all or disabled",+ required=False,+ )+ is_private = graphene.Boolean(+ description=f"{ADDED_IN_31} Visibility of warehouse stocks", required=False+ )class Warehouse(CountableDjangoObjectType):@@ -46,6 +54,10 @@ class Warehouse(CountableDjangoObjectType):f"{DEPRECATED_IN_3X_FIELD} Use `Address.companyName` instead."),)+ click_and_collect_option = WarehouseClickAndCollectOptionEnum(+ description=f"{ADDED_IN_31} Click and collect options: local, all or disabled",+ required=True,+ )class Meta:description = "Represents warehouse."@@ -58,6 +70,7 @@ class Warehouse(CountableDjangoObjectType):"shipping_zones","address","email",+ "is_private",]@staticmethoddiff --git a/saleor/order/migrations/0114_auto_20210726_1116.py b/saleor/order/migrations/0114_auto_20210726_1116.pynew file mode 100644index 0000000000..380dbbb937--- /dev/null+++ b/saleor/order/migrations/0114_auto_20210726_1116.py@@ -0,0 +1,33 @@+# Generated by Django 3.2.2 on 2021-07-26 11:16++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("warehouse", "0015_auto_20210713_0904"),+ ("order", "0113_orderevent_app"),+ ]++ operations = [+ migrations.AddField(+ model_name="order",+ name="collection_point",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="orders",+ to="warehouse.warehouse",+ ),+ ),+ migrations.AddField(+ model_name="order",+ name="collection_point_name",+ field=models.CharField(+ blank=True, default=None, editable=False, max_length=255, null=True+ ),+ ),+ ]diff --git a/saleor/order/migrations/0116_merge_20210824_1103.py b/saleor/order/migrations/0116_merge_20210824_1103.pynew file mode 100644index 0000000000..e20c921bca--- /dev/null+++ b/saleor/order/migrations/0116_merge_20210824_1103.py@@ -0,0 +1,13 @@+# Generated by Django 3.2.6 on 2021-08-24 11:03++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0114_auto_20210726_1116"),+ ("order", "0115_merge_20210820_1454"),+ ]++ operations = []diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 5526a60c15..a11f78b6f8 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -130,9 +130,20 @@ class Order(ModelWithMetadata):related_name="orders",on_delete=models.SET_NULL,)+ collection_point = models.ForeignKey(+ "warehouse.Warehouse",+ blank=True,+ null=True,+ related_name="orders",+ on_delete=models.SET_NULL,+ )shipping_method_name = models.CharField(max_length=255, null=True, default=None, blank=True, editable=False)+ collection_point_name = models.CharField(+ max_length=255, null=True, default=None, blank=True, editable=False+ )+channel = models.ForeignKey(Channel,related_name="orders",diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex bb1120ab7c..c2a2309e08 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -577,6 +577,24 @@ def get_valid_shipping_methods_for_order(order: Order):)+def is_shipping_required(lines: Iterable["OrderLine"]):+ return any(line.is_shipping_required for line in lines)+++def get_valid_collection_points_for_order(lines: Iterable["OrderLine"], address):+ if not is_shipping_required(lines):+ return []+ if not address:+ return []++ line_ids = [line.id for line in lines]+ lines = OrderLine.objects.filter(id__in=line_ids)++ return Warehouse.objects.applicable_for_click_and_collect(+ lines, address.country.code+ )++def get_discounted_lines(lines, voucher):discounted_products = voucher.products.all()discounted_categories = set(voucher.categories.all())diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.pyindex 86e48def17..b62cb0e234 100644--- a/saleor/payment/gateways/adyen/utils/common.py+++ b/saleor/payment/gateways/adyen/utils/common.py@@ -205,8 +205,10 @@ def get_shipping_data(manager, checkout_info, lines, discounts):"quantity": 1,"amountExcludingTax": price_to_minor_unit(total_net, currency),"taxPercentage": tax_percentage_in_adyen_format,- "description": f"Shipping - {checkout_info.shipping_method.name}",- "id": f"Shipping:{checkout_info.shipping_method.id}",+ "description": (+ f"Shipping - {checkout_info.delivery_method_info.delivery_method.name}"+ ),+ "id": f"Shipping:{checkout_info.delivery_method_info.delivery_method.id}","taxAmount": price_to_minor_unit(tax_amount, currency),"amountIncludingTax": price_to_minor_unit(total_gross, currency),}@@ -273,7 +275,9 @@ def append_checkout_details(payment_information: "PaymentData", payment_data: di}line_items.append(line_data)- if checkout_info.shipping_method and is_shipping_required(lines):+ if checkout_info.delivery_method_info.delivery_method and is_shipping_required(+ lines+ ):line_items.append(get_shipping_data(manager, checkout_info, lines, discounts))payment_data["lineItems"] = line_itemsdiff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.pyindex f1432d7ac6..ddca7b56b9 100644--- a/saleor/plugins/avatax/__init__.py+++ b/saleor/plugins/avatax/__init__.py@@ -167,7 +167,10 @@ def _validate_checkout(shipping_required = is_shipping_required(lines)address = shipping_address or checkout_info.billing_addressreturn _validate_adddress_details(- shipping_address, shipping_required, address, checkout_info.shipping_method+ shipping_address,+ shipping_required,+ address,+ checkout_info.delivery_method_info.delivery_method,)diff --git a/saleor/plugins/avatax/tests/conftest.py b/saleor/plugins/avatax/tests/conftest.pyindex a05500652b..6a35974d75 100644--- a/saleor/plugins/avatax/tests/conftest.py+++ b/saleor/plugins/avatax/tests/conftest.py@@ -1,7 +1,7 @@import pytestfrom ....account.models import Address-from ....checkout.fetch import CheckoutInfo+from ....checkout.fetch import CheckoutInfo, get_delivery_method_infofrom ....shipping.models import ShippingMethodChannelListingfrom ...models import PluginConfigurationfrom ..plugin import AvataxPlugin@@ -91,9 +91,12 @@ def checkout_with_items_and_shipping_info(checkout_with_items_and_shipping):channel=channel,billing_address=checkout.billing_address,shipping_address=shipping_address,- shipping_method=shipping_method,+ delivery_method_info=get_delivery_method_info(+ shipping_method, shipping_address+ ),shipping_method_channel_listings=shipping_channel_listings,valid_shipping_methods=[],+ valid_pick_up_points=[],)return checkout_infodiff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex 70e9934333..1ecc2fe77e 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -13,6 +13,7 @@ from ....checkout.fetch import (CheckoutInfo,fetch_checkout_info,fetch_checkout_lines,+ get_delivery_method_info,get_valid_shipping_method_list_for_checkout_info,)from ....checkout.utils import add_variant_to_checkout@@ -836,13 +837,16 @@ def test_get_checkout_line_tax_rate(checkout_info = CheckoutInfo(checkout=checkout_with_item,- shipping_method=checkout_with_item.shipping_method,+ delivery_method_info=get_delivery_method_info(+ checkout_with_item.shipping_method+ ),shipping_address=address,billing_address=None,channel=checkout_with_item.channel,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)lines = fetch_checkout_lines(checkout_with_item)checkout_line_info = lines[0]@@ -889,13 +893,16 @@ def test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false(checkout_info = CheckoutInfo(checkout=checkout_with_item,- shipping_method=checkout_with_item.shipping_method,+ delivery_method_info=get_delivery_method_info(+ checkout_with_item.shipping_method+ ),shipping_address=address,billing_address=None,channel=checkout_with_item.channel,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)lines = fetch_checkout_lines(checkout_with_item)checkout_line_info = lines[0]@@ -954,13 +961,16 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(variant2 = product2.variants.first()checkout_info = CheckoutInfo(checkout=checkout_with_item,- shipping_method=checkout_with_item.shipping_method,+ delivery_method_info=get_delivery_method_info(+ checkout_with_item.shipping_method+ ),shipping_address=address,billing_address=None,channel=checkout_with_item.channel,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)add_variant_to_checkout(checkout_info, variant2, 1)@@ -1179,13 +1189,16 @@ def test_get_checkout_shipping_tax_rate(lines = fetch_checkout_lines(checkout_with_item)checkout_info = CheckoutInfo(checkout=checkout_with_item,- shipping_method=checkout_with_item.shipping_method,+ delivery_method_info=get_delivery_method_info(+ checkout_with_item.shipping_method+ ),shipping_address=address,billing_address=None,channel=checkout_with_item.channel,user=None,shipping_method_channel_listings=None,valid_shipping_methods=[],+ valid_pick_up_points=[],)# whendiff --git a/saleor/plugins/vatlayer/plugin.py b/saleor/plugins/vatlayer/plugin.pyindex bd22dfd20a..44dd1c5374 100644--- a/saleor/plugins/vatlayer/plugin.py+++ b/saleor/plugins/vatlayer/plugin.py@@ -217,7 +217,7 @@ class VatlayerPlugin(BasePlugin):if address:taxes = self._get_taxes_for_country(address.country)if (- not checkout_info.shipping_method+ not checkout_info.delivery_method_info.delivery_methodor not checkout_info.shipping_method_channel_listings):return previous_valuediff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex e1be38019a..c6f7550a85 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -36,7 +36,7 @@ from ..attribute.models import ()from ..attribute.utils import associate_attribute_values_to_instancefrom ..checkout.fetch import fetch_checkout_info-from ..checkout.models import Checkout+from ..checkout.models import Checkout, CheckoutLinefrom ..checkout.utils import add_variant_to_checkoutfrom ..core import JobStatus, TimePeriodTypefrom ..core.payments import PaymentInterface@@ -108,6 +108,7 @@ from ..shipping.models import (ShippingZone,)from ..site.models import SiteSettings+from ..warehouse import WarehouseClickAndCollectOptionfrom ..warehouse.models import Allocation, Stock, Warehousefrom ..webhook.event_types import WebhookEventTypefrom ..webhook.models import Webhook, WebhookEvent@@ -271,7 +272,7 @@ def checkout(db, channel_USD):@pytest.fixturedef checkout_with_item(checkout, product):- variant = product.variants.get()+ variant = product.variants.first()checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())add_variant_to_checkout(checkout_info, variant, 3)checkout.save()@@ -551,6 +552,20 @@ def user_checkout(customer_user, channel_USD):return checkout+def user_checkout_for_cc(customer_user, channel_USD, warehouse_for_cc):+ checkout = Checkout.objects.create(+ user=customer_user,+ channel=channel_USD,+ billing_address=customer_user.default_billing_address,+ shipping_address=warehouse_for_cc.address,+ collection_point=warehouse_for_cc,+ note="Test notes",+ currency="USD",+ )+ return checkout++@pytest.fixturedef user_checkout_PLN(customer_user, channel_PLN):checkout = Checkout.objects.create(@@ -574,6 +589,28 @@ def user_checkout_with_items(user_checkout, product_list):return user_checkout+def user_checkout_with_items_for_cc(user_checkout_for_cc, product_list):+ checkout_info = fetch_checkout_info(+ user_checkout_for_cc, [], [], get_plugins_manager()+ )+ for product in product_list:+ variant = product.variants.get()+ add_variant_to_checkout(checkout_info, variant, 1)+ user_checkout_for_cc.refresh_from_db()+ return user_checkout_for_cc+++def user_checkouts(request, user_checkout_with_items, user_checkout_with_items_for_cc):+ if request.param == "regular":+ return user_checkout_with_items+ elif request.param == "click_and_collect":+ return user_checkout_with_items_for_cc+ else:+ raise ValueError("Internal test error")++@pytest.fixturedef order(customer_user, channel_USD):address = customer_user.default_billing_address.get_copy()@@ -1918,6 +1955,7 @@ def product_variant_list(product, channel_USD, channel_PLN):ProductVariant(product=product, sku="1"),ProductVariant(product=product, sku="2"),ProductVariant(product=product, sku="3"),+ ProductVariant(product=product, sku="4"),]))@@ -1944,6 +1982,13 @@ def product_variant_list(product, channel_USD, channel_PLN):price_amount=Decimal(10),currency=channel_PLN.currency_code,),+ ProductVariantChannelListing(+ variant=variants[3],+ channel=channel_USD,+ cost_price_amount=Decimal(1),+ price_amount=Decimal(10),+ currency=channel_USD.currency_code,+ ),])return variants@@ -2735,6 +2780,7 @@ def order_with_lines(stock = Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=2)+ stock.refresh_from_db()net = variant.get_price(product, [], channel_USD, channel_listing)currency = net.currency@@ -2776,6 +2822,33 @@ def order_with_lines(return order+def order_with_lines_for_cc(+ warehouse_for_cc,+ channel_USD,+ customer_user,+):+ address = customer_user.default_billing_address.get_copy()++ order = Order.objects.create(+ billing_address=address,+ channel=channel_USD,+ currency=channel_USD.currency_code,+ shipping_address=address,+ user_email=customer_user.email,+ user=customer_user,+ origin=OrderOrigin.CHECKOUT,+ )++ order.collection_point = warehouse_for_cc+ order.save()++ recalculate_order(order)++ order.refresh_from_db()+ return order++@pytest.fixturedef lines_info(order_with_lines):return [@@ -4225,6 +4298,177 @@ def warehouses(address, address_usa):)+def warehouses_for_cc(address, shipping_zones):+ warehouses = Warehouse.objects.bulk_create(+ [+ Warehouse(+ address=address.get_copy(),+ name="Warehouse1",+ slug="warehouse1",+ email="[email protected]",+ ),+ Warehouse(+ address=address.get_copy(),+ name="Warehouse2",+ slug="warehouse2",+ email="[email protected]",+ click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES,+ ),+ Warehouse(+ address=address.get_copy(),+ name="Warehouse3",+ slug="warehouse3",+ email="[email protected]",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ is_private=False,+ ),+ Warehouse(+ address=address.get_copy(),+ name="Warehouse4",+ slug="warehouse4",+ email="[email protected]",+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ is_private=False,+ ),+ ]+ )+ for warehouse in warehouses:+ warehouse.shipping_zones.add(shipping_zones[0])+ warehouse.shipping_zones.add(shipping_zones[1])+ warehouse.save()+ return warehouses+++def warehouse_for_cc(address, product_variant_list, shipping_zones):+ warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="Local Warehouse",+ slug="local-warehouse",+ email="[email protected]",+ is_private=False,+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,+ )+ warehouse.shipping_zones.add(shipping_zones[0])+ warehouse.shipping_zones.add(shipping_zones[1])++ Stock.objects.bulk_create(+ [+ Stock(+ warehouse=warehouse, product_variant=product_variant_list[0], quantity=1+ ),+ Stock(+ warehouse=warehouse, product_variant=product_variant_list[1], quantity=2+ ),+ Stock(+ warehouse=warehouse, product_variant=product_variant_list[2], quantity=2+ ),+ ]+ )+ return warehouse++[email protected](params=["warehouse_for_cc", "shipping_method"])+def delivery_method(request, warehouse_for_cc, shipping_method):+ if request.param == "warehouse":+ return warehouse_for_cc+ if request.param == "shipping_method":+ return shipping_method+++def stocks_for_cc(warehouses_for_cc, product_variant_list, product_with_two_variants):+ return Stock.objects.bulk_create(+ [+ Stock(+ warehouse=warehouses_for_cc[0],+ product_variant=product_variant_list[0],+ quantity=5,+ ),+ Stock(+ warehouse=warehouses_for_cc[1],+ product_variant=product_variant_list[0],+ quantity=3,+ ),+ Stock(+ warehouse=warehouses_for_cc[1],+ product_variant=product_variant_list[1],+ quantity=10,+ ),+ Stock(+ warehouse=warehouses_for_cc[1],+ product_variant=product_variant_list[2],+ quantity=10,+ ),+ Stock(+ warehouse=warehouses_for_cc[2],+ product_variant=product_variant_list[0],+ quantity=3,+ ),+ Stock(+ warehouse=warehouses_for_cc[3],+ product_variant=product_variant_list[0],+ quantity=3,+ ),+ Stock(+ warehouse=warehouses_for_cc[3],+ product_variant=product_variant_list[1],+ quantity=3,+ ),+ Stock(+ warehouse=warehouses_for_cc[3],+ product_variant=product_with_two_variants.variants.last(),+ quantity=7,+ ),+ Stock(+ warehouse=warehouses_for_cc[3],+ product_variant=product_variant_list[2],+ quantity=3,+ ),+ ]+ )+++def checkout_for_cc(channel_USD, customer_user, product_variant_list):+ return Checkout.objects.create(+ channel=channel_USD,+ billing_address=customer_user.default_billing_address,+ shipping_address=customer_user.default_shipping_address,+ note="Test notes",+ currency="USD",+ )+++def checkout_with_items_for_cc(checkout_for_cc, product_variant_list):+ CheckoutLine.objects.bulk_create(+ [+ CheckoutLine(+ checkout=checkout_for_cc, variant=product_variant_list[0], quantity=1+ ),+ CheckoutLine(+ checkout=checkout_for_cc, variant=product_variant_list[1], quantity=1+ ),+ CheckoutLine(+ checkout=checkout_for_cc, variant=product_variant_list[2], quantity=1+ ),+ ]+ )+ checkout_for_cc.set_country("US", commit=True)++ return checkout_for_cc+++def checkout_with_item_for_cc(checkout_for_cc, product_variant_list):+ CheckoutLine.objects.create(+ checkout=checkout_for_cc, variant=product_variant_list[0], quantity=1+ )+ return checkout_for_cc++@pytest.fixturedef warehouses_with_shipping_zone(warehouses, shipping_zone):warehouses[0].shipping_zones.add(shipping_zone)diff --git a/saleor/warehouse/__init__.py b/saleor/warehouse/__init__.pyindex e69de29bb2..715064472b 100644--- a/saleor/warehouse/__init__.py+++ b/saleor/warehouse/__init__.py@@ -0,0 +1,10 @@+class WarehouseClickAndCollectOption:+ DISABLED = "disabled"+ LOCAL_STOCK = "local"+ ALL_WAREHOUSES = "all"++ CHOICES = [+ (DISABLED, "Disabled"),+ (LOCAL_STOCK, "Local stock only"),+ (ALL_WAREHOUSES, "All warehouses"),+ ]diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex 9d5f76c5a3..e1e4ea1b7f 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -1,5 +1,5 @@from collections import defaultdict-from typing import TYPE_CHECKING, Dict, Iterable, List+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optionalfrom django.db.models import Sumfrom django.db.models.functions import Coalesce@@ -46,14 +46,19 @@ def check_stock_quantity_bulk(country_code: str,quantities: Iterable[int],channel_slug: str,+ additional_filter_lookup: Optional[Dict[str, Any]] = None,):"""Validate if there is stock available for given variants in given country.:raises InsufficientStock: when there is not enough items in stock for a variant."""+ filter_lookup = {"product_variant__in": variants}+ if additional_filter_lookup is not None:+ filter_lookup.update(additional_filter_lookup)+all_variants_stocks = (Stock.objects.for_country_and_channel(country_code, channel_slug)- .filter(product_variant__in=variants)+ .filter(**filter_lookup).annotate_available_quantity())diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 96bd7aa9ad..dcb4d9d9db 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -1,5 +1,5 @@from collections import defaultdict, namedtuple-from typing import TYPE_CHECKING, Dict, Iterable, List, cast+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, castfrom django.db import transactionfrom django.db.models import F, Sum@@ -24,6 +24,7 @@ def allocate_stocks(country_code: str,channel_slug: str,manager: PluginsManager,+ additional_filter_lookup: Optional[Dict[str, Any]] = None,):"""Allocate stocks for given `order_lines` in given country.@@ -41,11 +42,15 @@ def allocate_stocks(returnvariants = [line_info.variant for line_info in order_lines_info]+ filter_lookup = {"product_variant__in": variants}++ if additional_filter_lookup is not None:+ filter_lookup.update(additional_filter_lookup)stocks = list(Stock.objects.select_for_update(of=("self",)).for_country_and_channel(country_code, channel_slug)- .filter(product_variant__in=variants)+ .filter(**filter_lookup).order_by("pk").values("id", "product_variant", "pk", "quantity"))diff --git a/saleor/warehouse/migrations/0015_auto_20210713_0904.py b/saleor/warehouse/migrations/0015_auto_20210713_0904.pynew file mode 100644index 0000000000..179aeba9ce--- /dev/null+++ b/saleor/warehouse/migrations/0015_auto_20210713_0904.py@@ -0,0 +1,31 @@+# Generated by Django 3.2.2 on 2021-07-13 09:04++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("warehouse", "0014_remove_warehouse_company_name"),+ ]++ operations = [+ migrations.AddField(+ model_name="warehouse",+ name="click_and_collect_option",+ field=models.CharField(+ choices=[+ ("disabled", "Disabled"),+ ("local", "Local stock only"),+ ("all", "All warehouses"),+ ],+ default="disabled",+ max_length=30,+ ),+ ),+ migrations.AddField(+ model_name="warehouse",+ name="is_private",+ field=models.BooleanField(default=True),+ ),+ ]diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 31448640f6..c07fbbcd09 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -3,15 +3,19 @@ import uuidfrom typing import Setfrom django.db import models-from django.db.models import Exists, F, OuterRef, Q, Sum+from django.db.models import Count, Exists, F, OuterRef, Prefetch, Q, Sum+from django.db.models.expressions import Subqueryfrom django.db.models.functions import Coalesce+from django.db.models.query import QuerySetfrom ..account.models import Addressfrom ..channel.models import Channel+from ..checkout.models import CheckoutLinefrom ..core.models import ModelWithMetadatafrom ..order.models import OrderLinefrom ..product.models import Product, ProductVariantfrom ..shipping.models import ShippingZone+from . import WarehouseClickAndCollectOptionclass WarehouseQueryset(models.QuerySet):@@ -25,8 +29,74 @@ class WarehouseQueryset(models.QuerySet):.order_by("pk"))+ def applicable_for_click_and_collect_no_quantity_check(+ self, lines_qs: QuerySet[CheckoutLine], country: str+ ):+ """Return the queryset of a `Warehouse` which are applicable for click and collect.++ Note this method does not check stocks quantity for given `CheckoutLine`s.+ This method should be used only if stocks quantity will be checked in further+ validation steps, for instance in checkout completion.+ """++ stocks_qs = Stock.objects.filter(+ product_variant__id__in=lines_qs.values("variant_id"),+ ).select_related("product_variant")++ return self._for_country_lines_and_stocks(lines_qs, stocks_qs, country)++ def applicable_for_click_and_collect(+ self, lines_qs: QuerySet[CheckoutLine], country: str+ ) -> QuerySet["Warehouse"]:+ """Return the queryset of a `Warehouse` which are applicable for click and collect.++ Note additional check of stocks quantity for given `CheckoutLine`s.+ For `WarehouseClickAndCollect.LOCAL` all `CheckoutLine`s must be available from+ a single warehouse.+ """++ lines_quantity = (+ lines_qs.filter(variant_id=OuterRef("product_variant_id"))+ .annotate(prod_sum=Sum("quantity"))+ .values_list("prod_sum")+ )++ stocks_qs = (+ Stock.objects.annotate_available_quantity()+ .annotate(line_quantity=F("available_quantity") - Subquery(lines_quantity))+ .order_by("line_quantity")+ .filter(+ product_variant__id__in=lines_qs.values("variant_id"),+ line_quantity__gte=0,+ )+ .select_related("product_variant")+ )++ return self._for_country_lines_and_stocks(lines_qs, stocks_qs, country)++ def _for_country_lines_and_stocks(+ self,+ lines_qs: QuerySet[CheckoutLine],+ stocks_qs: QuerySet["Stock"],+ country: str,+ ) -> QuerySet["Warehouse"]:+ warehouse_cc_option_enum = WarehouseClickAndCollectOption++ return (+ self.for_country(country)+ .prefetch_related(Prefetch("stock_set", queryset=stocks_qs))+ .filter(stock__in=stocks_qs)+ .annotate(stock_num=Count("stock__id", distinct=True))+ .filter(+ Q(stock_num=lines_qs.count())+ & Q(click_and_collect_option=warehouse_cc_option_enum.LOCAL_STOCK)+ | Q(click_and_collect_option=warehouse_cc_option_enum.ALL_WAREHOUSES)+ )+ )+class Warehouse(ModelWithMetadata):+id = models.UUIDField(default=uuid.uuid4, primary_key=True)name = models.CharField(max_length=250)slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)@@ -35,6 +105,12 @@ class Warehouse(ModelWithMetadata):)address = models.ForeignKey(Address, on_delete=models.PROTECT)email = models.EmailField(blank=True, default="")+ click_and_collect_option = models.CharField(+ max_length=30,+ choices=WarehouseClickAndCollectOption.CHOICES,+ default=WarehouseClickAndCollectOption.DISABLED,+ )+ is_private = models.BooleanField(default=True)objects = models.Manager.from_queryset(WarehouseQueryset)()diff --git a/saleor/warehouse/tests/test_warehouse.py b/saleor/warehouse/tests/test_warehouse.pynew file mode 100644index 0000000000..881aafafcd--- /dev/null+++ b/saleor/warehouse/tests/test_warehouse.py@@ -0,0 +1,179 @@+import pytest+from django.db.models import Sum++from ...shipping.models import ShippingZone+from .. import WarehouseClickAndCollectOption+from ..models import Stock, Warehouse+++def test_applicable_for_click_and_collect_finds_warehouse_with_all_and_local(+ stocks_for_cc, checkout_with_items_for_cc+):+ expected_number_of_warehouses = 2++ lines = checkout_with_items_for_cc.lines.all()+ result = Warehouse.objects.applicable_for_click_and_collect(+ lines, checkout_with_items_for_cc.shipping_address.country.code+ )+ result.get(click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES)+ warehouse2 = result.get(+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK+ )++ assert result.count() == expected_number_of_warehouses+ assert warehouse2.stock_set.count() == lines.count()+++def test_applicable_for_click_and_collect_quantity_exceeded_for_local(+ stocks_for_cc, checkout_with_items_for_cc+):+ expected_number_of_warehouses = Warehouse.objects.filter(+ click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES+ ).count()++ lines = checkout_with_items_for_cc.lines.all()+ line = lines[2]+ quantity_above_available_in_stock = (+ Stock.objects.filter(product_variant=line.variant)+ .aggregate(total_quantity=Sum("quantity"))+ .get("total_quantity")+ + 1+ )++ line.quantity = quantity_above_available_in_stock+ line.save(update_fields=["quantity"])+ checkout_with_items_for_cc.refresh_from_db()++ result = Warehouse.objects.applicable_for_click_and_collect(+ lines, checkout_with_items_for_cc.shipping_address.country.code+ )+ assert result.count() == expected_number_of_warehouses+ with pytest.raises(Warehouse.DoesNotExist):+ result.get(click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK)+++def test_applicable_for_click_and_collect_for_one_line_two_local_warehouses(+ stocks_for_cc, checkout_with_item_for_cc+):+ expected_total_number_of_warehouses = Warehouse.objects.exclude(+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED+ ).count()+ expected_total_number_of_local_warehouses = Warehouse.objects.filter(+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK+ ).count()+ expected_total_number_of_all_warehouses = (+ expected_total_number_of_warehouses - expected_total_number_of_local_warehouses+ )++ lines = checkout_with_item_for_cc.lines.all()+ result = Warehouse.objects.applicable_for_click_and_collect(+ lines, checkout_with_item_for_cc.shipping_address.country.code+ )+ assert result.count() == expected_total_number_of_warehouses+ assert (+ result.filter(+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK+ ).count()+ == expected_total_number_of_local_warehouses+ )+ assert (+ result.filter(+ click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES+ ).count()+ == expected_total_number_of_all_warehouses+ )+++def test_applicable_for_click_and_collect_does_not_show_warehouses_with_empty_stocks(+ stocks_for_cc, checkout_with_items_for_cc+):+ expected_total_number_of_warehouses = 1+ reduced_stock_quantity = 0++ lines = checkout_with_items_for_cc.lines.all()+ stock = Stock.objects.filter(+ warehouse__click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK+ ).last()+ stock.quantity = reduced_stock_quantity+ stock.save(update_fields=["quantity"])++ result = Warehouse.objects.applicable_for_click_and_collect(+ lines, checkout_with_items_for_cc.shipping_address.country.code+ )+ assert result.count() == expected_total_number_of_warehouses+ assert (+ result.first().click_and_collect_option+ == WarehouseClickAndCollectOption.ALL_WAREHOUSES+ )+++def test_applicable_for_click_and_collect_additional_stock_does_not_change_availbility(+ stocks_for_cc, checkout_with_items_for_cc, warehouses_for_cc, product_variant_list+):+ expected_total_number_of_stocks = 5+ expected_total_number_of_warehouses = 2+ expected_number_of_checkout_lines = 3++ Stock.objects.create(+ warehouse=warehouses_for_cc[3], product_variant=product_variant_list[3]+ )+ lines = checkout_with_items_for_cc.lines.all()++ result = Warehouse.objects.applicable_for_click_and_collect(+ lines, checkout_with_items_for_cc.shipping_address.country.code+ )++ assert result.count() == expected_total_number_of_warehouses+ result.get(click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES)+ warehouse = result.get(+ click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK+ )+ assert warehouse == warehouses_for_cc[3]+ # Taken from warehouses fixture, due to the prefetch_related on stocks qs for lines+ assert warehouses_for_cc[3].stock_set.count() == expected_total_number_of_stocks+ assert lines.count() == expected_number_of_checkout_lines+++def test_applicable_for_click_and_collect_returns_empty_collection_if_no_shipping_zone(+ warehouse_for_cc, checkout_with_items_for_cc+):+ lines = checkout_with_items_for_cc.lines.all()+ result = Warehouse.objects.applicable_for_click_and_collect(+ lines, checkout_with_items_for_cc.shipping_address.country.code+ )+ assert result.count() == 1++ warehouse_for_cc.shipping_zones.clear()+ result = Warehouse.objects.applicable_for_click_and_collect(+ lines, checkout_with_items_for_cc.shipping_address.country.code+ )++ assert not result+++def test_applicable_for_click_and_collect_returns_empty_collection_if_different_zone(+ warehouse_for_cc, checkout_with_items_for_cc+):+ lines = checkout_with_items_for_cc.lines.all()+ warehouse_for_cc.shipping_zones.filter(name="Poland").delete()++ result = Warehouse.objects.applicable_for_click_and_collect(+ lines, checkout_with_items_for_cc.shipping_address.country.code+ )++ assert not result+++def test_applicable_for_click_and_collect_when_country_is_duplicated_within_zones(+ warehouse_for_cc, checkout_with_items_for_cc+):+ shipping_zone = ShippingZone.objects.create(name="Poland", countries=["PL"])+ warehouse_for_cc.shipping_zones.add(shipping_zone)++ lines = checkout_with_items_for_cc.lines.all()++ result = Warehouse.objects.applicable_for_click_and_collect(+ lines, checkout_with_items_for_cc.shipping_address.country.code+ )++ assert result.count() == 1diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex e079b6b769..b765e426cb 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -126,6 +126,22 @@ def generate_order_lines_payload(lines: Iterable[OrderLine]):)+def _generate_collection_point_payload(warehouse: "Warehouse"):+ serializer = PayloadSerializer()+ collection_point_fields = (+ "name",+ "email",+ "click_and_collect_option",+ "is_private",+ )+ collection_point_data = serializer.serialize(+ [warehouse],+ fields=collection_point_fields,+ additional_fields={"address": (lambda w: w.address, ADDRESS_FIELDS)},+ )+ return collection_point_data++def generate_order_payload(order: "Order"):serializer = PayloadSerializer()fulfillment_fields = (@@ -197,6 +213,11 @@ def generate_order_payload(order: "Order"):"original": graphene.Node.to_global_id("Order", order.original_id),"lines": json.loads(generate_order_lines_payload(lines)),"fulfillments": json.loads(fulfillments_data),+ "collection_point": json.loads(+ _generate_collection_point_payload(order.collection_point)+ )[0]+ if order.collection_point+ else None,},)return order_data@@ -242,7 +263,12 @@ def generate_checkout_payload(checkout: "Checkout"):},extra_dict_data={# Casting to list to make it json-serializable- "lines": list(lines_dict_data)+ "lines": list(lines_dict_data),+ "collection_point": json.loads(+ _generate_collection_point_payload(checkout.collection_point)+ )[0]+ if checkout.collection_point+ else None,},)return checkout_datadiff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex 9659bd45d4..3f78aa21f7 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -15,6 +15,7 @@ from ...order.models import Orderfrom ...plugins.manager import get_plugins_managerfrom ...plugins.webhook.utils import from_payment_app_idfrom ...product.models import ProductVariant+from ...warehouse import WarehouseClickAndCollectOptionfrom ..payloads import (ORDER_FIELDS,PRODUCT_VARIANT_FIELDS,@@ -614,3 +615,19 @@ def test_generate_customer_payload(customer_user, address_other_country, address}assert payload == expected_payload+++def test_generate_collection_point_payload(order_with_lines_for_cc):+ payload = json.loads(generate_order_payload(order_with_lines_for_cc))[0]++ payload_collection_point = payload.get("collection_point")++ assert payload_collection_point+ assert payload_collection_point.get("address")+ assert payload_collection_point.get("email") == "[email protected]"+ assert payload_collection_point.get("name") == "Local Warehouse"+ assert not payload_collection_point.get("is_private")+ assert (+ payload_collection_point.get("click_and_collect_option")+ == WarehouseClickAndCollectOption.LOCAL_STOCK+ )diff --git a/saleor/webhook/tests/test_webhook_sample_payloads.py b/saleor/webhook/tests/test_webhook_sample_payloads.pyindex d67aa02c91..27de223e5d 100644--- a/saleor/webhook/tests/test_webhook_sample_payloads.py+++ b/saleor/webhook/tests/test_webhook_sample_payloads.py@@ -1,5 +1,6 @@import copyimport json+from unittest import mockimport grapheneimport pytest@@ -146,27 +147,34 @@ def _remove_anonymized_checkout_data(checkout_data: dict) -> dict:return checkout_data-def test_generate_sample_checkout_payload(user_checkout_with_items):- checkout = user_checkout_with_items- payload = generate_sample_payload(WebhookEventType.CHECKOUT_UPDATED)- checkout_payload = json.loads(generate_checkout_payload(checkout))- # Check anonymized data differ- assert checkout.token != payload[0]["token"]- assert checkout.user.email != payload[0]["user"]["email"]- assert checkout.email != payload[0]["email"]- assert (- checkout.billing_address.street_address_1- != payload[0]["billing_address"]["street_address_1"]- )- assert (- checkout.shipping_address.street_address_1- != payload[0]["shipping_address"]["street_address_1"]- )- assert "note" not in payload[0]- assert checkout.metadata != payload[0]["metadata"]- assert checkout.private_metadata != payload[0]["private_metadata"]- # Remove anonymized data- payload = _remove_anonymized_checkout_data(payload)- checkout_payload = _remove_anonymized_checkout_data(checkout_payload)- # Compare the payloads- assert payload == checkout_payload+ "user_checkouts", ["regular", "click_and_collect"], indirect=True+)+def test_generate_sample_checkout_payload(user_checkouts):++ with mock.patch(+ "saleor.webhook.payloads._get_sample_object", return_value=user_checkouts+ ):+ checkout = user_checkouts+ payload = generate_sample_payload(WebhookEventType.CHECKOUT_UPDATED)+ checkout_payload = json.loads(generate_checkout_payload(checkout))+ # Check anonymized data differ+ assert checkout.token != payload[0]["token"]+ assert checkout.user.email != payload[0]["user"]["email"]+ assert checkout.email != payload[0]["email"]+ assert (+ checkout.billing_address.street_address_1+ != payload[0]["billing_address"]["street_address_1"]+ )+ assert (+ checkout.shipping_address.street_address_1+ != payload[0]["shipping_address"]["street_address_1"]+ )+ assert "note" not in payload[0]+ assert checkout.metadata != payload[0]["metadata"]+ assert checkout.private_metadata != payload[0]["private_metadata"]+ # Remove anonymized data+ payload = _remove_anonymized_checkout_data(payload)+ checkout_payload = _remove_anonymized_checkout_data(checkout_payload)+ # Compare the payloads+ assert payload == checkout_payload