Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add voucher recalculation in every mutations that changes the checkout
Aleksander Spyra4419dc59a52a
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex c89e87fe9a..4a1c4352dc 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -740,7 +740,7 @@ def recalculate_cart_discount(cart, discounts, taxes):def add_voucher_to_cart(voucher, cart):"""Add voucher data to cart.-+Raise NotApplicable if voucher of given type cannot be applied."""discount_amount = get_voucher_discount_for_cart(voucher, cart)cart.voucher_code = voucher.codediff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 1fb33a578d..48cd9b78e3 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -7,7 +7,7 @@ from ...checkout import modelsfrom ...checkout.utils import (add_variant_to_cart, add_voucher_to_cart, change_billing_address_in_cart,change_shipping_address_in_cart, create_order, get_taxes_for_cart,- get_voucher_for_cart, get_voucher_discount_for_cart, ready_to_place_order,+ get_voucher_for_cart, ready_to_place_order, recalculate_cart_discount,remove_voucher_from_cart)from ...core import analyticsfrom ...core.exceptions import InsufficientStock@@ -20,7 +20,6 @@ from ..account.i18n import I18nMixinfrom ..account.types import AddressInput, Userfrom ..core.mutations import BaseMutation, ModelMutationfrom ..core.types.common import Error-from ..discount.types import Voucherfrom ..order.types import Orderfrom ..product.types import ProductVariantfrom ..shipping.types import ShippingMethod@@ -239,6 +238,9 @@ class CheckoutLinesAdd(BaseMutation):add_variant_to_cart(checkout, variant, quantity, replace=replace)+ recalculate_cart_discount(+ checkout, info.context.discounts, info.context.taxes)+return CheckoutLinesAdd(checkout=checkout, errors=errors)@@ -283,6 +285,9 @@ class CheckoutLineDelete(BaseMutation):if errors:return CheckoutLineDelete(errors=errors)+ recalculate_cart_discount(+ checkout, info.context.discounts, info.context.taxes)+return CheckoutLineDelete(checkout=checkout, errors=errors)@@ -367,6 +372,9 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):with transaction.atomic():shipping_address.save()change_shipping_address_in_cart(checkout, shipping_address)+ recalculate_cart_discount(+ checkout, info.context.discounts, info.context.taxes)+return CheckoutShippingAddressUpdate(checkout=checkout, errors=errors)@@ -451,6 +459,9 @@ class CheckoutShippingMethodUpdate(BaseMutation):if not errors:checkout.shipping_method = shipping_methodcheckout.save(update_fields=['shipping_method'])+ recalculate_cart_discount(+ checkout, info.context.discounts, info.context.taxes)+return CheckoutShippingMethodUpdate(checkout=checkout, errors=errors)@@ -537,7 +548,7 @@ class CheckoutUpdateVoucher(BaseMutation):try:add_voucher_to_cart(voucher, checkout)- except voucher_model.NotApplicable as e:+ except voucher_model.NotApplicable:cls.add_error(errors=errors,field='voucher_code',diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 8fdbfcce1a..eb9aa9ca5a 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -3,12 +3,13 @@ from unittest.mock import ANY, patchimport grapheneimport pytest+from tests.api.utils import get_graphql_contentfrom saleor.checkout.models import Cart-from saleor.checkout.utils import is_fully_paid, ready_to_place_order+from saleor.checkout.utils import (+ add_voucher_to_cart, is_fully_paid, ready_to_place_order)from saleor.graphql.core.utils import str_to_enumfrom saleor.order.models import Order-from tests.api.utils import get_graphql_contentMUTATION_CHECKOUT_CREATE = """mutation createCheckout($checkoutInput: CheckoutCreateInput!) {@@ -476,35 +477,39 @@ def test_checkout_lines_update_check_lines_quantity(assert data['errors'][0]['field'] == 'quantity'+MUTATION_CHECKOUT_LINES_DELETE = """+ mutation checkoutLineDelete($checkoutId: ID!, $lineId: ID!) {+ checkoutLineDelete(checkoutId: $checkoutId, lineId: $lineId) {+ checkout {+ token+ lines {+ quantity+ variant {+ id+ }+ }+ }+ errors {+ field+ message+ }+ }+ }+"""++def test_checkout_line_delete(user_api_client, cart_with_item):cart = cart_with_itemassert cart.lines.count() == 1line = cart.lines.first()assert line.quantity == 3- query = """- mutation checkoutLineDelete($checkoutId: ID!, $lineId: ID!) {- checkoutLineDelete(checkoutId: $checkoutId, lineId: $lineId) {- checkout {- token- lines {- quantity- variant {- id- }- }- }- errors {- field- message- }- }- }- """+checkout_id = graphene.Node.to_global_id('Checkout', cart.pk)line_id = graphene.Node.to_global_id('CheckoutLine', line.pk)variables = {'checkoutId': checkout_id, 'lineId': line_id}- response = user_api_client.post_graphql(query, variables)+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_DELETE, variables)content = get_graphql_content(response)data = content['data']['checkoutLineDelete']@@ -1212,7 +1217,7 @@ def test_checkout_add_voucher_invalid_checkout(api_client, voucher):variables = {'checkoutId': 'XXX', 'voucherCode': voucher.code}data = _mutate_checkout_update_voucher(api_client, variables)- assert len(data['errors']) > 0+ assert data['errors']assert data['errors'][0]['field'] == 'checkoutId'@@ -1221,7 +1226,7 @@ def test_checkout_add_voucher_invalid_code(api_client, cart_with_item):variables = {'checkoutId': checkout_id, 'voucherCode': 'XXX'}data = _mutate_checkout_update_voucher(api_client, variables)- assert len(data['errors']) > 0+ assert data['errors']assert data['errors'][0]['field'] == 'voucherCode'@@ -1233,5 +1238,60 @@ def test_checkout_add_voucher_not_applicable_voucher('voucherCode': voucher_with_high_min_amount_spent.code}data = _mutate_checkout_update_voucher(api_client, variables)- assert len(data['errors']) > 0+ assert data['errors']assert data['errors'][0]['field'] == 'voucherCode'+++def test_checkout_lines_delete_with_not_applicable_voucher(+ user_api_client, cart_with_item, voucher):+ voucher.min_amount_spent = cart_with_item.get_subtotal().gross+ voucher.save(update_fields=['min_amount_spent'])++ add_voucher_to_cart(voucher, cart_with_item)+ assert cart_with_item.voucher_code == voucher.code++ line = cart_with_item.lines.first()++ checkout_id = graphene.Node.to_global_id('Checkout', cart_with_item.pk)+ line_id = graphene.Node.to_global_id('CheckoutLine', line.pk)+ variables = {'checkoutId': checkout_id, 'lineId': line_id}+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_DELETE, variables)+ content = get_graphql_content(response)++ data = content['data']['checkoutLineDelete']+ assert not data['errors']+ cart_with_item.refresh_from_db()+ assert cart_with_item.lines.count() == 0+ assert cart_with_item.voucher_code is None+++def test_checkout_shipping_address_update_with_not_applicable_voucher(+ user_api_client, cart_with_item, voucher_shipping_type,+ graphql_address_data, address_other_country, shipping_method):+ assert cart_with_item.shipping_address is None+ assert cart_with_item.voucher_code is None++ cart_with_item.shipping_address = address_other_country+ cart_with_item.shipping_method = shipping_method+ cart_with_item.save(update_fields=['shipping_address', 'shipping_method'])+ assert cart_with_item.shipping_address.country == address_other_country.country++ voucher = voucher_shipping_type+ assert voucher.countries[0].code == address_other_country.country++ add_voucher_to_cart(voucher, cart_with_item)+ assert cart_with_item.voucher_code == voucher.code++ checkout_id = graphene.Node.to_global_id('Checkout', cart_with_item.pk)+ new_address = graphql_address_data+ variables = {'checkoutId': checkout_id, 'shippingAddress': new_address}+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables)+ content = get_graphql_content(response)+ data = content['data']['checkoutShippingAddressUpdate']+ assert not data['errors']++ cart_with_item.refresh_from_db()+ assert cart_with_item.shipping_address.country == new_address['country']+ assert cart_with_item.voucher_code is Nonediff --git a/tests/conftest.py b/tests/conftest.pyindex 174d621ced..ed3c697186 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -22,6 +22,7 @@ from saleor.checkout.models import Cartfrom saleor.checkout.utils import add_variant_to_cartfrom saleor.dashboard.menu.utils import update_menufrom saleor.dashboard.order.utils import fulfill_order_line+from saleor.discount import VoucherTypefrom saleor.discount.models import Sale, Voucher, VoucherTranslationfrom saleor.menu.models import Menu, MenuItemfrom saleor.order import OrderEvents, OrderStatus@@ -98,6 +99,19 @@ def address(db): # pylint: disable=W0613country='PL',phone='+48713988102')++def address_other_country():+ return Address.objects.create(+ first_name='John',+ last_name='Doe',+ street_address_1='4371 Lucas Knoll Apt. 791',+ city='Bennettmouth',+ postal_code='13377',+ country='IS',+ phone='')++@pytest.fixturedef graphql_address_data():return {@@ -461,6 +475,15 @@ def voucher_with_high_min_amount_spent():min_amount_spent=Money(1000000, 'USD'))+def voucher_shipping_type():+ return Voucher.objects.create(+ code='mirumee',+ discount_value=10,+ type=VoucherType.SHIPPING,+ countries='IS')++@pytest.fixture()def order_with_lines(order, product_type, category, shipping_zone, vatlayer):