Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Always create checkout metadata for new checkouts (#17176)

Maciej Korycinski331e18a7fe99
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 196381dc4b..40fe24787d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,7 +39,6 @@ All notable, unreleased changes to this project will be documented in this file.
- Truncate lenghty responses in `EventDeliveryAttempt` objects - #17044 by @wcislo-saleor
### Other changes
-
- Added support for numeric and lower-case boolean environment variables - #16313 by @NyanKiyoshi
- Fixed a potential crash when Checkout metadata is accessed with high concurrency - #16411 by @patrys
- Add slugs to product/category/collection/page translations. Allow to query by translated slug - #16449 by @delemeator
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 35484a8505..798401982c 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -706,19 +706,21 @@ def _create_order(
# assign checkout payments to the order
checkout.payments.update(order=order)
- checkout_metadata = get_checkout_metadata(checkout)
# store current tax configuration
update_order_display_gross_prices(order)
+ checkout_metadata = get_checkout_metadata(checkout)
# copy metadata from the checkout into the new order
- order.metadata = checkout_metadata.metadata
+ if checkout_metadata:
+ order.metadata = checkout_metadata.metadata
+ order.private_metadata = checkout_metadata.private_metadata
+
if metadata_list:
order.store_value_in_metadata({data.key: data.value for data in metadata_list})
order.redirect_url = checkout.redirect_url
- order.private_metadata = checkout_metadata.private_metadata
if private_metadata_list:
order.store_value_in_private_metadata(
{data.key: data.value for data in private_metadata_list}
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index fc8fabfc78..192918cf2e 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -39,7 +39,7 @@ from ..fetch import (
fetch_checkout_info,
fetch_checkout_lines,
)
-from ..models import Checkout, CheckoutLine
+from ..models import Checkout, CheckoutLine, CheckoutMetadata
from ..utils import (
PRIVATE_META_APP_SHIPPING_ID,
add_voucher_to_checkout,
@@ -48,7 +48,7 @@ from ..utils import (
change_billing_address_in_checkout,
change_shipping_address_in_checkout,
clear_delivery_method,
- delete_external_shipping_id,
+ delete_external_shipping_id_if_present,
get_checkout_metadata,
get_external_shipping_id,
get_voucher_discount_for_checkout,
@@ -359,6 +359,52 @@ def test_clear_delivery_method(checkout, shipping_method):
assert isinstance(checkout_info.delivery_method_info, DeliveryMethodBase)
[email protected](CheckoutMetadata, "save")
+def test_clear_delivery_method_do_not_update_metadata_when_no_external_shipping(
+ mocked_metadata_save, checkout, shipping_method
+):
+ # given
+ checkout.shipping_method = shipping_method
+ checkout.save()
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, [], manager)
+
+ # when
+ clear_delivery_method(checkout_info)
+
+ # then
+ checkout.refresh_from_db()
+ assert not mocked_metadata_save.called
+ assert not checkout.shipping_method
+ assert isinstance(checkout_info.delivery_method_info, DeliveryMethodBase)
+
+
[email protected](CheckoutMetadata, "save")
+def test_clear_delivery_method_update_metadata_when_external_shipping(
+ mocked_metadata_save, checkout, shipping_method
+):
+ # given
+ checkout.shipping_method = shipping_method
+ checkout.metadata_storage.private_metadata = {PRIVATE_META_APP_SHIPPING_ID: "ID"}
+ checkout.metadata_storage.save()
+ checkout.save()
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, [], manager)
+
+ # when
+ clear_delivery_method(checkout_info)
+
+ # then
+ checkout.refresh_from_db()
+ checkout.metadata_storage.refresh_from_db()
+ assert mocked_metadata_save.called
+ assert not checkout.shipping_method
+ assert isinstance(checkout_info.delivery_method_info, DeliveryMethodBase)
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+
+
def test_last_change_update(checkout):
with freeze_time(datetime.datetime.now(tz=datetime.UTC)):
assert checkout.last_change != datetime.datetime.now(tz=datetime.UTC)
@@ -2187,19 +2233,60 @@ def test_checkout_without_delivery_method_creates_empty_delivery_method(
assert not delivery_method_info.is_method_in_valid_methods(checkout_info)
-def test_manage_external_shipping_id(checkout):
+def test_set_external_shipping_id(checkout):
+ # given
app_shipping_id = "abcd"
initial_private_metadata = {"test": 123}
checkout.metadata_storage.private_metadata = initial_private_metadata
checkout.metadata_storage.save()
+ # when
set_external_shipping_id(checkout, app_shipping_id)
+
+ # then
assert PRIVATE_META_APP_SHIPPING_ID in checkout.metadata_storage.private_metadata
+
+def test_get_external_shipping_id(checkout):
+ # given
+ app_shipping_id = "abcd"
+ initial_private_metadata = {"test": 123}
+ checkout.metadata_storage.private_metadata = initial_private_metadata
+ checkout.metadata_storage.save()
+ set_external_shipping_id(checkout, app_shipping_id)
+
+ # when
shipping_id = get_external_shipping_id(checkout)
+
+ # then
assert shipping_id == app_shipping_id
- delete_external_shipping_id(checkout)
+
+def test_delete_external_shipping_id(checkout):
+ # given
+ app_shipping_id = "abcd"
+ initial_private_metadata = {"test": 123}
+ checkout.metadata_storage.private_metadata = initial_private_metadata
+ checkout.metadata_storage.save()
+ set_external_shipping_id(checkout, app_shipping_id)
+
+ # when
+ delete_external_shipping_id_if_present(checkout)
+
+ # then
+ assert checkout.metadata_storage.private_metadata == initial_private_metadata
+
+
+def test_delete_external_shipping_id_when_external_shipping_missing(checkout):
+ # given
+ initial_private_metadata = {"test": 123}
+ checkout.metadata_storage.private_metadata = initial_private_metadata
+ checkout.metadata_storage.save()
+
+ # when
+ delete_external_shipping_id_if_present(checkout)
+
+ # then
assert checkout.metadata_storage.private_metadata == initial_private_metadata
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index dcc2df5c2a..8c5ab37d1f 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1018,7 +1018,6 @@ def clear_delivery_method(checkout_info: "CheckoutInfo"):
shipping_channel_listings=checkout_info.shipping_channel_listings,
)
- delete_external_shipping_id(checkout=checkout)
checkout.save(
update_fields=[
"shipping_method",
@@ -1026,7 +1025,7 @@ def clear_delivery_method(checkout_info: "CheckoutInfo"):
"last_change",
]
)
- get_checkout_metadata(checkout).save()
+ delete_external_shipping_id_if_present(checkout=checkout)
def is_fully_paid(
@@ -1102,24 +1101,38 @@ def set_external_shipping_id(checkout: Checkout, app_shipping_id: str):
metadata.store_value_in_private_metadata(
{PRIVATE_META_APP_SHIPPING_ID: app_shipping_id}
)
+ metadata.save()
def get_external_shipping_id(container: Union["Checkout", "Order"]):
- metadata_object: ModelWithMetadata
+ metadata_object: ModelWithMetadata | None
if isinstance(container, Checkout):
metadata_object = get_checkout_metadata(container)
else:
metadata_object = container
+ if not metadata_object:
+ return None
return metadata_object.get_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)
-def delete_external_shipping_id(checkout: Checkout, save: bool = False):
- metadata = get_or_create_checkout_metadata(checkout)
- metadata.delete_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)
- if save:
+def delete_external_shipping_id_if_present(checkout: Checkout):
+ """Delete external shipping key if present in metadata."""
+ metadata = get_checkout_metadata(checkout)
+ if not metadata:
+ return
+
+ field_deleted = metadata.delete_value_from_private_metadata(
+ PRIVATE_META_APP_SHIPPING_ID
+ )
+ if field_deleted:
metadata.save(update_fields=["private_metadata"])
+@allow_writer()
+def create_checkout_metadata(checkout: "Checkout"):
+ return CheckoutMetadata.objects.create(checkout=checkout)
+
+
@allow_writer()
def get_or_create_checkout_metadata(checkout: "Checkout") -> CheckoutMetadata:
if hasattr(checkout, "metadata_storage"):
@@ -1129,11 +1142,11 @@ def get_or_create_checkout_metadata(checkout: "Checkout") -> CheckoutMetadata:
@allow_writer()
-def get_checkout_metadata(checkout: "Checkout"):
+def get_checkout_metadata(checkout: "Checkout") -> CheckoutMetadata | None:
if hasattr(checkout, "metadata_storage"):
# TODO: load metadata_storage with dataloader and pass as an argument
return checkout.metadata_storage
- return CheckoutMetadata(checkout=checkout)
+ return None
def calculate_checkout_weight(lines: list["CheckoutLineInfo"]) -> "Weight":
diff --git a/saleor/core/models.py b/saleor/core/models.py
index 93e15ab211..ba97a97659 100644
--- a/saleor/core/models.py
+++ b/saleor/core/models.py
@@ -101,9 +101,11 @@ class ModelWithMetadata(models.Model):
def clear_private_metadata(self):
self.private_metadata = {}
- def delete_value_from_private_metadata(self, key: str):
+ def delete_value_from_private_metadata(self, key: str) -> bool:
if key in self.private_metadata:
del self.private_metadata[key]
+ return True
+ return False
def get_value_from_metadata(self, key: str, default: Any = None) -> Any:
return self.metadata.get(key, default)
diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.py
index b18fce6d2a..f2e4c32f49 100644
--- a/saleor/graphql/checkout/mutations/checkout_create.py
+++ b/saleor/graphql/checkout/mutations/checkout_create.py
@@ -6,7 +6,7 @@ from django.conf import settings
from ....checkout import AddressType, models
from ....checkout.actions import call_checkout_event
from ....checkout.error_codes import CheckoutErrorCode
-from ....checkout.utils import add_variants_to_checkout
+from ....checkout.utils import add_variants_to_checkout, create_checkout_metadata
from ....core.tracing import traced_atomic_transaction
from ....core.utils.country import get_active_country
from ....product import models as product_models
@@ -375,6 +375,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
instance.billing_address = billing_address.get_copy()
instance.save()
+ create_checkout_metadata(instance)
@classmethod
def get_instance(cls, info: ResolveInfo, **data):
diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
index 317e0501c6..c5aa0bdbd8 100644
--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
@@ -10,8 +10,7 @@ from ....checkout.fetch import (
fetch_checkout_lines,
)
from ....checkout.utils import (
- delete_external_shipping_id,
- get_or_create_checkout_metadata,
+ delete_external_shipping_id_if_present,
invalidate_checkout,
is_shipping_required,
set_external_shipping_id,
@@ -247,7 +246,7 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
checkout=checkout, app_shipping_id=external_shipping_method.id
)
else:
- delete_external_shipping_id(checkout=checkout)
+ delete_external_shipping_id_if_present(checkout=checkout)
# Clear checkout shipping address if it was switched from C&C.
if checkout.collection_point_id and not collection_point:
@@ -266,7 +265,6 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
checkout.save(
update_fields=checkout_fields_to_update + invalidate_prices_updated_fields
)
- get_or_create_checkout_metadata(checkout).save()
call_checkout_info_event(
manager,
event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
index eb5d4bcd84..b14897e0c9 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
@@ -5,8 +5,7 @@ from ....checkout.actions import call_checkout_info_event
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import (
- delete_external_shipping_id,
- get_checkout_metadata,
+ delete_external_shipping_id_if_present,
invalidate_checkout,
is_shipping_required,
set_external_shipping_id,
@@ -209,7 +208,6 @@ class CheckoutShippingMethodUpdate(BaseMutation):
checkout_info, lines, delivery_method=delivery_method
)
- delete_external_shipping_id(checkout=checkout)
checkout.shipping_method = shipping_method
invalidate_prices_updated_fields = invalidate_checkout(
checkout_info, lines, manager, save=False
@@ -220,7 +218,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):
]
+ invalidate_prices_updated_fields
)
- get_checkout_metadata(checkout).save()
+ delete_external_shipping_id_if_present(checkout=checkout)
call_checkout_info_event(
manager,
@@ -261,7 +259,6 @@ class CheckoutShippingMethodUpdate(BaseMutation):
]
+ invalidate_prices_updated_fields
)
- get_checkout_metadata(checkout).save()
call_checkout_info_event(
manager,
event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
@@ -274,7 +271,6 @@ class CheckoutShippingMethodUpdate(BaseMutation):
@classmethod
def remove_shipping_method(cls, checkout, checkout_info, lines, manager):
checkout.shipping_method = None
- delete_external_shipping_id(checkout=checkout)
invalidate_prices_updated_fields = invalidate_checkout(
checkout_info, lines, manager, save=False
)
@@ -284,7 +280,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):
]
+ invalidate_prices_updated_fields
)
- get_checkout_metadata(checkout).save()
+ delete_external_shipping_id_if_present(checkout=checkout)
call_checkout_info_event(
manager,
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index e8e72d9d34..ae195a59f2 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -19,7 +19,7 @@ from ....checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ....checkout.utils import (
calculate_checkout_quantity,
clear_delivery_method,
- delete_external_shipping_id,
+ delete_external_shipping_id_if_present,
get_external_shipping_id,
is_shipping_required,
)
@@ -103,7 +103,7 @@ def update_checkout_external_shipping_method_if_invalid(
checkout_info: "CheckoutInfo", lines: list[CheckoutLineInfo]
):
if not _is_external_shipping_valid(checkout_info):
- delete_external_shipping_id(checkout_info.checkout, save=True)
+ delete_external_shipping_id_if_present(checkout_info.checkout)
def update_checkout_shipping_method_if_invalid(
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index ad5b2e9df0..3d976ec112 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -417,7 +417,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(82):
+ with django_assert_num_queries(83):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -435,7 +435,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(82):
+ with django_assert_num_queries(83):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -567,7 +567,7 @@ def test_create_checkout_with_order_promotion(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(87):
+ with django_assert_num_queries(88):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
index cf96d7f2c1..4b7a0a9cae 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
@@ -322,6 +322,66 @@ def test_checkout_delivery_method_update_external_shipping(
)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
+ "clean_delivery_method"
+)
+def test_checkout_delivery_method_update_deletes_external_shipping_when_not_valid(
+ mock_clean_delivery,
+ mock_send_request,
+ api_client,
+ checkout_with_item_for_cc,
+ settings,
+ shipping_app,
+ channel_USD,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_item_for_cc
+ query = MUTATION_UPDATE_DELIVERY_METHOD
+ mock_clean_delivery.return_value = True
+
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "abcd"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": "Provider - Economy",
+ "amount": "10",
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mock_send_request.return_value = mock_json_response
+
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+
+ checkout.metadata_storage.private_metadata = {
+ PRIVATE_META_APP_SHIPPING_ID: graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+ }
+ checkout.metadata_storage.save()
+
+ # when
+ response = api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ checkout.refresh_from_db()
+
+ errors = data["errors"]
+
+ assert not errors
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+
+
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_checkout_delivery_method_update_external_shipping_invalid_currency(
mock_send_request,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
index 0d5b6e097d..550f73562d 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
@@ -143,6 +143,62 @@ def test_checkout_shipping_method_update_external_shipping_method(
assert PRIVATE_META_APP_SHIPPING_ID in checkout.metadata_storage.private_metadata
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_checkout_shipping_method_update_deletes_external_shipping_when_not_valid(
+ mock_send_request,
+ staff_api_client,
+ address,
+ checkout_with_item,
+ shipping_app,
+ channel_USD,
+ settings,
+ shipping_method,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "abcd"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": "Provider - Economy",
+ "amount": "10",
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mock_send_request.return_value = mock_json_response
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+
+ checkout.metadata_storage.private_metadata = {
+ PRIVATE_META_APP_SHIPPING_ID: graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+ }
+ checkout.metadata_storage.save()
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ checkout.refresh_from_db()
+
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["token"] == str(checkout_with_item.token)
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+
+
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_checkout_shipping_method_update_external_shipping_method_with_tax_plugin(
mock_send_request,
diff --git a/saleor/graphql/meta/mutations/utils.py b/saleor/graphql/meta/mutations/utils.py
index 3855d168f4..58cdcaeea7 100644
--- a/saleor/graphql/meta/mutations/utils.py
+++ b/saleor/graphql/meta/mutations/utils.py
@@ -7,11 +7,6 @@ from ....core.error_codes import MetadataErrorCode
from ....core.models import ModelWithMetadata
-# `instance = get_checkout_metadata(instance)` is calling the
-# `get_checkout_metadata` function to retrieve the metadata associated with a
-# checkout instance. This function is defined in the `.../checkout/utils.py` file
-# and takes a `Checkout` instance as an argument. It returns a dictionary
-# containing the metadata associated with the checkout.
def get_valid_metadata_instance(instance) -> ModelWithMetadata:
if isinstance(instance, Checkout):
instance = get_or_create_checkout_metadata(instance)
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
index 5c8d0305e0..d7518d1614 100644
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -357,7 +357,12 @@ def request_data_for_gateway_config(
country_code = country.code
else:
country_code = Country(settings.DEFAULT_COUNTRY).code
- channel = get_checkout_metadata(checkout).get_value_from_metadata("channel", "web")
+ checkout_metadata = get_checkout_metadata(checkout)
+ if checkout_metadata:
+ channel = checkout_metadata.get_value_from_metadata("channel", "web")
+ else:
+ channel = "web"
+
return {
"merchantAccount": merchant_account,
"countryCode": country_code,
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index eb1c69aca2..6f9a73b539 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -269,7 +269,10 @@ def create_payment_information(
checkout_token = str(checkout.token)
from ..checkout.utils import get_checkout_metadata
- checkout_metadata = get_checkout_metadata(checkout).metadata
+ checkout_metadata = None
+ checkout_metadata_storage = get_checkout_metadata(checkout)
+ if checkout_metadata_storage:
+ checkout_metadata = checkout_metadata_storage.metadata
elif order := payment.order:
billing = order.billing_address
shipping = order.shipping_address
@@ -988,9 +991,11 @@ def parse_transaction_action_data(
TransactionRequestResponse(
psp_reference=psp_reference,
available_actions=available_actions,
- event=TransactionRequestEventResponse(**parsed_event_data)
- if parsed_event_data
- else None,
+ event=(
+ TransactionRequestEventResponse(**parsed_event_data)
+ if parsed_event_data
+ else None
+ ),
),
None,
)
@@ -1555,9 +1560,9 @@ def get_transaction_item_params(
):
return {
"name": name,
- "checkout_id": source_object.pk
- if isinstance(source_object, Checkout)
- else None,
+ "checkout_id": (
+ source_object.pk if isinstance(source_object, Checkout) else None
+ ),
"order_id": source_object.pk if isinstance(source_object, Order) else None,
"currency": source_object.currency,
"app": app,
@@ -1633,9 +1638,11 @@ def handle_transaction_initialize_session(
amount_value=amount,
defaults={
"include_in_calculations": False,
- "type": TransactionEventType.CHARGE_REQUEST
- if action == TransactionFlowStrategy.CHARGE
- else TransactionEventType.AUTHORIZATION_REQUEST,
+ "type": (
+ TransactionEventType.CHARGE_REQUEST
+ if action == TransactionFlowStrategy.CHARGE
+ else TransactionEventType.AUTHORIZATION_REQUEST
+ ),
"currency": transaction_item.currency,
"amount_value": amount,
"idempotency_key": idempotency_key,
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 2b054f895c..a28a7ab22f 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -4,12 +4,7 @@ from collections import defaultdict
from collections.abc import Iterable
from dataclasses import asdict
from decimal import Decimal
-from typing import (
- TYPE_CHECKING,
- Any,
- Optional,
- Union,
-)
+from typing import TYPE_CHECKING, Any, Optional, Union
import graphene
from django.db.models import F, QuerySet, Sum
@@ -337,11 +332,11 @@ def generate_order_payload(
"original": graphene.Node.to_global_id("Order", order.original_id),
"lines": json.loads(generate_order_lines_payload(lines)),
"fulfillments": json.loads(fulfillments_data),
- "collection_point": json.loads(
- _generate_collection_point_payload(order.collection_point)
- )[0]
- if order.collection_point
- else None,
+ "collection_point": (
+ json.loads(_generate_collection_point_payload(order.collection_point))[0]
+ if order.collection_point
+ else None
+ ),
"payments": json.loads(_generate_order_payment_payload(payments)),
"shipping_method": _generate_shipping_method_payload(
order.shipping_method, order.channel
@@ -580,25 +575,31 @@ def generate_checkout_payload(
checkout.shipping_method, checkout.channel
),
"lines": list(lines_dict_data),
- "collection_point": json.loads(
- _generate_collection_point_payload(checkout.collection_point)
- )[0]
- if checkout.collection_point
- else None,
+ "collection_point": (
+ json.loads(
+ _generate_collection_point_payload(checkout.collection_point)
+ )[0]
+ if checkout.collection_point
+ else None
+ ),
"meta": generate_meta(requestor_data=generate_requestor(requestor)),
"created": checkout.created_at,
# We add token as a graphql ID as it worked in that way since we introduce
# a checkout payload
"token": graphene.Node.to_global_id("Checkout", checkout.token),
"metadata": (
- lambda c=checkout: get_checkout_metadata(c).metadata
- if hasattr(c, "metadata_storage")
- else {}
+ lambda c=checkout: (
+ get_checkout_metadata(c).metadata # type: ignore[union-attr]
+ if hasattr(c, "metadata_storage")
+ else {}
+ )
),
"private_metadata": (
- lambda c=checkout: get_checkout_metadata(c).private_metadata
- if hasattr(c, "metadata_storage")
- else {}
+ lambda c=checkout: (
+ get_checkout_metadata(c).private_metadata # type: ignore[union-attr]
+ if hasattr(c, "metadata_storage")
+ else {}
+ )
),
},
)
@@ -660,9 +661,11 @@ def generate_collection_payload(
"metadata",
],
extra_dict_data={
- "background_image": build_absolute_uri(collection.background_image.url)
- if collection.background_image
- else None,
+ "background_image": (
+ build_absolute_uri(collection.background_image.url)
+ if collection.background_image
+ else None
+ ),
"meta": generate_meta(requestor_data=generate_requestor(requestor)),
},
)
@@ -908,15 +911,19 @@ def generate_fulfillment_lines_payload(fulfillment: Fulfillment):
"product_sku": lambda fl: fl.order_line.product_sku,
"product_variant_id": lambda fl: fl.order_line.product_variant_id,
"weight": (
- lambda fl: fl.order_line.variant.get_weight().g
- if fl.order_line.variant
- else None
+ lambda fl: (
+ fl.order_line.variant.get_weight().g
+ if fl.order_line.variant
+ else None
+ )
),
"weight_unit": "gram",
"product_type": (
- lambda fl: fl.order_line.variant.product.product_type.name
- if fl.order_line.variant
- else None
+ lambda fl: (
+ fl.order_line.variant.product.product_type.name
+ if fl.order_line.variant
+ else None
+ )
),
"unit_price_net": lambda fl: quantize_price(
fl.order_line.unit_price_net_amount, fl.order_line.currency
@@ -951,11 +958,11 @@ def generate_fulfillment_lines_payload(fulfillment: Fulfillment):
* fl.quantity
),
"currency": lambda fl: fl.order_line.currency,
- "warehouse_id": lambda fl: graphene.Node.to_global_id(
- "Warehouse", fl.stock.warehouse_id
- )
- if fl.stock
- else None,
+ "warehouse_id": lambda fl: (
+ graphene.Node.to_global_id("Warehouse", fl.stock.warehouse_id)
+ if fl.stock
+ else None
+ ),
"sale_id": lambda fl: fl.order_line.sale_id,
"voucher_code": lambda fl: fl.order_line.voucher_code,
},
@@ -1355,9 +1362,11 @@ def generate_checkout_payload_for_tax_calculation(
"discounts": discounts,
"lines": lines_dict_data,
"metadata": (
- lambda c=checkout: get_checkout_metadata(c).metadata
- if hasattr(c, "metadata_storage")
- else {}
+ lambda c=checkout: (
+ get_checkout_metadata(c).metadata # type: ignore[union-attr]
+ if hasattr(c, "metadata_storage")
+ else {}
+ )
),
},
)
@@ -1383,9 +1392,9 @@ def _generate_order_lines_payload_for_tax_calculation(lines: QuerySet[OrderLine]
lambda line: line.variant.product.metadata if line.variant else {}
),
"product_type_metadata": (
- lambda line: line.variant.product.product_type.metadata
- if line.variant
- else {}
+ lambda line: (
+ line.variant.product.product_type.metadata if line.variant else {}
+ )
),
"charge_taxes": (lambda _line: charge_taxes),
"sku": (lambda line: line.product_sku),