Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Metadata support in CheckoutLinesUpdate (#17523)
Lukasz Ostrowski5477b7dd3867
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2473c1f71a..f955f75dbe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -58,6 +58,8 @@ All notable, unreleased changes to this project will be documented in this file.- Deprecate `draftOrderInput.discount` field - #17294 by @zedzior- `GiftCardCreate` and `GiftCardUpdate` mutations now allows to set `metadata` and `privateMetadata` fields via `GiftCardCreateInput` and `GiftCardUpdateInput` - #17399 by @lkostrowski- Improved error handling when trying to set invalid metadata. Now, invalid metadata should properly return `error.field` containing `metadata` or `privateMetadata`, instead generic `input` - #17470 by @lkostrowski+- `CheckoutLinesUpdate` now accepts `metadata` for each line in the input. That means updating checkout lines and metadata of checkout lines can be done in single mutations - #17523 by @lkostrowski+- `CheckoutLinesAdd` now properly validates `metadata` provided in input - #17523 by @lkostrowski- `CheckoutCreateInput` now accepts `metadata` and `privateMetadata` fields, so `checkoutCreate` can now create checkout with metadata in a single call - #17503 by @lkostrowski- `orderUpdate` mutation now allows to update `metadata` and `privateMetadata` via `OrderUpdateInput` - #1508 by @lkostrowskidiff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex b3ee96133b..a5b14cc9f8 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -1,4 +1,5 @@import graphene+from django.core.exceptions import ValidationErrorfrom ....checkout.actions import call_checkout_info_eventfrom ....checkout.error_codes import CheckoutErrorCode@@ -8,6 +9,7 @@ from ....checkout.fetch import (update_delivery_method_lists_for_checkout_info,)from ....checkout.utils import add_variants_to_checkout, invalidate_checkout+from ....core.utils import metadata_managerfrom ....warehouse.reservations import get_reservation_length, is_reservation_enabledfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...app.dataloaders import get_app_promise@@ -15,6 +17,7 @@ from ...core import ResolveInfofrom ...core.context import SyncWebhookControlContextfrom ...core.descriptions import DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_CHECKOUT+from ...core.enums import MetadataErrorCodefrom ...core.mutations import BaseMutationfrom ...core.scalars import UUIDfrom ...core.types import CheckoutError, NonNullList@@ -185,6 +188,21 @@ class CheckoutLinesAdd(BaseMutation):variants_ids_to_validate, checkout.channel_id)+ @classmethod+ def _validate_lines_metadata(cls, lines: list[CheckoutLineInput]):+ try:+ for line in lines:+ metadata_manager.create_from_graphql_input(line.metadata)+ except metadata_manager.MetadataEmptyKeyError:+ raise ValidationError(+ {+ "metadata": ValidationError(+ "Metadata key cannot be empty.",+ code=MetadataErrorCode.REQUIRED.value,+ )+ }+ ) from None+@classmethoddef perform_mutation( # type: ignore[override]cls,@@ -200,6 +218,11 @@ class CheckoutLinesAdd(BaseMutation):app = get_app_promise(info.context).get()check_permissions_for_custom_prices(app, lines)+ # Validate lines early, before clean input. This class pass to clean_input already modified payload+ # Hence common logic for validation pure input doesn't work.+ # At this point lines are raw so validation like checking metadata can be performed early+ cls._validate_lines_metadata(lines)+checkout = get_checkout(cls, info, checkout_id=checkout_id, token=token, id=id)manager = get_plugin_manager_promise(info.context).get()variants = cls._get_variants_from_lines_input(lines)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.pyindex b12363bc94..38063989b5 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py@@ -9,12 +9,13 @@ from ....webhook.event_types import WebhookEventAsyncTypefrom ...app.dataloaders import get_app_promisefrom ...checkout.types import CheckoutLinefrom ...core import ResolveInfo-from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.descriptions import ADDED_IN_321, DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_CHECKOUTfrom ...core.scalars import UUID, PositiveDecimalfrom ...core.types import BaseInputObjectType, CheckoutError, NonNullListfrom ...core.utils import WebhookEventInfofrom ...core.validators import validate_one_of_args_is_in_mutation+from ...meta.inputs import MetadataInput, MetadataInputDescriptionfrom ...product.types import ProductVariantfrom ...site.dataloaders import get_site_promisefrom ...utils import ERROR_COULD_NO_RESOLVE_GLOBAL_ID@@ -55,6 +56,15 @@ class CheckoutLineUpdateInput(BaseInputObjectType):required=False,)+ metadata = NonNullList(+ MetadataInput,+ description=(+ f"Checkout line public metadata. Will add and update keys. To delete keys use deleteMetadata mutation. {ADDED_IN_321} "+ f"{MetadataInputDescription.PUBLIC_METADATA_INPUT}"+ ),+ required=False,+ )+class Meta:doc_category = DOC_CATEGORY_CHECKOUTdiff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex 13d985804b..17cf080068 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -443,6 +443,7 @@ def group_lines_input_data_on_update(for line in lines:variant_id = cast(str, line.get("variant_id"))line_id = cast(str, line.get("line_id"))+ metadata_list = line.get("metadata")line_db_id, variant_db_id = None, Noneif line_id:@@ -472,6 +473,11 @@ def group_lines_input_data_on_update(line_data.custom_price = line["price"]line_data.custom_price_to_update = True+ if line_data.metadata_list and metadata_list:+ line_data.metadata_list += metadata_list+ else:+ line_data.metadata_list = metadata_list+grouped_checkout_lines_data += list(checkout_lines_data_map.values())return grouped_checkout_lines_datadiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex df38a0d312..51d36b3d35 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -734,6 +734,51 @@ def test_checkout_lines_add_with_new_variant_and_metadata(assert line.metadata == {metadata_key: metadata_value}+def test_checkout_lines_add_with_invalid_metadata(+ user_api_client,+ checkout_with_item,+ stock,+):+ # given+ checkout = checkout_with_item++ old_meta = {"old_key": "old_value"}+ # Empty key is invalid and should throw+ metadata_key = ""+ metadata_value = "md value"++ line = checkout.lines.first()+ line.store_value_in_metadata(old_meta)+ line.save(update_fields=["metadata"])++ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 3+ 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,+ "metadata": [{"key": metadata_key, "value": metadata_value}],+ }+ ],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]++ # then+ errors = data["errors"]++ assert errors[0]["code"] == "REQUIRED"+ assert errors[0]["field"] == "metadata"++@mock.patch("saleor.graphql.checkout.mutations.checkout_lines_add.""update_checkout_shipping_method_if_invalid",diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.pyindex 664b21efb4..94b1124fd1 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py@@ -1622,3 +1622,190 @@ def test_checkout_lines_update_when_line_deleted(user_api_client, checkout_with_assert len(data["errors"]) == 1assert data["errors"][0]["field"] == "lineId"assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name+++def test_checkout_lines_update_with_metadata(+ user_api_client,+ checkout_with_item,+):+ # given+ checkout = checkout_with_item++ assert checkout.lines.count() == 1++ line = checkout.lines.first()+ variant = line.variant++ assert not line.metadata.get("test_key")++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ "metadata": [{"key": "test_key", "value": "test_value"}],+ }+ ],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)++ # then+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]++ assert not data["errors"]++ checkout.refresh_from_db()++ assert checkout.lines.count() == 1++ line = checkout.lines.first()++ assert line.metadata["test_key"] == "test_value"++ assert line.variant == variant+++def test_checkout_lines_update_with_metadata_overwrite_key(+ user_api_client,+ checkout_with_item,+):+ # given+ checkout = checkout_with_item++ assert checkout.lines.count() == 1++ line = checkout.lines.first()+ variant = line.variant++ line.metadata["test_key"] = "old_value"++ line.save(update_fields=["metadata"])++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ "metadata": [{"key": "test_key", "value": "test_value"}],+ }+ ],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)++ # then+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]++ assert not data["errors"]++ checkout.refresh_from_db()++ assert checkout.lines.count() == 1++ line = checkout.lines.first()++ assert line.metadata["test_key"] == "test_value"++ assert line.variant == variant+++def test_checkout_lines_update_with_metadata_empty_list(+ user_api_client,+ checkout_with_item,+):+ # given+ checkout = checkout_with_item++ assert checkout.lines.count() == 1++ line = checkout.lines.first()+ variant = line.variant++ line.metadata["test_key"] = "old_value"++ line.save(update_fields=["metadata"])++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ # Empty list should not prune metadata+ "metadata": [],+ }+ ],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)++ # then+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]++ assert not data["errors"]++ checkout.refresh_from_db()++ assert checkout.lines.count() == 1++ line = checkout.lines.first()++ assert line.metadata["test_key"] == "old_value"++ assert line.variant == variant+++def test_checkout_lines_update_with_invalid_metadata(+ user_api_client,+ checkout_with_item,+):+ # given+ checkout = checkout_with_item++ assert checkout.lines.count() == 1++ line = checkout.lines.first()+ variant = line.variant++ assert not line.metadata.get("test_key")++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [+ {+ "variantId": variant_id,+ "quantity": 1,+ # Key can't be empty+ "metadata": [{"key": "", "value": "test_value"}],+ }+ ],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)++ # then+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]++ expected_error = data["errors"][0]++ assert expected_error["field"] == "metadata"+ assert expected_error["code"] == "REQUIRED"diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 5eb8f1e397..b7d385847d 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -27117,6 +27117,15 @@ input CheckoutLineUpdateInput @doc(category: "Checkout") {"""ID of the line."""lineId: ID++ """+ Checkout line public metadata. Will add and update keys. To delete keys use deleteMetadata mutation.++ Added in Saleor 3.21. Can be read by any API client authorized to read the object it's attached to.++ Warning: never store sensitive information, including financial data such as credit card details.+ """+ metadata: [MetadataInput!]}"""