Skip to content

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

Fix circular imports (#17159)

Marcin Gębalaeaebe6b1ed09
diff --git a/saleor/core/payments.py b/saleor/core/payments.py
index e9c6b1f354..f1e85c5665 100644
--- a/saleor/core/payments.py
+++ b/saleor/core/payments.py
@@ -1,9 +1,8 @@
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Optional
-from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
-
if TYPE_CHECKING:
+ from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..payment.interface import (
CustomerSource,
GatewayResponse,
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index 36f145b9b8..8abe4ce5c8 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -47,7 +47,6 @@ from ..models import (
from .shared import update_discount
if TYPE_CHECKING:
- from ...checkout.fetch import CheckoutLineInfo
from ...order.fetch import EditableOrderLineInfo
from ...order.models import OrderLine
from ...product.managers import ProductVariantQueryset
diff --git a/saleor/graphql/webhook/mutations/webhook_trigger.py b/saleor/graphql/webhook/mutations/webhook_trigger.py
index a3c9f1a998..4c1ce4e642 100644
--- a/saleor/graphql/webhook/mutations/webhook_trigger.py
+++ b/saleor/graphql/webhook/mutations/webhook_trigger.py
@@ -15,6 +15,12 @@ from ....permission.auth_filters import AuthorizationFilters
from ....webhook.error_codes import WebhookTriggerErrorCode
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.models import Webhook
+from ....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+ generate_deferred_payloads,
+ send_webhook_request_async,
+)
+from ....webhook.transport.utils import prepare_deferred_payload_data
from ...core import ResolveInfo
from ...core.doc_category import DOC_CATEGORY_WEBHOOKS
from ...core.mutations import BaseMutation
@@ -148,13 +154,6 @@ class WebhookTrigger(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, **data):
- from ....webhook.transport.asynchronous.transport import (
- create_deliveries_for_subscriptions,
- generate_deferred_payloads,
- send_webhook_request_async,
- )
- from ....webhook.transport.utils import prepare_deferred_payload_data
-
event_type, object, webhook = cls.validate_input(info, **data)
delivery = None
requestor = get_user_or_app_from_context(info.context)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index bf37f61eaf..9e3a5bb157 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -102,6 +102,7 @@ from ...webhook.transport.shipping import (
)
from ...webhook.transport.synchronous.transport import (
trigger_all_webhooks_sync,
+ trigger_transaction_request,
trigger_webhook_sync,
trigger_webhook_sync_if_not_cached,
)
@@ -116,7 +117,6 @@ from ...webhook.transport.utils import (
parse_list_payment_gateways_response,
parse_payment_action_response,
parse_tax_data,
- trigger_transaction_request,
)
from ...webhook.utils import get_webhooks_for_event
from ..base_plugin import BasePlugin, ExcludedShippingMethod
diff --git a/saleor/webhook/observability/obfuscation.py b/saleor/webhook/observability/obfuscation.py
index f0f30c38ff..af915c60d9 100644
--- a/saleor/webhook/observability/obfuscation.py
+++ b/saleor/webhook/observability/obfuscation.py
@@ -20,7 +20,6 @@ from graphql.validation import validate
from graphql.validation.rules.base import ValidationRule
from graphql.validation.validation import ValidationContext
-from ...graphql.api import schema
from .sensitive_data import ALLOWED_HEADERS, SENSITIVE_HEADERS, SensitiveFieldsMap
if TYPE_CHECKING:
@@ -189,6 +188,9 @@ def anonymize_event_payload(
) -> Any:
if not subscription_query:
return payload
+
+ from ...graphql.api import schema
+
graphql_backend = get_default_backend()
document = graphql_backend.document_from_string(schema, subscription_query)
if _contain_sensitive_field(document, sensitive_fields):
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 90cf639a71..2f9831e178 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -20,7 +20,6 @@ from .. import __version__
from ..account.models import User
from ..attribute.models import AttributeValueTranslation
from ..checkout import base_calculations
-from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..checkout.models import Checkout
from ..checkout.utils import get_checkout_metadata
from ..core.db.connection import allow_writer
@@ -56,8 +55,10 @@ from .serializers import (
serialize_product_attributes,
serialize_variant_attributes,
)
+from .transport.utils import from_payment_app_id
if TYPE_CHECKING:
+ from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..discount.models import Promotion
from ..invoice.models import Invoice
from ..payment.interface import (
@@ -1065,8 +1066,6 @@ def _generate_refund_data_payload(data):
def generate_payment_payload(
payment_data: "PaymentData", requestor: Optional["RequestorOrLazyObject"] = None
):
- from .transport.utils import from_payment_app_id
-
data = asdict(payment_data)
if refund_data := data.get("refund_data"):
diff --git a/saleor/webhook/tests/test_tasks.py b/saleor/webhook/tests/test_tasks.py
index 9ee379df3f..98357b7078 100644
--- a/saleor/webhook/tests/test_tasks.py
+++ b/saleor/webhook/tests/test_tasks.py
@@ -16,8 +16,10 @@ from ...payment.models import TransactionEvent
from ...payment.transaction_item_calculations import recalculate_transaction_amounts
from ..event_types import WebhookEventSyncType
from ..payloads import generate_transaction_action_request_payload
-from ..transport.synchronous.transport import handle_transaction_request_task
-from ..transport.utils import trigger_transaction_request
+from ..transport.synchronous.transport import (
+ handle_transaction_request_task,
+ trigger_transaction_request,
+)
@pytest.fixture
diff --git a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
index 7c6ecdd75c..1512672bf0 100644
--- a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
+++ b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
@@ -10,7 +10,7 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....core import EventDeliveryStatus
from .....core.models import EventDelivery
from ....event_types import WebhookEventAsyncType
-from ...utils import get_webhooks_for_event
+from ....utils import get_webhooks_for_event
from ..transport import (
DeferredPayloadData,
generate_deferred_payloads,
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index 4f2c66dfa1..c6ec51a029 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -14,6 +14,7 @@ from ....core.db.connection import allow_writer
from ....core.models import EventDelivery, EventPayload
from ....core.tracing import webhooks_opentracing_trace
from ....core.utils import get_domain
+from ....core.utils.events import call_event
from ....core.utils.url import sanitize_url_for_logging
from ....graphql.webhook.subscription_payload import (
generate_payload_from_subscription,
@@ -21,14 +22,18 @@ from ....graphql.webhook.subscription_payload import (
)
from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP
from ....graphql.webhook.utils import get_pregenerated_subscription_payload
+from ....payment import PaymentError
+from ....payment.interface import TransactionActionData
from ....payment.models import TransactionEvent
from ....payment.utils import (
+ create_failed_transaction_event,
create_transaction_event_from_request_and_webhook_response,
recalculate_refundable_for_checkout,
)
from ... import observability
from ...const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
from ...event_types import WebhookEventSyncType
+from ...payloads import generate_transaction_action_request_payload
from ...utils import get_webhooks_for_event
from .. import signature_for_payload
from ..utils import (
@@ -387,3 +392,71 @@ def trigger_all_webhooks_sync(
if parsed_response := parse_response(response_data):
return parsed_response
return None
+
+
+def trigger_transaction_request(
+ transaction_data: "TransactionActionData", event_type: str, requestor
+) -> None:
+ if not transaction_data.transaction_app_owner:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause=(
+ "Cannot process the action as the given transaction is not "
+ "attached to any app."
+ ),
+ )
+ recalculate_refundable_for_checkout(
+ transaction_data.transaction, transaction_data.event
+ )
+ return
+ webhook = get_webhooks_for_event(
+ event_type, apps_ids=[transaction_data.transaction_app_owner.pk]
+ ).first()
+ if not webhook:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause="Cannot find a webhook that can process the action.",
+ )
+ recalculate_refundable_for_checkout(
+ transaction_data.transaction, transaction_data.event
+ )
+ return
+
+ if webhook.subscription_query:
+ delivery = None
+ try:
+ delivery = create_delivery_for_subscription_sync_event(
+ event_type=event_type,
+ subscribable_object=transaction_data,
+ webhook=webhook,
+ )
+ except PaymentError as e:
+ logger.warning("Failed to create delivery for subscription webhook: %s", e)
+ if not delivery:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause="Cannot generate a payload for the action.",
+ )
+ recalculate_refundable_for_checkout(
+ transaction_data.transaction, transaction_data.event
+ )
+ return
+ else:
+ payload = generate_transaction_action_request_payload(
+ transaction_data, requestor
+ )
+ with allow_writer():
+ # Use transaction to ensure EventPayload and EventDelivery are created together, preventing inconsistent DB state.
+ with transaction.atomic():
+ event_payload = EventPayload.objects.create_with_payload_file(payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=event_type,
+ payload=event_payload,
+ webhook=webhook,
+ )
+ call_event(
+ handle_transaction_request_task.delay,
+ delivery.id,
+ transaction_data.event.id,
+ )
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index 8ceba69ced..53bd2546af 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -17,7 +17,6 @@ from celery import Task
from celery.exceptions import MaxRetriesExceededError, Retry
from celery.utils.log import get_task_logger
from django.conf import settings
-from django.db import transaction
from django.urls import reverse
from google.cloud import pubsub_v1
from requests import RequestException
@@ -36,21 +35,13 @@ from ...core.models import (
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.events import call_event
from ...core.utils.url import sanitize_url_for_logging
-from ...payment import PaymentError
from ...payment.interface import (
GatewayResponse,
PaymentData,
PaymentGateway,
PaymentMethodInfo,
- TransactionActionData,
)
-from ...payment.utils import (
- create_failed_transaction_event,
- recalculate_refundable_for_checkout,
-)
-from ...webhook.utils import get_webhooks_for_event
from .. import observability
from ..const import APP_ID_PREFIX
from ..event_types import WebhookEventSyncType
@@ -546,80 +537,6 @@ def save_unsuccessful_delivery_attempt(attempt: "EventDeliveryAttempt"):
attempt.save()
-def trigger_transaction_request(
- transaction_data: "TransactionActionData", event_type: str, requestor
-) -> None:
- from ..payloads import generate_transaction_action_request_payload
- from .synchronous.transport import (
- create_delivery_for_subscription_sync_event,
- handle_transaction_request_task,
- )
-
- if not transaction_data.transaction_app_owner:
- create_failed_transaction_event(
- transaction_data.event,
- cause=(
- "Cannot process the action as the given transaction is not "
- "attached to any app."
- ),
- )
- recalculate_refundable_for_checkout(
- transaction_data.transaction, transaction_data.event
- )
- return
- webhook = get_webhooks_for_event(
- event_type, apps_ids=[transaction_data.transaction_app_owner.pk]
- ).first()
- if not webhook:
- create_failed_transaction_event(
- transaction_data.event,
- cause="Cannot find a webhook that can process the action.",
- )
- recalculate_refundable_for_checkout(
- transaction_data.transaction, transaction_data.event
- )
- return
-
- if webhook.subscription_query:
- delivery = None
- try:
- delivery = create_delivery_for_subscription_sync_event(
- event_type=event_type,
- subscribable_object=transaction_data,
- webhook=webhook,
- )
- except PaymentError as e:
- logger.warning("Failed to create delivery for subscription webhook: %s", e)
- if not delivery:
- create_failed_transaction_event(
- transaction_data.event,
- cause="Cannot generate a payload for the action.",
- )
- recalculate_refundable_for_checkout(
- transaction_data.transaction, transaction_data.event
- )
- return
- else:
- payload = generate_transaction_action_request_payload(
- transaction_data, requestor
- )
- with allow_writer():
- # Use transaction to ensure EventPayload and EventDelivery are created together, preventing inconsistent DB state.
- with transaction.atomic():
- event_payload = EventPayload.objects.create_with_payload_file(payload)
- delivery = EventDelivery.objects.create(
- status=EventDeliveryStatus.PENDING,
- event_type=event_type,
- payload=event_payload,
- webhook=webhook,
- )
- call_event(
- handle_transaction_request_task.delay,
- delivery.id,
- transaction_data.event.id,
- )
-
-
def parse_tax_data(
response_data: Any,
) -> Optional[TaxData]: