Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor webhook.transport.utils.py file (#17761)
Iga Karbowiak96c4c8802926
diff --git a/saleor/core/tests/test_taxes.py b/saleor/core/tests/test_taxes.pyindex 0389745918..92727f3748 100644--- a/saleor/core/tests/test_taxes.py+++ b/saleor/core/tests/test_taxes.py@@ -10,7 +10,7 @@ from ...permission.enums import ()from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ...webhook.models import Webhook, WebhookEvent-from ...webhook.transport.utils import get_current_tax_app+from ...webhook.transport.taxes import get_current_tax_app@pytest.fixturediff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 5e4ee966b3..3d47c961e2 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -109,6 +109,10 @@ from ...webhook.transport.list_stored_payment_methods import (get_response_for_stored_payment_method_request_delete,invalidate_cache_for_stored_payment_methods,)+from ...webhook.transport.payment import (+ parse_list_payment_gateways_response,+ parse_payment_action_response,+)from ...webhook.transport.shipping import (get_cache_data_for_shipping_list_methods_for_checkout,get_excluded_shipping_data,@@ -120,17 +124,17 @@ from ...webhook.transport.synchronous.transport import (trigger_webhook_sync,trigger_webhook_sync_if_not_cached,)-from ...webhook.transport.utils import (+from ...webhook.transport.taxes import (DEFAULT_TAX_CODE,DEFAULT_TAX_DESCRIPTION,+ get_current_tax_app,+ parse_tax_data,+)+from ...webhook.transport.utils import (delivery_update,from_payment_app_id,- get_current_tax_app,get_meta_code_key,get_meta_description_key,- parse_list_payment_gateways_response,- parse_payment_action_response,- parse_tax_data,)from ...webhook.utils import get_webhooks_for_eventfrom ..base_plugin import BasePlugin, ExcludedShippingMethoddiff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.pyindex 1d85484b9d..58ac210047 100644--- a/saleor/plugins/webhook/tests/test_payment_webhook.py+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py@@ -19,14 +19,16 @@ from ....payment.utils import create_payment_informationfrom ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....webhook.models import Webhook, WebhookEventfrom ....webhook.transport import signature_for_payload+from ....webhook.transport.payment import (+ parse_list_payment_gateways_response,+ parse_payment_action_response,+)from ....webhook.transport.synchronous.transport import (send_webhook_request_sync,trigger_webhook_sync,)from ....webhook.transport.utils import (from_payment_app_id,- parse_list_payment_gateways_response,- parse_payment_action_response,to_payment_app_id,)from .utils import generate_request_headersdiff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.pyindex b706411b57..fb9d848ca8 100644--- a/saleor/plugins/webhook/tests/test_tax_webhook.py+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py@@ -12,7 +12,7 @@ from ....core.taxes import TaxDataError, TaxTypefrom ....graphql.webhook.utils import get_subscription_query_hashfrom ....webhook.event_types import WebhookEventSyncTypefrom ....webhook.payloads import generate_order_payload_for_tax_calculation-from ....webhook.transport.utils import (+from ....webhook.transport.taxes import (DEFAULT_TAX_CODE,DEFAULT_TAX_DESCRIPTION,parse_tax_data,diff --git a/saleor/webhook/tests/test_payment_webhook_utils.py b/saleor/webhook/tests/test_payment_webhook_utils.pyindex e76a2f528c..d87a81d74c 100644--- a/saleor/webhook/tests/test_payment_webhook_utils.py+++ b/saleor/webhook/tests/test_payment_webhook_utils.py@@ -4,11 +4,13 @@ from ...core import EventDeliveryStatus, private_storagefrom ...core.models import EventDelivery, EventPayloadfrom ...payment import TransactionKindfrom ..const import APP_ID_PREFIX+from ..transport.payment import (+ parse_list_payment_gateways_response,+ parse_payment_action_response,+)from ..transport.utils import (clear_successful_delivery,from_payment_app_id,- parse_list_payment_gateways_response,- parse_payment_action_response,to_payment_app_id,)diff --git a/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py b/saleor/webhook/tests/test_sync_webhooks_for_removed_app.pyindex 203861efc4..557b006842 100644--- a/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py+++ b/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py@@ -5,7 +5,7 @@ from django.utils import timezonefrom ...core.models import EventDelivery, EventPayloadfrom ..event_types import WebhookEventSyncTypefrom ..transport.synchronous.transport import trigger_taxes_all_webhooks_sync-from ..transport.utils import parse_tax_data+from ..transport.taxes import parse_tax_data@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")diff --git a/saleor/webhook/tests/test_tax_webhook_tasks.py b/saleor/webhook/tests/test_tax_webhook_tasks.pyindex acf3fe65de..38eec92311 100644--- a/saleor/webhook/tests/test_tax_webhook_tasks.py+++ b/saleor/webhook/tests/test_tax_webhook_tasks.py@@ -7,7 +7,7 @@ from ...core.models import EventDeliveryfrom ..event_types import WebhookEventSyncTypefrom ..models import Webhook, WebhookEventfrom ..transport.synchronous import trigger_taxes_all_webhooks_sync-from ..transport.utils import parse_tax_data+from ..transport.taxes import parse_tax_data@pytest.fixturediff --git a/saleor/webhook/tests/test_tax_webhook_utils.py b/saleor/webhook/tests/test_tax_webhook_utils.pyindex f545fb27a0..5b4426ba8b 100644--- a/saleor/webhook/tests/test_tax_webhook_utils.py+++ b/saleor/webhook/tests/test_tax_webhook_utils.py@@ -1,50 +1,12 @@-import decimal-import pytestfrom pydantic import ValidationErrorfrom ...core.taxes import TaxData-from ..transport.utils import (- _unsafe_parse_tax_line_data,+from ..transport.taxes import (parse_tax_data,)-def test_unsafe_parse_tax_line_data_success(tax_line_data_response):- # when- tax_line_data = _unsafe_parse_tax_line_data(tax_line_data_response)-- # then- assert not tax_line_data.total_gross_amount.compare(- decimal.Decimal(tax_line_data_response["total_gross_amount"])- )- assert not tax_line_data.total_net_amount.compare(- decimal.Decimal(tax_line_data_response["total_net_amount"])- )- assert tax_line_data.tax_rate == tax_line_data_response["tax_rate"]---def test_unsafe_parse_tax_line_data_keyerror(tax_line_data_response):- # given- tax_line_data_response["total_net_amount_v2"] = tax_line_data_response[- "total_net_amount"- ]- del tax_line_data_response["total_net_amount"]-- # when- with pytest.raises(KeyError):- _unsafe_parse_tax_line_data(tax_line_data_response)---def test_unsafe_parse_tax_line_data_decimalexception(tax_line_data_response):- # given- tax_line_data_response["total_net_amount"] = "invalid value"-- # when- with pytest.raises(decimal.DecimalException):- _unsafe_parse_tax_line_data(tax_line_data_response)--def test_parse_tax_data_success(tax_data_response):# givenline_count = len(tax_data_response["lines"])diff --git a/saleor/webhook/transport/payment.py b/saleor/webhook/transport/payment.pynew file mode 100644index 0000000000..b581209ad0--- /dev/null+++ b/saleor/webhook/transport/payment.py@@ -0,0 +1,82 @@+import decimal+from typing import Any++from ...app.models import App+from ...payment.interface import (+ GatewayResponse,+ PaymentData,+ PaymentGateway,+ PaymentMethodInfo,+)+from .utils import to_payment_app_id+++def parse_list_payment_gateways_response(+ response_data: Any, app: "App"+) -> list["PaymentGateway"]:+ gateways: list[PaymentGateway] = []+ if not isinstance(response_data, list):+ return gateways++ for gateway_data in response_data:+ gateway_id = gateway_data.get("id")+ gateway_name = gateway_data.get("name")+ gateway_currencies = gateway_data.get("currencies")+ gateway_config = gateway_data.get("config")++ if gateway_id:+ gateways.append(+ PaymentGateway(+ id=to_payment_app_id(app, gateway_id),+ name=gateway_name,+ currencies=gateway_currencies,+ config=gateway_config,+ )+ )+ return gateways+++def parse_payment_action_response(+ payment_information: "PaymentData",+ response_data: Any,+ transaction_kind: "str",+) -> "GatewayResponse":+ error = response_data.get("error")+ is_success = not error++ payment_method_info = None+ payment_method_data = response_data.get("payment_method")+ if payment_method_data:+ payment_method_info = PaymentMethodInfo(+ brand=payment_method_data.get("brand"),+ exp_month=payment_method_data.get("exp_month"),+ exp_year=payment_method_data.get("exp_year"),+ last_4=payment_method_data.get("last_4"),+ name=payment_method_data.get("name"),+ type=payment_method_data.get("type"),+ )++ amount = payment_information.amount+ if "amount" in response_data:+ try:+ amount = decimal.Decimal(response_data["amount"])+ except decimal.DecimalException:+ pass++ return GatewayResponse(+ action_required=response_data.get("action_required", False),+ action_required_data=response_data.get("action_required_data"),+ amount=amount,+ currency=payment_information.currency,+ customer_id=response_data.get("customer_id"),+ error=error,+ is_success=is_success,+ kind=response_data.get("kind", transaction_kind),+ payment_method_info=payment_method_info,+ raw_response=response_data,+ psp_reference=response_data.get("psp_reference"),+ transaction_id=response_data.get("transaction_id", ""),+ transaction_already_processed=response_data.get(+ "transaction_already_processed", False+ ),+ )diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.pyindex 0338ae77f8..e7c552244c 100644--- a/saleor/webhook/transport/synchronous/transport.py+++ b/saleor/webhook/transport/synchronous/transport.py@@ -44,6 +44,7 @@ from ...payloads import generate_transaction_action_request_payloadfrom ...utils import get_webhooks_for_eventfrom .. import signature_for_payloadfrom ..metrics import record_external_request+from ..taxes import parse_tax_datafrom ..utils import (WebhookResponse,WebhookSchemes,@@ -54,7 +55,6 @@ from ..utils import (generate_cache_key_for_webhook,get_delivery_for_webhook,handle_webhook_retry,- parse_tax_data,save_unsuccessful_delivery_attempt,send_webhook_using_http,)diff --git a/saleor/webhook/transport/taxes.py b/saleor/webhook/transport/taxes.pynew file mode 100644index 0000000000..2a21629402--- /dev/null+++ b/saleor/webhook/transport/taxes.py@@ -0,0 +1,43 @@+from typing import Any++from ...app.models import App+from ...core.taxes import TaxData, TaxLineData+from ..event_types import WebhookEventSyncType+from ..response_schemas.taxes import CalculateTaxesSchema++DEFAULT_TAX_CODE = "UNMAPPED"+DEFAULT_TAX_DESCRIPTION = "Unmapped Product/Product Type"+++def get_current_tax_app() -> App | None:+ """Return currently used tax app or None, if there aren't any."""+ return (+ App.objects.order_by("pk")+ .filter(removed_at__isnull=True)+ .for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)+ .for_event_type(WebhookEventSyncType.ORDER_CALCULATE_TAXES)+ .last()+ )+++def parse_tax_data(+ response_data: Any,+ lines_count: int,+) -> TaxData:+ calculated_taxes_model = CalculateTaxesSchema.model_validate(+ response_data,+ context={"expected_line_count": lines_count},+ )+ return TaxData(+ shipping_price_gross_amount=calculated_taxes_model.shipping_price_gross_amount,+ shipping_price_net_amount=calculated_taxes_model.shipping_price_net_amount,+ shipping_tax_rate=calculated_taxes_model.shipping_tax_rate,+ lines=[+ TaxLineData(+ tax_rate=tax_line.tax_rate,+ total_gross_amount=tax_line.total_gross_amount,+ total_net_amount=tax_line.total_net_amount,+ )+ for tax_line in calculated_taxes_model.lines+ ],+ )diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.pyindex 3a5d30dbae..82225984c6 100644--- a/saleor/webhook/transport/utils.py+++ b/saleor/webhook/transport/utils.py@@ -1,5 +1,4 @@import datetime-import decimalimport hashlibimport jsonimport logging@@ -8,7 +7,7 @@ from contextlib import contextmanagerfrom dataclasses import dataclassfrom enum import Enumfrom time import time-from typing import Any, Optional+from typing import Optionalfrom urllib.parse import unquote, urlparse, urlunparsefrom uuid import UUID@@ -35,30 +34,17 @@ from ...core.models import (EventPayload,)from ...core.tasks import delete_files_from_private_storage_task-from ...core.taxes import TaxData, TaxLineDatafrom ...core.utils import build_absolute_urifrom ...core.utils.url import sanitize_url_for_logging-from ...payment.interface import (- GatewayResponse,- PaymentData,- PaymentGateway,- PaymentMethodInfo,-)from .. import observabilityfrom ..const import APP_ID_PREFIX-from ..event_types import WebhookEventSyncTypefrom ..models import Webhook-from ..response_schemas.taxes import CalculateTaxesSchemafrom . import signature_for_payloadlogger = logging.getLogger(__name__)task_logger = get_task_logger(f"{__name__}.celery")-DEFAULT_TAX_CODE = "UNMAPPED"-DEFAULT_TAX_DESCRIPTION = "Unmapped Product/Product Type"--class WebhookSchemes(str, Enum):HTTP = "http"HTTPS = "https"@@ -643,93 +629,6 @@ def save_unsuccessful_delivery_attempt(attempt: "EventDeliveryAttempt"):attempt.save()-def parse_tax_data(- response_data: Any,- lines_count: int,-) -> TaxData:- calculated_taxes_model = CalculateTaxesSchema.model_validate(- response_data,- context={"expected_line_count": lines_count},- )- return TaxData(- shipping_price_gross_amount=calculated_taxes_model.shipping_price_gross_amount,- shipping_price_net_amount=calculated_taxes_model.shipping_price_net_amount,- shipping_tax_rate=calculated_taxes_model.shipping_tax_rate,- lines=[- TaxLineData(- tax_rate=tax_line.tax_rate,- total_gross_amount=tax_line.total_gross_amount,- total_net_amount=tax_line.total_net_amount,- )- for tax_line in calculated_taxes_model.lines- ],- )---def parse_payment_action_response(- payment_information: "PaymentData",- response_data: Any,- transaction_kind: "str",-) -> "GatewayResponse":- error = response_data.get("error")- is_success = not error-- payment_method_info = None- payment_method_data = response_data.get("payment_method")- if payment_method_data:- payment_method_info = PaymentMethodInfo(- brand=payment_method_data.get("brand"),- exp_month=payment_method_data.get("exp_month"),- exp_year=payment_method_data.get("exp_year"),- last_4=payment_method_data.get("last_4"),- name=payment_method_data.get("name"),- type=payment_method_data.get("type"),- )-- amount = payment_information.amount- if "amount" in response_data:- try:- amount = decimal.Decimal(response_data["amount"])- except decimal.DecimalException:- pass-- return GatewayResponse(- action_required=response_data.get("action_required", False),- action_required_data=response_data.get("action_required_data"),- amount=amount,- currency=payment_information.currency,- customer_id=response_data.get("customer_id"),- error=error,- is_success=is_success,- kind=response_data.get("kind", transaction_kind),- payment_method_info=payment_method_info,- raw_response=response_data,- psp_reference=response_data.get("psp_reference"),- transaction_id=response_data.get("transaction_id", ""),- transaction_already_processed=response_data.get(- "transaction_already_processed", False- ),- )---def _unsafe_parse_tax_line_data(- tax_line_data_response: Any,-) -> TaxLineData:- """Unsafe TaxLineData parser.-- Raises KeyError or DecimalException on invalid data.- """- total_gross_amount = decimal.Decimal(tax_line_data_response["total_gross_amount"])- total_net_amount = decimal.Decimal(tax_line_data_response["total_net_amount"])- tax_rate = decimal.Decimal(tax_line_data_response["tax_rate"])-- return TaxLineData(- total_gross_amount=total_gross_amount,- total_net_amount=total_net_amount,- tax_rate=tax_rate,- )--def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:splitted_id = app_gateway_id.split(":", maxsplit=2)if len(splitted_id) == 3 and splitted_id[0] == APP_ID_PREFIX and all(splitted_id):@@ -746,17 +645,6 @@ def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:return None-def get_current_tax_app() -> App | None:- """Return currently used tax app or None, if there aren't any."""- return (- App.objects.order_by("pk")- .filter(removed_at__isnull=True)- .for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)- .for_event_type(WebhookEventSyncType.ORDER_CALCULATE_TAXES)- .last()- )--def get_meta_code_key(app: App) -> str:return f"{app.identifier}.code"@@ -768,28 +656,3 @@ def get_meta_description_key(app: App) -> str:def to_payment_app_id(app: "App", external_id: str) -> "str":app_identifier = app.identifier or app.idreturn f"{APP_ID_PREFIX}:{app_identifier}:{external_id}"---def parse_list_payment_gateways_response(- response_data: Any, app: "App"-) -> list["PaymentGateway"]:- gateways: list[PaymentGateway] = []- if not isinstance(response_data, list):- return gateways-- for gateway_data in response_data:- gateway_id = gateway_data.get("id")- gateway_name = gateway_data.get("name")- gateway_currencies = gateway_data.get("currencies")- gateway_config = gateway_data.get("config")-- if gateway_id:- gateways.append(- PaymentGateway(- id=to_payment_app_id(app, gateway_id),- name=gateway_name,- currencies=gateway_currencies,- config=gateway_config,- )- )- return gateways