Skip to content

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

Refactor webhook.transport.utils.py file (#17761)

Iga Karbowiak96c4c8802926
diff --git a/saleor/core/tests/test_taxes.py b/saleor/core/tests/test_taxes.py
index 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, WebhookEventSyncType
from ...webhook.models import Webhook, WebhookEvent
-from ...webhook.transport.utils import get_current_tax_app
+from ...webhook.transport.taxes import get_current_tax_app
@pytest.fixture
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 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_event
from ..base_plugin import BasePlugin, ExcludedShippingMethod
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index 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_information
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....webhook.models import Webhook, WebhookEvent
from ....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_headers
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
index 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, TaxType
from ....graphql.webhook.utils import get_subscription_query_hash
from ....webhook.event_types import WebhookEventSyncType
from ....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.py
index 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_storage
from ...core.models import EventDelivery, EventPayload
from ...payment import TransactionKind
from ..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.py
index 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 timezone
from ...core.models import EventDelivery, EventPayload
from ..event_types import WebhookEventSyncType
from ..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.py
index 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 EventDelivery
from ..event_types import WebhookEventSyncType
from ..models import Webhook, WebhookEvent
from ..transport.synchronous import trigger_taxes_all_webhooks_sync
-from ..transport.utils import parse_tax_data
+from ..transport.taxes import parse_tax_data
@pytest.fixture
diff --git a/saleor/webhook/tests/test_tax_webhook_utils.py b/saleor/webhook/tests/test_tax_webhook_utils.py
index 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 pytest
from pydantic import ValidationError
from ...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):
# given
line_count = len(tax_data_response["lines"])
diff --git a/saleor/webhook/transport/payment.py b/saleor/webhook/transport/payment.py
new file mode 100644
index 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.py
index 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_payload
from ...utils import get_webhooks_for_event
from .. import signature_for_payload
from ..metrics import record_external_request
+from ..taxes import parse_tax_data
from ..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.py
new file mode 100644
index 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.py
index 3a5d30dbae..82225984c6 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -1,5 +1,4 @@
import datetime
-import decimal
import hashlib
import json
import logging
@@ -8,7 +7,7 @@ from contextlib import contextmanager
from dataclasses import dataclass
from enum import Enum
from time import time
-from typing import Any, Optional
+from typing import Optional
from urllib.parse import unquote, urlparse, urlunparse
from 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, TaxLineData
from ...core.utils import build_absolute_uri
from ...core.utils.url import sanitize_url_for_logging
-from ...payment.interface import (
- GatewayResponse,
- PaymentData,
- PaymentGateway,
- PaymentMethodInfo,
-)
from .. import observability
from ..const import APP_ID_PREFIX
-from ..event_types import WebhookEventSyncType
from ..models import Webhook
-from ..response_schemas.taxes import CalculateTaxesSchema
from . import signature_for_payload
logger = 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.id
return 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