Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use app identifier for shipping webhooks (#10780)
Iga Karbowiak0419d6da3be8
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex b450a3c81b..41b10b137a 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -436,6 +436,7 @@ def update_checkout_info_delivery_method_info(The attribute is lazy-evaluated avoid external API calls unless accessed."""+ from ..plugins.webhook.shipping import convert_to_app_id_with_identifierfrom .utils import get_external_shipping_iddelivery_method: Optional[Union[ShippingMethodData, Warehouse, Callable]] = None@@ -459,7 +460,12 @@ def update_checkout_info_delivery_method_info(methods = {method.id: method for method in checkout_info.all_shipping_methods}- return methods.get(external_shipping_method_id)+ if method := methods.get(external_shipping_method_id):+ return method+ new_shipping_method_id = convert_to_app_id_with_identifier(+ external_shipping_method_id+ )+ return methods.get(new_shipping_method_id)delivery_method = _resolve_external_methoddiff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex ccd1e28fba..14b8a4146e 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -79,6 +79,7 @@ def test_is_valid_delivery_method_external_method(mock_send_request, checkout_with_item, address, settings, shipping_app):settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ assert not shipping_app.identifierresponse_method_id = "abcd"mock_json_response = [{@@ -107,6 +108,80 @@ def test_is_valid_delivery_method_external_method(assert delivery_method_info.is_method_in_valid_methods(checkout_info)+@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_is_valid_delivery_method_external_method_shipping_app_id_with_identifier(+ mock_send_request, checkout_with_item, address, settings, shipping_app+):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ shipping_app.identifier = "abcd"+ shipping_app.save(update_fields=["identifier"])++ response_method_id = "123"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.identifier}:{response_method_id}"+ )++ mock_send_request.return_value = mock_json_response+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.private_metadata = {PRIVATE_META_APP_SHIPPING_ID: method_id}+ checkout.save()++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ delivery_method_info = checkout_info.delivery_method_info++ assert delivery_method_info.is_method_in_valid_methods(checkout_info)+++@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_is_valid_delivery_method_external_method_old_shipping_app_id(+ mock_send_request, checkout_with_item, address, settings, shipping_app+):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ shipping_app.identifier = "abcd"+ shipping_app.save(update_fields=["identifier"])++ response_method_id = "123"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ mock_send_request.return_value = mock_json_response+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.private_metadata = {PRIVATE_META_APP_SHIPPING_ID: method_id}+ checkout.save()++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ delivery_method_info = checkout_info.delivery_method_info++ assert delivery_method_info.is_method_in_valid_methods(checkout_info)++@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")def test_is_valid_delivery_method_external_method_no_longer_available(mock_send_request, checkout_with_item, address, settings, shipping_appdiff --git a/saleor/graphql/checkout/tests/benchmark/test_homepage.py b/saleor/graphql/checkout/tests/benchmark/test_homepage.pyindex caf8f7d387..14d6b39b09 100644--- a/saleor/graphql/checkout/tests/benchmark/test_homepage.py+++ b/saleor/graphql/checkout/tests/benchmark/test_homepage.py@@ -4,6 +4,7 @@ import pytestfrom django.utils import timezonefrom .....checkout.utils import set_external_shipping_id+from .....plugins.webhook.shipping import to_shipping_app_idfrom ....tests.utils import get_graphql_content@@ -148,6 +149,7 @@ def test_user_checkout_details(user_api_client, customer_checkout, count_queries@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")def test_user_checkout_details_with_external_shipping_method(mock_send_request,+ app,user_api_client,customer_checkout,shipping_app,@@ -155,7 +157,7 @@ def test_user_checkout_details_with_external_shipping_method():# givensettings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- external_id = "abcd"+ external_id = to_shipping_app_id(app, "abcd")mock_json_response = [{"id": external_id,diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 491dae9875..40cfde0d64 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -1386,8 +1386,7 @@ class WebhookPlugin(BasePlugin):)if response_data:shipping_methods = parse_list_shipping_methods_response(- response_data,- webhook.app_id,+ response_data, webhook.app)methods.extend(shipping_methods)return methodsdiff --git a/saleor/plugins/webhook/shipping.py b/saleor/plugins/webhook/shipping.pyindex 5a908fdda5..faaa4ecfdd 100644--- a/saleor/plugins/webhook/shipping.py+++ b/saleor/plugins/webhook/shipping.py@@ -9,6 +9,7 @@ from django.db.models import QuerySetfrom graphql import GraphQLErrorfrom prices import Money+from ...app.models import Appfrom ...checkout.models import Checkoutfrom ...graphql.core.utils import from_global_id_or_errorfrom ...graphql.shipping.types import ShippingMethod@@ -23,14 +24,36 @@ from .utils import APP_ID_PREFIXlogger = logging.getLogger(__name__)-def to_shipping_app_id(app_id: int, shipping_method_id: str) -> "str":+def to_shipping_app_id(app: "App", shipping_method_id: str) -> "str":+ app_identifier = app.identifier or app.idreturn base64.b64encode(- str.encode(f"{APP_ID_PREFIX}:{app_id}:{shipping_method_id}")+ str.encode(f"{APP_ID_PREFIX}:{app_identifier}:{shipping_method_id}")).decode("utf-8")+def convert_to_app_id_with_identifier(shipping_app_id: str):+ """Prepare the shipping_app_id in format `app:<app-identifier>/method_id>`.++ The format of shipping_app_id has been changes so we need to support both of them.+ This method is preparing the new shipping_app_id format based on assumptions+ that right now the old one is used which is `app:<app-pk>:method_id>`+ """+ decoded_id = base64.b64decode(shipping_app_id).decode()+ splitted_id = decoded_id.split(":")+ if len(splitted_id) != 3:+ return+ try:+ app_id = int(splitted_id[1])+ except (TypeError, ValueError):+ return None+ app = App.objects.filter(id=app_id).first()+ if app is None:+ return None+ return to_shipping_app_id(app, splitted_id[2])++def parse_list_shipping_methods_response(- response_data: Any, app_id: int+ response_data: Any, app: "App") -> List["ShippingMethodData"]:shipping_methods = []for shipping_method_data in response_data:@@ -42,7 +65,7 @@ def parse_list_shipping_methods_response(shipping_methods.append(ShippingMethodData(- id=to_shipping_app_id(app_id, method_id),+ id=to_shipping_app_id(app, method_id),name=method_name,price=Money(method_amount, method_currency),maximum_delivery_days=method_maximum_delivery_days,diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.pyindex 618b2ea3f8..6f57ba6246 100644--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py@@ -349,8 +349,10 @@ def test_parse_excluded_shipping_methods_response(app):},]}+# whenexcluded_methods = get_excluded_shipping_methods_from_response(response)+# thenassert len(excluded_methods) == 2assert excluded_methods[0]["id"] == "2"