Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix invalid available shipping methods calculation for checkout (#9135)
Iga Karbowiak45301d74fb45
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 462c77beed..81224a636a 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -61,6 +61,7 @@ class CheckoutInfo:delivery_method_info: "DeliveryMethodBase"all_shipping_methods: List["ShippingMethodData"]valid_pick_up_points: List["Warehouse"]+ voucher: Optional["Voucher"] = None@propertydef valid_shipping_methods(self) -> List["ShippingMethodData"]:@@ -352,10 +353,13 @@ def fetch_checkout_info(] = None,) -> CheckoutInfo:"""Fetch checkout as CheckoutInfo object."""+ from .utils import get_voucher_for_checkout+channel = checkout.channelshipping_address = checkout.shipping_addressif shipping_channel_listings is None:shipping_channel_listings = channel.shipping_method_listings.all()+ voucher = get_voucher_for_checkout(checkout, channel_slug=channel.slug)delivery_method_info = get_delivery_method_info(None, shipping_address)checkout_info = CheckoutInfo(@@ -367,6 +371,7 @@ def fetch_checkout_info(delivery_method_info=delivery_method_info,all_shipping_methods=[],valid_pick_up_points=[],+ voucher=voucher,)update_delivery_method_lists_for_checkout_info(checkout_info,@@ -466,7 +471,14 @@ def get_valid_internal_shipping_method_list_for_checkout_info(subtotal = manager.calculate_checkout_subtotal(checkout_info, lines, checkout_info.shipping_address, discounts)- subtotal -= checkout_info.checkout.discount+ # if a voucher is applied to shipping, we don't want to subtract the discount amount+ # as some methods based on shipping price may become unavailable,+ # for example, method on which the discount was applied+ is_shipping_voucher = (+ checkout_info.voucher and checkout_info.voucher.type == VoucherType.SHIPPING+ )+ if not is_shipping_voucher:+ subtotal -= checkout_info.checkout.discountvalid_shipping_methods = get_valid_internal_shipping_methods_for_checkout(checkout_info,lines,diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex d5bed2c649..982bf3f4b9 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -483,8 +483,7 @@ def recalculate_checkout_discount(applicable."""checkout = checkout_info.checkout- voucher = get_voucher_for_checkout_info(checkout_info)- if voucher is not None:+ if voucher := checkout_info.voucher:address = checkout_info.shipping_address or checkout_info.billing_addresstry:discount = get_voucher_discount_for_checkout(@@ -492,6 +491,7 @@ def recalculate_checkout_discount()except NotApplicable:remove_voucher_from_checkout(checkout)+ checkout_info.voucher = Noneelse:subtotal = calculations.checkout_subtotal(manager=manager,@@ -612,6 +612,7 @@ def add_voucher_to_checkout("last_change",])+ checkout_info.voucher = voucherdef remove_promo_code_from_checkout(checkout_info: "CheckoutInfo", promo_code: str):@@ -624,9 +625,10 @@ def remove_promo_code_from_checkout(checkout_info: "CheckoutInfo", promo_code: sdef remove_voucher_code_from_checkout(checkout_info: "CheckoutInfo", voucher_code: str):"""Remove voucher data from checkout by code."""- existing_voucher = get_voucher_for_checkout_info(checkout_info)+ existing_voucher = checkout_info.voucherif existing_voucher and existing_voucher.code == voucher_code:remove_voucher_from_checkout(checkout_info.checkout)+ checkout_info.voucher = Nonedef remove_voucher_from_checkout(checkout: Checkout):diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex 7bc4ad1487..6b15ea7bf9 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -12,6 +12,7 @@ from ...checkout.fetch import (from ...checkout.models import Checkout, CheckoutLinefrom ..account.dataloaders import AddressByIdLoader, UserByUserIdLoaderfrom ..core.dataloaders import DataLoader+from ..discount.dataloaders import VoucherByCodeLoaderfrom ..product.dataloaders import (CollectionsByVariantIdLoader,ProductByVariantIdLoader,@@ -196,6 +197,12 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):collection_points = WarehouseByIdLoader(self.context).load_many(collection_point_ids)+ voucher_codes = {+ checkout.voucher_code+ for checkout in checkouts+ if checkout.voucher_code+ }+ vouchers = VoucherByCodeLoader(self.context).load_many(voucher_codes)def with_checkout_info(results):(@@ -204,6 +211,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):shipping_methods,listings_for_channels,collection_points,+ vouchers,) = resultsaddress_map = {address.id: address for address in addresses}user_map = {user.id: user for user in users}@@ -215,6 +223,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):collection_point.id: collection_pointfor collection_point in collection_points}+ voucher_map = {voucher.code: voucher for voucher in vouchers}checkout_info_map = {}for key, checkout, channel, checkout_lines in zip(@@ -230,6 +239,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):delivery_method_info = get_delivery_method_info(None, shipping_address)+ voucher = voucher_map.get(checkout.voucher_code)checkout_info = CheckoutInfo(checkout=checkout,user=user_map.get(checkout.user_id),@@ -243,6 +253,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):delivery_method_info=delivery_method_info,valid_pick_up_points=[],all_shipping_methods=[],+ voucher=voucher,)manager = self.context.plugins@@ -274,6 +285,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader):shipping_methods,shipping_method_channel_listings,collection_points,+ vouchers,]).then(with_checkout_info)diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 7a3116673b..b24d670985 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -1942,6 +1942,52 @@ def test_checkout_shipping_methods_with_price_based_shipping_method_and_discountassert shipping_method.name not in shipping_methods+def test_checkout_shipping_methods_with_price_based_shipping_and_shipping_discount(+ api_client,+ checkout_with_item,+ address,+ shipping_method,+ voucher_shipping_type,+):+ """Ensure that price based shipping method is returned when checkout+ has discount on shipping."""+ checkout_with_item.shipping_address = address+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)++ subtotal = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout_with_item.shipping_address,+ )++ checkout_with_item.discount_amount = Decimal(5.0)+ checkout_with_item.voucher_code = voucher_shipping_type.code+ checkout_with_item.save(+ update_fields=["shipping_address", "discount_amount", "voucher_code"]+ )++ shipping_method.name = "Price based"+ shipping_method.save(update_fields=["name"])++ shipping_channel_listing = shipping_method.channel_listings.get(+ channel=checkout_with_item.channel+ )+ shipping_channel_listing.minimum_order_price_amount = subtotal.gross.amount - 1+ shipping_channel_listing.save(update_fields=["minimum_order_price_amount"])++ query = GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS+ variables = {"token": checkout_with_item.token}+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ shipping_methods = [method["name"] for method in data["availableShippingMethods"]]+ assert shipping_method.name in shipping_methods++def test_checkout_available_shipping_methods_shipping_zone_without_channels(api_client, checkout_with_item, address, shipping_zone):diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.pyindex 61dbc57c73..ec1778dfd9 100644--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py@@ -4,6 +4,7 @@ from decimal import Decimalfrom unittest import mockimport graphene+import pytestfrom prices import Moneyfrom ....checkout import calculations@@ -892,6 +893,103 @@ def test_checkout_add_promo_code_no_checkout_email(assert data["errors"][0]["code"] == CheckoutErrorCode.EMAIL_NOT_SET.name[email protected]("shipping_price", [12, 10, 5])+def test_checkout_add_free_shipping_voucher_do_not_invalidate_shipping_method(+ shipping_price,+ api_client,+ checkout_with_item,+ voucher_free_shipping,+ shipping_method,+ address_usa,+):+ """Ensure that adding free shipping voucher do not invalidate+ current shipping method.+ """+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.shipping_address = address_usa+ checkout_with_item.save(update_fields=["shipping_method", "shipping_address"])++ channel = checkout_with_item.channel++ line = checkout_with_item.lines.first()+ line.quantity = 1+ line.save(update_fields=["quantity"])++ variant_listing = line.variant.channel_listings.get(channel=channel)+ variant_listing.price = Money(10, "USD")+ variant_listing.save(update_fields=["price_amount"])++ # set minimal price similar to order subtotal price;+ # set shipping price so big, that in case the discount will be applied+ # substracted from subtotal the shipping method will be not valid anymore+ shipping_listing = shipping_method.channel_listings.get(channel=channel)+ shipping_listing.price = Money(shipping_price, "USD")+ shipping_listing.minimum_order_price = Money(8, "USD")+ shipping_listing.save(update_fields=["price_amount", "minimum_order_price_amount"])++ variables = {+ "token": checkout_with_item.token,+ "promoCode": voucher_free_shipping.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # ensure that shipping method wasn't invalidate+ assert data["checkout"]["shippingMethod"]["id"] == graphene.Node.to_global_id(+ "ShippingMethod", shipping_method.id+ )++[email protected]("shipping_discount", [12, 10, 5])+def test_checkout_add_shipping_voucher_do_not_invalidate_shipping_method(+ shipping_discount,+ api_client,+ checkout_with_item,+ voucher_shipping_type,+ shipping_method,+ address_usa,+):+ """Ensure that adding shipping voucher do not invalidate current shipping method."""+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.shipping_address = address_usa+ checkout_with_item.save(update_fields=["shipping_method", "shipping_address"])++ channel = checkout_with_item.channel++ line = checkout_with_item.lines.first()+ line.quantity = 1+ line.save(update_fields=["quantity"])++ variant_listing = line.variant.channel_listings.get(channel=channel)+ variant_listing.price = Money(10, "USD")+ variant_listing.save(update_fields=["price_amount"])++ # set minimal price similar to order subtotal price;+ shipping_listing = shipping_method.channel_listings.get(channel=channel)+ shipping_listing.price = Money(20, "USD")+ shipping_listing.minimum_order_price = Money(8, "USD")+ shipping_listing.save(update_fields=["price_amount", "minimum_order_price_amount"])++ # set shipping voucher price so big, that in case the discount will be+ # substracted from subtotal price the shipping method will be not valid anymore+ voucher_listing = voucher_shipping_type.channel_listings.get(channel=channel)+ voucher_listing.discount = Money(shipping_discount, "USD")+ voucher_listing.save(update_fields=["discount_value"])++ voucher_shipping_type.countries = []+ voucher_shipping_type.save(update_fields=["countries"])++ variables = {+ "token": checkout_with_item.token,+ "promoCode": voucher_shipping_type.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # ensure that shipping method wasn't invalidate+ assert data["checkout"]["shippingMethod"]["id"] == graphene.Node.to_global_id(+ "ShippingMethod", shipping_method.id+ )++MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """mutation($token: UUID, $promoCode: String, $promoCodeId: ID) {checkoutRemovePromoCode(diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.pyindex 2c2353fa7f..8cfe2c51e7 100644--- a/saleor/graphql/discount/dataloaders.py+++ b/saleor/graphql/discount/dataloaders.py@@ -96,6 +96,18 @@ class VoucherByIdLoader(DataLoader):return [vouchers.get(voucher_id) for voucher_id in keys]+class VoucherByCodeLoader(DataLoader):+ context_key = "voucher_by_code"++ def batch_load(self, keys):+ vouchers = (+ Voucher.objects.using(self.database_connection_name)+ .filter(code__in=keys)+ .in_bulk(field_name="code")+ )+ return [vouchers.get(code) for code in keys]++class VoucherChannelListingByVoucherIdAndChanneSlugLoader(DataLoader):context_key = "voucherchannelisting_by_voucher_and_channel"