Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix incorrect discount applied to checkout (#13833)
Maciej Korycinski094ff358d8b1
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 7d4350f72a..61380808cc 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -20,6 +20,7 @@ from ..discount import VoucherTypefrom ..discount.interface import VoucherInfo, fetch_voucher_infofrom ..discount.models import NotApplicable, Voucherfrom ..discount.utils import (+ generate_sale_discount_objects_for_checkout,get_products_voucher_discount,validate_voucher_for_checkout,)@@ -64,6 +65,7 @@ def invalidate_checkout_prices(checkout = checkout_info.checkoutif recalculate_discount:+ generate_sale_discount_objects_for_checkout(checkout_info, lines)recalculate_checkout_discount(manager, checkout_info, lines)checkout.price_expiration = timezone.now()diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 6c59f7d209..8ee2e56d3e 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -681,7 +681,7 @@ def test_update_checkout_lines_with_reservations(reservation_length=5,)- with django_assert_num_queries(74):+ with django_assert_num_queries(75):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"id": to_global_id_or_none(checkout),@@ -695,7 +695,7 @@ def test_update_checkout_lines_with_reservations(assert not data["errors"]# Updating multiple lines in checkout has same query count as updating one- with django_assert_num_queries(74):+ with django_assert_num_queries(75):variables = {"id": to_global_id_or_none(checkout),"lines": [],@@ -940,7 +940,7 @@ def test_add_checkout_lines_with_reservations(new_lines.append({"quantity": 2, "variantId": variant_id})# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(73):+ with django_assert_num_queries(74):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -953,7 +953,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(73):+ with django_assert_num_queries(74):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex f883895caf..590747a998 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -10,7 +10,14 @@ from django.utils import timezonefrom .....checkout.error_codes import CheckoutErrorCodefrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.models import Checkout-from .....checkout.utils import calculate_checkout_quantity, invalidate_checkout_prices+from .....checkout.utils import (+ calculate_checkout_quantity,+ invalidate_checkout_prices,+ recalculate_checkout_discount,+)+from .....discount import DiscountValueType+from .....discount.models import Sale, SaleChannelListing+from .....discount.utils import generate_sale_discount_objects_for_checkoutfrom .....plugins.manager import get_plugins_managerfrom .....product.models import ProductChannelListingfrom .....warehouse import WarehouseClickAndCollectOption@@ -21,27 +28,46 @@ from ....tests.utils import assert_no_permission, get_graphql_contentfrom ...mutations.utils import update_checkout_shipping_method_if_invalidMUTATION_CHECKOUT_LINES_ADD = """- mutation checkoutLinesAdd(- $id: ID, $lines: [CheckoutLineInput!]!) {- checkoutLinesAdd(id: $id, lines: $lines) {- checkout {- token- quantity- lines {- quantity- variant {- id- }- }- }- errors {- field- code- message- variants- }+mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {+ checkoutLinesAdd(id: $id, lines: $lines) {+ checkout {+ token+ discount{+ amount+ }+ quantity+ lines {+ unitPrice {+ gross {+ amount+ }+ }+ totalPrice {+ gross {+ amount+ }}- }"""+ undiscountedTotalPrice {+ amount+ }+ undiscountedUnitPrice {+ amount+ }+ quantity+ variant {+ id+ }+ }+ }+ errors {+ field+ code+ message+ variants+ }+ }+}+"""@mock.patch(@@ -100,6 +126,105 @@ def test_checkout_lines_add(assert mocked_invalidate_checkout_prices.call_count == 1+ "saleor.graphql.checkout.mutations.checkout_lines_add."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+ "saleor.graphql.checkout.mutations.checkout_lines_add."+ "invalidate_checkout_prices",+ wraps=invalidate_checkout_prices,+)+def test_add_to_existing_line_with_sale_when_checkout_has_voucher(+ mocked_invalidate_checkout_prices,+ mocked_update_shipping_method,+ user_api_client,+ checkout_with_item,+ stock,+ voucher_percentage,+ channel_USD,+):+ # given++ # prepare voucher with 50% discount+ voucher_percentage_value = 50+ voucher_percentage.channel_listings.update(discount_value=voucher_percentage_value)++ checkout = checkout_with_item+ checkout.voucher_code = voucher_percentage.code+ checkout.save()++ variant_unit_price = Decimal(100)+ line = checkout.lines.first()+ variant = line.variant+ variant.channel_listings.update(price_amount=variant_unit_price)++ manager = get_plugins_manager()++ # prepare sale with 50% discount+ sale_percentage_value = 50+ sale = Sale.objects.create(name="Sale", type=DiscountValueType.PERCENTAGE)+ SaleChannelListing.objects.create(+ sale=sale,+ channel=channel_USD,+ discount_value=sale_percentage_value,+ currency=channel_USD.currency_code,+ )+ sale.variants.add(variant)++ # create checkout discount objects for checkout lines+ lines_infos, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines_infos, manager)+ generate_sale_discount_objects_for_checkout(checkout_info, lines_infos)+ recalculate_checkout_discount(manager, checkout_info, lines_infos)++ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # then+ # unit_price: 100, sale 50% then voucher 50% = 25+ expected_unit_price_after_all_discount = Decimal(25)++ expected_discount_per_single_item = Decimal(25)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ print(data)+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ line = checkout.lines.last()+ assert (+ line.total_price_gross_amount+ == expected_unit_price_after_all_discount * line.quantity+ )+ assert (+ line.total_price_net_amount+ == expected_unit_price_after_all_discount * line.quantity+ )+ unit_price = data["checkout"]["lines"][0]["unitPrice"]["gross"]["amount"]+ assert Decimal(unit_price) == expected_unit_price_after_all_discount+ total_price = data["checkout"]["lines"][0]["totalPrice"]["gross"]["amount"]+ assert (+ Decimal(total_price) == expected_unit_price_after_all_discount * line.quantity+ )+ checkout_discount_amount = data["checkout"]["discount"]["amount"]+ # unit price is 50 USD, (after applying sale), then 50% voucher gives us a+ # unit_price equal to 25 USD. The discount amount is 25 USD * quantity+ assert (+ Decimal(checkout_discount_amount)+ == expected_discount_per_single_item * line.quantity+ )++def test_checkout_lines_add_with_existing_variant_and_metadata(user_api_client,checkout_with_item,