Skip to content

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

[POC] Pass paylaod from resolver to webhook plugin

fowczrek2b1c457a9ea6
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 6079810082..4793d3cec4 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -110,6 +110,7 @@ def calculate_checkout_total_with_gift_cards(
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+ subscription_payload: Optional[dict] = None,
) -> "TaxedMoney":
total = checkout_total(
manager=manager,
@@ -117,6 +118,7 @@ def calculate_checkout_total_with_gift_cards(
lines=lines,
address=address,
database_connection_name=database_connection_name,
+ subscription_payload=subscription_payload,
) - checkout_info.checkout.get_total_gift_cards_balance(database_connection_name)
return max(total, zero_taxed_money(total.currency))
@@ -129,6 +131,7 @@ def checkout_total(
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+ subscription_payload: Optional[dict] = None,
) -> "TaxedMoney":
"""Return the total cost of the checkout.
@@ -144,6 +147,7 @@ def checkout_total(
lines=lines,
address=address,
database_connection_name=database_connection_name,
+ subscription_payload=subscription_payload,
)
return quantize_price(checkout_info.checkout.total, currency)
@@ -230,6 +234,7 @@ def _fetch_checkout_prices_if_expired(
address: Optional["Address"] = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+ subscription_payload: Optional[dict] = None,
) -> tuple["CheckoutInfo", Iterable["CheckoutLineInfo"]]:
"""Fetch checkout prices with taxes.
@@ -264,6 +269,7 @@ def _fetch_checkout_prices_if_expired(
checkout.tax_error = None
if prices_entered_with_tax:
+ # TODO Owczar: Cover this flow
# If prices are entered with tax, we need to always calculate it anyway, to
# display the tax rate to the user.
try:
@@ -303,6 +309,7 @@ def _fetch_checkout_prices_if_expired(
prices_entered_with_tax,
address,
database_connection_name=database_connection_name,
+ subscription_payload=subscription_payload,
)
except TaxEmptyData as e:
_set_checkout_base_prices(checkout, checkout_info, lines)
@@ -357,6 +364,7 @@ def _calculate_and_add_tax(
prices_entered_with_tax: bool,
address: Optional["Address"] = None,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+ subscription_payload: Optional[dict] = None,
):
from .utils import log_address_if_validation_skipped_for_checkout
@@ -365,6 +373,7 @@ def _calculate_and_add_tax(
# If taxAppId is provided run tax plugin or Tax App. taxAppId can be
# configured with Avatax plugin identifier.
if not tax_app_identifier:
+ # TODO Owczar: Cover this flow
# Call the tax plugins.
_apply_tax_data_from_plugins(
checkout, manager, checkout_info, lines, address
@@ -384,6 +393,7 @@ def _calculate_and_add_tax(
checkout_info,
lines,
address,
+ subscription_payload,
)
else:
# Get taxes calculated with flat rates and apply to checkout.
@@ -404,6 +414,7 @@ def _call_plugin_or_tax_app(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"] = None,
+ subscription_payload: Optional[dict] = None,
):
from .utils import log_address_if_validation_skipped_for_checkout
@@ -428,7 +439,10 @@ def _call_plugin_or_tax_app(
raise TaxEmptyData("Empty tax data.")
else:
tax_data = manager.get_taxes_for_checkout(
- checkout_info, lines, tax_app_identifier
+ checkout_info,
+ lines,
+ tax_app_identifier,
+ subscription_payload=subscription_payload,
)
if tax_data is None:
log_address_if_validation_skipped_for_checkout(checkout_info, logger)
@@ -594,6 +608,7 @@ def fetch_checkout_data(
checkout_transactions: Optional[Iterable["TransactionItem"]] = None,
force_status_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+ subscription_payload: Optional[dict] = None,
):
"""Fetch checkout data.
@@ -608,6 +623,7 @@ def fetch_checkout_data(
address=address,
force_update=force_update,
database_connection_name=database_connection_name,
+ subscription_payload=subscription_payload,
)
current_total_gross = checkout_info.checkout.total.gross
if current_total_gross != previous_total_gross or force_status_update:
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 587a42a9e6..e361e6ec05 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -897,6 +897,11 @@ class Checkout(ModelObjectType[models.Checkout]):
@allow_writer_in_context(info.context)
def calculate_total_price(data):
address, lines, checkout_info, manager = data
+ import inspect
+
+ print(len(inspect.stack(0)))
+ # sample_payload = {} #Sample Payload from Dataloader
+ sample_payload = None
database_connection_name = get_database_connection_name(info.context)
taxed_total = calculations.calculate_checkout_total_with_gift_cards(
manager=manager,
@@ -904,6 +909,7 @@ class Checkout(ModelObjectType[models.Checkout]):
lines=lines,
address=address,
database_connection_name=database_connection_name,
+ subscription_payload=sample_payload,
)
return max(taxed_total, zero_taxed_money(root.currency))
@@ -1100,11 +1106,11 @@ class Checkout(ModelObjectType[models.Checkout]):
CheckoutMetadataByCheckoutIdLoader(info.context)
.load(root.pk)
.then(
- lambda metadata_storage: MetaResolvers.resolve_metadata(
- metadata_storage.metadata
+ lambda metadata_storage: (
+ MetaResolvers.resolve_metadata(metadata_storage.metadata)
+ if metadata_storage
+ else {}
)
- if metadata_storage
- else {}
)
)
@@ -1114,9 +1120,9 @@ class Checkout(ModelObjectType[models.Checkout]):
CheckoutMetadataByCheckoutIdLoader(info.context)
.load(root.pk)
.then(
- lambda metadata_storage: metadata_storage.metadata.get(key)
- if metadata_storage
- else None
+ lambda metadata_storage: (
+ metadata_storage.metadata.get(key) if metadata_storage else None
+ )
)
)
@@ -1126,11 +1132,11 @@ class Checkout(ModelObjectType[models.Checkout]):
CheckoutMetadataByCheckoutIdLoader(info.context)
.load(root.pk)
.then(
- lambda metadata_storage: _filter_metadata(
- metadata_storage.metadata, keys
+ lambda metadata_storage: (
+ _filter_metadata(metadata_storage.metadata, keys)
+ if metadata_storage
+ else {}
)
- if metadata_storage
- else {}
)
)
@@ -1140,11 +1146,11 @@ class Checkout(ModelObjectType[models.Checkout]):
CheckoutMetadataByCheckoutIdLoader(info.context)
.load(root.pk)
.then(
- lambda metadata_storage: MetaResolvers.resolve_private_metadata(
- metadata_storage, info
+ lambda metadata_storage: (
+ MetaResolvers.resolve_private_metadata(metadata_storage, info)
+ if metadata_storage
+ else {}
)
- if metadata_storage
- else {}
)
)
@@ -1158,11 +1164,11 @@ class Checkout(ModelObjectType[models.Checkout]):
CheckoutMetadataByCheckoutIdLoader(info.context)
.load(root.pk)
.then(
- lambda metadata_storage: resolve_private_metafield_with_privilege_check(
- metadata_storage
+ lambda metadata_storage: (
+ resolve_private_metafield_with_privilege_check(metadata_storage)
+ if metadata_storage
+ else None
)
- if metadata_storage
- else None
)
)
@@ -1176,11 +1182,11 @@ class Checkout(ModelObjectType[models.Checkout]):
CheckoutMetadataByCheckoutIdLoader(info.context)
.load(root.pk)
.then(
- lambda metadata_storage: resolve_private_metafields_with_privilege(
- metadata_storage
+ lambda metadata_storage: (
+ resolve_private_metafields_with_privilege(metadata_storage)
+ if metadata_storage
+ else {}
)
- if metadata_storage
- else {}
)
)
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index e9f4bdd83f..17020230a2 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -604,7 +604,7 @@ class BasePlugin:
]
get_taxes_for_checkout: Callable[
- ["CheckoutInfo", Iterable["CheckoutLineInfo"], str, Any],
+ ["CheckoutInfo", Iterable["CheckoutLineInfo"], str, Any, Optional[dict]],
Optional["TaxData"],
]
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index f1c2bffc19..591468c5ef 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -652,13 +652,14 @@ class PluginsManager(PaymentInterface):
)
def get_taxes_for_checkout(
- self, checkout_info, lines, app_identifier
+ self, checkout_info, lines, app_identifier, subscription_payload=None
) -> Optional[TaxData]:
return self.__run_plugin_method_until_first_success(
"get_taxes_for_checkout",
checkout_info,
lines,
app_identifier,
+ subscription_payload=subscription_payload,
channel_slug=checkout_info.channel.slug,
)
@@ -2291,13 +2292,14 @@ class PluginsManager(PaymentInterface):
*args,
channel_slug: Optional[str],
plugins: Optional[list["BasePlugin"]] = None,
+ **kwargs,
):
if plugins is None:
plugins = self.get_plugins(channel_slug=channel_slug, active_only=True)
if plugins:
for plugin in plugins:
result = self.__run_method_on_single_plugin(
- plugin, method_name, None, *args
+ plugin, method_name, None, *args, **kwargs
)
if result is not None:
return result
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 96f2496c32..9bf1e3c672 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -3032,6 +3032,7 @@ class WebhookPlugin(BasePlugin):
app_identifier: str,
payload_gen: Callable,
subscriptable_object=None,
+ subscription_payload=None,
):
app = (
App.objects.filter(
@@ -3065,12 +3066,23 @@ class WebhookPlugin(BasePlugin):
subscribable_object=subscriptable_object,
request=request_context,
requestor=self.requestor,
+ subscription_payload=subscription_payload,
)
return parse_tax_data(response)
def get_taxes_for_checkout(
- self, checkout_info, lines, app_identifier, previous_value
+ self,
+ checkout_info,
+ lines,
+ app_identifier,
+ previous_value,
+ subscription_payload=None,
) -> Optional["TaxData"]:
+ print("checkout_info", checkout_info)
+ print("lines", lines)
+ print("app_identifier", app_identifier)
+ print("previous_value", previous_value)
+ print("subscription_payload", subscription_payload)
event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
if app_identifier:
return self.__run_tax_webhook(
@@ -3080,6 +3092,7 @@ class WebhookPlugin(BasePlugin):
checkout_info, lines
),
checkout_info.checkout,
+ subscription_payload=subscription_payload,
)
else:
return trigger_all_webhooks_sync(
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index b683616656..ed45a702a3 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -213,6 +213,7 @@ def create_delivery_for_subscription_sync_event(
requestor=None,
request=None,
allow_replica=False,
+ payload=None,
) -> Optional[EventDelivery]:
"""Generate webhook payload based on subscription query and create delivery object.
@@ -240,13 +241,17 @@ def create_delivery_for_subscription_sync_event(
event_type=event_type,
allow_replica=allow_replica,
)
- data = generate_payload_from_subscription(
- event_type=event_type,
- subscribable_object=subscribable_object,
- subscription_query=webhook.subscription_query,
- request=request,
- app=webhook.app,
- )
+ if not payload:
+ data = generate_payload_from_subscription(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ subscription_query=webhook.subscription_query,
+ request=request,
+ app=webhook.app,
+ )
+ else:
+ data = payload
+
if not data:
logger.info(
"No payload was generated with subscription for event: %s", event_type
@@ -275,6 +280,7 @@ def trigger_webhook_sync(
timeout=None,
request=None,
requestor=None,
+ subscription_payload=None,
) -> Optional[dict[Any, Any]]:
"""Send a synchronous webhook request."""
if webhook.subscription_query:
@@ -285,6 +291,7 @@ def trigger_webhook_sync(
requestor=requestor,
request=request,
allow_replica=allow_replica,
+ payload=subscription_payload,
)
if not delivery:
return None
@@ -321,6 +328,7 @@ def trigger_all_webhooks_sync(
If no webhook responds with expected response,
this function returns None.
"""
+ # TODO Owczar: Adjust flow to handle pre-generated payloads
webhooks = get_webhooks_for_event(event_type)
request_context = None
event_payload = None