Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix checkout metadata fetches to not create checkout metadata objects (#12729)
Iga Karbowiak54dccb47e580
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 21a8cc1efa..e186468689 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -83,7 +83,11 @@ from .checkout_cleaner import ()from .fetch import CheckoutInfo, CheckoutLineInfofrom .models import Checkout-from .utils import get_or_create_checkout_metadata, get_voucher_for_checkout_info+from .utils import (+ get_checkout_metadata,+ get_or_create_checkout_metadata,+ get_voucher_for_checkout_info,+)if TYPE_CHECKING:from ..app.models import App@@ -587,7 +591,7 @@ def _create_order(# assign checkout payments to the ordercheckout.payments.update(order=order)- checkout_metadata = get_or_create_checkout_metadata(checkout)+ checkout_metadata = get_checkout_metadata(checkout)# store current tax configurationupdate_order_display_gross_prices(order)diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex f9ef753cd8..6716c43b0b 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -37,6 +37,7 @@ from ..utils import (change_shipping_address_in_checkout,clear_delivery_method,delete_external_shipping_id,+ get_checkout_metadata,get_external_shipping_id,get_voucher_discount_for_checkout,get_voucher_for_checkout_info,@@ -1758,3 +1759,25 @@ def test_checkout_has_currency(checkout):def test_checkout_line_has_currency(checkout_line):assert hasattr(checkout_line, "currency")+++def test_get_checkout_metadata_no_metadata_storage(checkout):+ # given+ checkout.metadata_storage.delete()++ # when+ metadata_container = get_checkout_metadata(checkout)++ # then+ assert metadata_container+++def test_get_checkout_metadata(checkout):+ # given+ assert checkout.metadata_storage.id++ # when+ metadata_container = get_checkout_metadata(checkout)++ # then+ assert metadata_containerdiff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex b6c5aa4711..17c0b08e3f 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -874,7 +874,7 @@ def clear_delivery_method(checkout_info: "CheckoutInfo"):"last_change",])- get_or_create_checkout_metadata(checkout).save(+ get_checkout_metadata(checkout).save(update_fields=["private_metadata",]@@ -953,7 +953,7 @@ def set_external_shipping_id(checkout: Checkout, app_shipping_id: str):def get_external_shipping_id(container: Union["Checkout", "Order"]):if type(container) == Checkout:- container = get_or_create_checkout_metadata(container)+ container = get_checkout_metadata(container)return container.get_value_from_private_metadata( # type:ignorePRIVATE_META_APP_SHIPPING_ID)@@ -969,3 +969,10 @@ def get_or_create_checkout_metadata(checkout: "Checkout"):return checkout.metadata_storageelse:return CheckoutMetadata.objects.create(checkout=checkout)+++def get_checkout_metadata(checkout: "Checkout"):+ if hasattr(checkout, "metadata_storage"):+ return checkout.metadata_storage+ else:+ return CheckoutMetadata(checkout=checkout)diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.pyindex cf021dcab4..2c8ca799e2 100644--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py@@ -7,7 +7,7 @@ from ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.utils import (delete_external_shipping_id,- get_or_create_checkout_metadata,+ get_checkout_metadata,invalidate_checkout_prices,is_shipping_required,set_external_shipping_id,@@ -202,11 +202,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):]+ invalidate_prices_updated_fields)- get_or_create_checkout_metadata(checkout).save(- update_fields=[- "private_metadata",- ]- )+ get_checkout_metadata(checkout).save()cls.call_event(manager.checkout_updated, checkout)return CheckoutShippingMethodUpdate(checkout=checkout)@@ -243,9 +239,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):]+ invalidate_prices_updated_fields)- get_or_create_checkout_metadata(checkout).save(- update_fields=["private_metadata"]- )+ get_checkout_metadata(checkout).save()cls.call_event(manager.checkout_updated, checkout)return CheckoutShippingMethodUpdate(checkout=checkout)diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 1f97240856..babdd90030 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -390,7 +390,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(67):+ with django_assert_num_queries(66):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -408,7 +408,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(67):+ with django_assert_num_queries(66):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10diff --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 5726b530c0..fc0a74887f 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@@ -175,3 +175,57 @@ def test_checkout_shipping_method_update_both_token_and_id_given(assert len(data["errors"]) == 1assert not data["checkout"]assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name+++@patch(+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update."+ "clean_delivery_method"+)+def test_checkout_shipping_method_update_by_id_no_checkout_metadata(+ mock_clean_shipping,+ staff_api_client,+ shipping_method,+ checkout_with_item_and_shipping_method,+):+ # given+ checkout = checkout_with_item_and_shipping_method+ old_shipping_method = checkout.shipping_method+ query = MUTATION_UPDATE_SHIPPING_METHOD+ mock_clean_shipping.return_value = True++ checkout.metadata_storage.delete()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ # when+ response = staff_api_client.post_graphql(+ query, {"checkoutId": checkout_id, "shippingMethodId": method_id}+ )++ # then+ 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.delivery_method_info = get_delivery_method_info(+ convert_to_shipping_method_data(+ old_shipping_method, old_shipping_method.channel_listings.first()+ ),+ None,+ )++ mock_clean_shipping.assert_called_once_with(+ checkout_info=checkout_info,+ lines=lines,+ method=convert_to_shipping_method_data(+ shipping_method, shipping_method.channel_listings.first()+ ),+ )+ errors = data["errors"]+ assert not errors+ assert data["checkout"]["id"] == checkout_id+ assert checkout.shipping_method == shipping_methoddiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex 5f53a431a9..56cdd65f1c 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -484,6 +484,84 @@ def test_checkout_complete_with_metadata_updates_existing_keys(assert order.metadata == {meta_key: new_meta_value}+@patch("saleor.plugins.manager.PluginsManager.order_confirmed")+def test_checkout_complete_with_metadata_checkout_without_metadata(+ order_confirmed_mock,+ user_api_client,+ checkout_with_gift_card,+ gift_card,+ payment_dummy,+ address,+ shipping_method,+):+ """Ensure that checkout is properly completed with provided metadata when the+ checkout object hasn't assigned any metadata."""+ # given+ assert not gift_card.last_used_on++ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ # delete the current metadata+ checkout.metadata_storage.delete()++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ channel = checkout.channel+ channel.automatically_confirm_all_new_orders = True+ channel.save()+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ redirect_url = "https://www.example.com"+ metadata_value = "metaValue"+ metadata_key = "metaKey"+ variables = {+ "id": to_global_id_or_none(checkout),+ "redirectUrl": redirect_url,+ "metadata": [{"key": metadata_key, "value": metadata_value}],+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]++ # then+ assert not data["errors"]+ assert Order.objects.count() == orders_count + 1+ order = Order.objects.first()+ assert order.status == OrderStatus.UNFULFILLED+ assert order.origin == OrderOrigin.CHECKOUT+ assert not order.original++ assert order.metadata == {+ **checkout.metadata_storage.metadata,+ **{metadata_key: metadata_value},+ }+ assert order.private_metadata == checkout.metadata_storage.private_metadata++ assert not Checkout.objects.filter(+ pk=checkout.pk+ ).exists(), "Checkout should have been deleted"+ order_confirmed_mock.assert_called_once_with(order)++@pytest.mark.integration@patch("saleor.graphql.checkout.mutations.checkout_complete.complete_checkout")def test_checkout_complete_by_app(diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.pyindex dac95fa229..bc347149a1 100644--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py@@ -369,6 +369,79 @@ def test_order_from_checkout_with_metadata(order_confirmed_mock.assert_called_once_with(order)+@patch("saleor.plugins.manager.PluginsManager.order_confirmed")+def test_order_from_checkout_with_metadata_checkout_without_metadata(+ order_confirmed_mock,+ app_api_client,+ permission_handle_checkouts,+ permission_manage_checkouts,+ site_settings,+ checkout_with_gift_card,+ gift_card,+ address,+ shipping_method,+):+ # given+ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ metadata_key = "md key"+ metadata_value = "md value"++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ channel = checkout.channel+ channel.automatically_confirm_all_new_orders = True+ channel.save()++ # delete the current metadata+ checkout.metadata_storage.delete()++ orders_count = Order.objects.count()+ variables = {+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),+ "metadata": [{"key": metadata_key, "value": metadata_value}],+ "privateMetadata": [{"key": metadata_key, "value": metadata_value}],+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,+ variables,+ permissions=[permission_handle_checkouts, permission_manage_checkouts],+ )++ content = get_graphql_content(response)+ data = content["data"]["orderCreateFromCheckout"]+ assert not data["errors"]++ order_token = data["order"]["token"]+ assert Order.objects.count() == orders_count + 1+ order = Order.objects.first()+ assert order.status == OrderStatus.UNCONFIRMED+ assert order.origin == OrderOrigin.CHECKOUT+ assert not order.original+ assert str(order.pk) == order_token+ assert order.total.gross == total.gross+ assert order.metadata == {+ **checkout.metadata_storage.metadata,+ **{metadata_key: metadata_value},+ }+ assert order.private_metadata == {+ **checkout.metadata_storage.private_metadata,+ **{metadata_key: metadata_value},+ }+ order_confirmed_mock.assert_called_once_with(order)++def test_order_from_checkout_by_app_with_missing_permission(app_api_client,checkout_with_item,diff --git a/saleor/graphql/meta/types.py b/saleor/graphql/meta/types.pyindex 4a9f63b726..1348dbaa99 100644--- a/saleor/graphql/meta/types.py+++ b/saleor/graphql/meta/types.py@@ -4,7 +4,7 @@ import graphenefrom graphene.types.generic import GenericScalarfrom ...checkout.models import Checkout-from ...checkout.utils import get_or_create_checkout_metadata+from ...checkout.utils import get_checkout_metadatafrom ...core.models import ModelWithMetadatafrom ..channel import ChannelContextfrom ..core import ResolveInfo@@ -164,5 +164,5 @@ class ObjectWithMetadata(graphene.Interface):def get_valid_metadata_instance(instance):if isinstance(instance, Checkout):- instance = get_or_create_checkout_metadata(instance)+ instance = get_checkout_metadata(instance)return instancediff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.pyindex 4643e1cde2..5a1f354e7b 100644--- a/saleor/payment/gateways/adyen/utils/common.py+++ b/saleor/payment/gateways/adyen/utils/common.py@@ -18,7 +18,7 @@ from .....checkout.calculations import ()from .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.models import Checkout-from .....checkout.utils import get_or_create_checkout_metadata, is_shipping_required+from .....checkout.utils import get_checkout_metadata, is_shipping_requiredfrom .....discount.utils import fetch_active_discountsfrom .....payment.models import Paymentfrom .....plugins.manager import get_plugins_manager@@ -352,9 +352,7 @@ def request_data_for_gateway_config(country_code = country.codeelse:country_code = Country(settings.DEFAULT_COUNTRY).code- channel = get_or_create_checkout_metadata(checkout).get_value_from_metadata(- "channel", "web"- )+ channel = get_checkout_metadata(checkout).get_value_from_metadata("channel", "web")return {"merchantAccount": merchant_account,"countryCode": country_code,diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 80e61e2908..3b86c8d41f 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -194,9 +194,9 @@ def create_payment_information(email = cast(str, checkout.get_customer_email())user_id = checkout.user_idcheckout_token = str(checkout.token)- from ..checkout.utils import get_or_create_checkout_metadata+ from ..checkout.utils import get_checkout_metadata- checkout_metadata = get_or_create_checkout_metadata(checkout).metadata+ checkout_metadata = get_checkout_metadata(checkout).metadataelif order := payment.order:billing = order.billing_addressshipping = order.shipping_addressdiff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex b8cebf24a1..dc8ac8fd6d 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -26,7 +26,7 @@ from ..attribute.models import AttributeValueTranslationfrom ..checkout import base_calculationsfrom ..checkout.fetch import CheckoutInfo, CheckoutLineInfofrom ..checkout.models import Checkout-from ..checkout.utils import get_or_create_checkout_metadata+from ..checkout.utils import get_checkout_metadatafrom ..core.prices import quantize_price, quantize_price_fieldsfrom ..core.utils import build_absolute_urifrom ..core.utils.anonymization import (@@ -592,12 +592,12 @@ def generate_checkout_payload(# a checkout payload"token": graphene.Node.to_global_id("Checkout", checkout.token),"metadata": (- lambda c=checkout: get_or_create_checkout_metadata(c).metadata+ lambda c=checkout: get_checkout_metadata(c).metadataif hasattr(c, "metadata_storage")else {}),"private_metadata": (- lambda c=checkout: get_or_create_checkout_metadata(c).private_metadata+ lambda c=checkout: get_checkout_metadata(c).private_metadataif hasattr(c, "metadata_storage")else {}),@@ -1344,7 +1344,7 @@ def generate_checkout_payload_for_tax_calculation("discounts": discounts,"lines": lines_dict_data,"metadata": (- lambda c=checkout: get_or_create_checkout_metadata(c).metadata+ lambda c=checkout: get_checkout_metadata(c).metadataif hasattr(c, "metadata_storage")else {}),