Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix circular imports (#17159)
Marcin Gębalaeaebe6b1ed09
diff --git a/saleor/core/payments.py b/saleor/core/payments.pyindex e9c6b1f354..f1e85c5665 100644--- a/saleor/core/payments.py+++ b/saleor/core/payments.py@@ -1,9 +1,8 @@from abc import ABC, abstractmethodfrom typing import TYPE_CHECKING, Optional-from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo-if TYPE_CHECKING:+ from ..checkout.fetch import CheckoutInfo, CheckoutLineInfofrom ..payment.interface import (CustomerSource,GatewayResponse,diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.pyindex 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_discountif TYPE_CHECKING:- from ...checkout.fetch import CheckoutLineInfofrom ...order.fetch import EditableOrderLineInfofrom ...order.models import OrderLinefrom ...product.managers import ProductVariantQuerysetdiff --git a/saleor/graphql/webhook/mutations/webhook_trigger.py b/saleor/graphql/webhook/mutations/webhook_trigger.pyindex 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 AuthorizationFiltersfrom ....webhook.error_codes import WebhookTriggerErrorCodefrom ....webhook.event_types import WebhookEventAsyncTypefrom ....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_datafrom ...core import ResolveInfofrom ...core.doc_category import DOC_CATEGORY_WEBHOOKSfrom ...core.mutations import BaseMutation@@ -148,13 +154,6 @@ class WebhookTrigger(BaseMutation):@classmethoddef 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 = Nonerequestor = get_user_or_app_from_context(info.context)diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 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_eventfrom ..base_plugin import BasePlugin, ExcludedShippingMethoddiff --git a/saleor/webhook/observability/obfuscation.py b/saleor/webhook/observability/obfuscation.pyindex f0f30c38ff..af915c60d9 100644--- a/saleor/webhook/observability/obfuscation.py+++ b/saleor/webhook/observability/obfuscation.py@@ -20,7 +20,6 @@ from graphql.validation import validatefrom graphql.validation.rules.base import ValidationRulefrom graphql.validation.validation import ValidationContext-from ...graphql.api import schemafrom .sensitive_data import ALLOWED_HEADERS, SENSITIVE_HEADERS, SensitiveFieldsMapif 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.pyindex 90cf639a71..2f9831e178 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -20,7 +20,6 @@ from .. import __version__from ..account.models import Userfrom ..attribute.models import AttributeValueTranslationfrom ..checkout import base_calculations-from ..checkout.fetch import CheckoutInfo, CheckoutLineInfofrom ..checkout.models import Checkoutfrom ..checkout.utils import get_checkout_metadatafrom ..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_idif TYPE_CHECKING:+ from ..checkout.fetch import CheckoutInfo, CheckoutLineInfofrom ..discount.models import Promotionfrom ..invoice.models import Invoicefrom ..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.pyindex 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 TransactionEventfrom ...payment.transaction_item_calculations import recalculate_transaction_amountsfrom ..event_types import WebhookEventSyncTypefrom ..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.fixturediff --git a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.pyindex 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_linesfrom .....core import EventDeliveryStatusfrom .....core.models import EventDeliveryfrom ....event_types import WebhookEventAsyncType-from ...utils import get_webhooks_for_event+from ....utils import get_webhooks_for_eventfrom ..transport import (DeferredPayloadData,generate_deferred_payloads,diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.pyindex 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_writerfrom ....core.models import EventDelivery, EventPayloadfrom ....core.tracing import webhooks_opentracing_tracefrom ....core.utils import get_domain+from ....core.utils.events import call_eventfrom ....core.utils.url import sanitize_url_for_loggingfrom ....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_MAPfrom ....graphql.webhook.utils import get_pregenerated_subscription_payload+from ....payment import PaymentError+from ....payment.interface import TransactionActionDatafrom ....payment.models import TransactionEventfrom ....payment.utils import (+ create_failed_transaction_event,create_transaction_event_from_request_and_webhook_response,recalculate_refundable_for_checkout,)from ... import observabilityfrom ...const import WEBHOOK_CACHE_DEFAULT_TIMEOUTfrom ...event_types import WebhookEventSyncType+from ...payloads import generate_transaction_action_request_payloadfrom ...utils import get_webhooks_for_eventfrom .. import signature_for_payloadfrom ..utils import (@@ -387,3 +392,71 @@ def trigger_all_webhooks_sync(if parsed_response := parse_response(response_data):return parsed_responsereturn 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.pyindex 8ceba69ced..53bd2546af 100644--- a/saleor/webhook/transport/utils.py+++ b/saleor/webhook/transport/utils.py@@ -17,7 +17,6 @@ from celery import Taskfrom celery.exceptions import MaxRetriesExceededError, Retryfrom celery.utils.log import get_task_loggerfrom django.conf import settings-from django.db import transactionfrom django.urls import reversefrom google.cloud import pubsub_v1from requests import RequestException@@ -36,21 +35,13 @@ from ...core.models import (from ...core.tasks import delete_files_from_private_storage_taskfrom ...core.taxes import TaxData, TaxLineDatafrom ...core.utils import build_absolute_uri-from ...core.utils.events import call_eventfrom ...core.utils.url import sanitize_url_for_logging-from ...payment import PaymentErrorfrom ...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_eventfrom .. import observabilityfrom ..const import APP_ID_PREFIXfrom ..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]: