Skip to content

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

Add PregeneratedSubscriptionPayloadsByCheckoutTokenLoader dataloader

fowczrek897f9e7d6766
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 8d4435b1a0..242deca106 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -269,7 +269,6 @@ 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:
@@ -283,6 +282,7 @@ def _fetch_checkout_prices_if_expired(
prices_entered_with_tax,
address,
database_connection_name=database_connection_name,
+ pregenerated_subscription_payloads=pregenerated_subscription_payloads,
)
except TaxEmptyData as e:
_set_checkout_base_prices(checkout, checkout_info, lines)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index f7af54cecc..47809dceb1 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -85,6 +85,7 @@ from ..tax.dataloaders import (
from ..utils import get_user_or_app_from_context
from ..warehouse.dataloaders import StocksReservationsByCheckoutTokenLoader
from ..warehouse.types import Warehouse
+from ..webhook.dataloaders import PregeneratedSubscriptionPayloadsByCheckoutTokenLoader
from .dataloaders import (
CheckoutByTokenLoader,
CheckoutInfoByCheckoutTokenLoader,
@@ -103,7 +104,7 @@ if TYPE_CHECKING:
def get_dataloaders_for_fetching_checkout_data(
- root: models.Checkout, info: ResolveInfo
+ root: models.Checkout, info: ResolveInfo, extra_data: bool = False
) -> tuple[
Optional[Promise["Address"]],
Promise[list["CheckoutLineInfo"]],
@@ -115,6 +116,11 @@ def get_dataloaders_for_fetching_checkout_data(
lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token)
checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(root.token)
manager = get_plugin_manager_promise(info.context)
+ payloads = PregeneratedSubscriptionPayloadsByCheckoutTokenLoader(info.context).load(
+ root.token
+ )
+ if extra_data:
+ return address, lines, checkout_info, manager, payloads
return address, lines, checkout_info, manager
@@ -896,11 +902,11 @@ class Checkout(ModelObjectType[models.Checkout]):
def resolve_total_price(root: models.Checkout, info: ResolveInfo):
@allow_writer_in_context(info.context)
def calculate_total_price(data):
- address, lines, checkout_info, manager = data
+ address, lines, checkout_info, manager, payloads = data
+ # address, lines, checkout_info, manager = data
import inspect
print(len(inspect.stack(0)))
- sample_payloads = {} #Sample Payload from Dataloader
database_connection_name = get_database_connection_name(info.context)
taxed_total = calculations.calculate_checkout_total_with_gift_cards(
manager=manager,
@@ -908,11 +914,13 @@ class Checkout(ModelObjectType[models.Checkout]):
lines=lines,
address=address,
database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=sample_payloads,
+ pregenerated_subscription_payloads=payloads,
)
return max(taxed_total, zero_taxed_money(root.currency))
- dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
+ dataloaders = list(
+ get_dataloaders_for_fetching_checkout_data(root, info, extra_data=True)
+ )
return Promise.all(dataloaders).then(calculate_total_price)
@staticmethod
diff --git a/saleor/graphql/webhook/dataloaders.py b/saleor/graphql/webhook/dataloaders.py
index 3a7894c304..95fb7ee10e 100644
--- a/saleor/graphql/webhook/dataloaders.py
+++ b/saleor/graphql/webhook/dataloaders.py
@@ -1,8 +1,30 @@
from collections import defaultdict
+from typing import Any
+
+from promise import Promise
from ...core.models import EventPayload
+from ...tax import TaxCalculationStrategy
+from ...tax.utils import (
+ get_tax_app_id,
+ get_tax_calculation_strategy,
+ get_tax_configuration_for_checkout,
+)
+from ...webhook.event_types import WebhookEventSyncType
from ...webhook.models import Webhook, WebhookEvent
+from ...webhook.utils import get_webhooks_for_event
+from ..app.dataloaders import AppByIdLoader
+from ..checkout.dataloaders import (
+ CheckoutInfoByCheckoutTokenLoader,
+ CheckoutLinesInfoByCheckoutTokenLoader,
+)
from ..core.dataloaders import DataLoader
+from ..utils import get_user_or_app_from_context
+from .subscription_payload import (
+ generate_payload_from_subscription,
+ initialize_request,
+)
+from .utils import get_subscription_query_hash
class PayloadByIdLoader(DataLoader[str, str]):
@@ -45,3 +67,76 @@ class WebhooksByAppIdLoader(DataLoader):
for webhook in webhooks:
webhooks_by_app_map[webhook.app_id].append(webhook)
return [webhooks_by_app_map.get(app_id, []) for app_id in keys]
+
+
+class PregeneratedSubscriptionPayloadsByCheckoutTokenLoader(DataLoader):
+ context_key = "pregenerated_subscription_payloads_by_checkout_token"
+
+ def batch_load(self, keys):
+ # TODO Owczar: Add dict explanation here.
+ results: dict[str, dict[int, dict[str, dict[str, Any]]]] = defaultdict(
+ lambda: defaultdict(dict)
+ )
+
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ requestor = get_user_or_app_from_context(self.context)
+ request_context = initialize_request(
+ requestor,
+ event_type in WebhookEventSyncType.ALL,
+ False,
+ event_type=event_type,
+ )
+ # TDDO: Implement below function as a DataLoader
+ webhooks = get_webhooks_for_event(event_type)
+ apps_ids = [webhook.app_id for webhook in webhooks]
+
+ def generate_payloads(data):
+ checkouts_info, checkout_liens_info, apps = data
+ apps_map = {app.id: app for app in apps}
+ for checkout_info, lines_info in zip(checkouts_info, checkout_liens_info):
+ tax_configuration, country_tax_configuration = (
+ get_tax_configuration_for_checkout(
+ checkout_info, lines_info, self.database_connection_name
+ )
+ )
+ tax_strategy = get_tax_calculation_strategy(
+ tax_configuration, country_tax_configuration
+ )
+
+ if tax_strategy == TaxCalculationStrategy.TAX_APP:
+ tax_app_identifier = get_tax_app_id(
+ tax_configuration, country_tax_configuration
+ )
+ for webhook in webhooks:
+ app_id = webhook.app_id
+ app = apps_map[app_id]
+ if webhook.subscription_query and (
+ not tax_app_identifier
+ or app.identifier == tax_app_identifier
+ ):
+ query_hash = get_subscription_query_hash(
+ webhook.subscription_query
+ )
+ checkout = checkout_info.checkout
+ checkout_token = str(checkout.pk)
+
+ payload = generate_payload_from_subscription(
+ event_type=event_type,
+ subscribable_object=checkout,
+ subscription_query=webhook.subscription_query,
+ request=request_context,
+ app=app,
+ )
+ if payload:
+ results[checkout_token][app_id][query_hash] = payload
+ print("IN DATALOADER", "!" * 20)
+ from pprint import pprint
+
+ print(keys)
+ pprint(dict(results))
+ return [results[str(checkout_token)] for checkout_token in keys]
+
+ checkouts_info = CheckoutInfoByCheckoutTokenLoader(self.context).load_many(keys)
+ lines = CheckoutLinesInfoByCheckoutTokenLoader(self.context).load_many(keys)
+ apps = AppByIdLoader(self.context).load_many(apps_ids)
+ return Promise.all([checkouts_info, lines, apps]).then(generate_payloads)
diff --git a/saleor/graphql/webhook/utils.py b/saleor/graphql/webhook/utils.py
index c5ddb50a53..e746b10784 100644
--- a/saleor/graphql/webhook/utils.py
+++ b/saleor/graphql/webhook/utils.py
@@ -26,8 +26,6 @@ def get_pregenerated_subscription_payload(
return None
query_hash = get_subscription_query_hash(webhook.subscription_query)
- return (
- pregenerated_subscription_payloads.get(webhook.app_id, {})
- .get(query_hash, {})
- .get(str(subscriptable_object.pk), None)
+ return pregenerated_subscription_payloads.get(webhook.app_id, {}).get(
+ query_hash, None
)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 7d7bce8224..c25d7d9f48 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -3083,18 +3083,8 @@ class WebhookPlugin(BasePlugin):
previous_value,
pregenerated_subscription_payloads={},
) -> Optional["TaxData"]:
- print("checkout_info", checkout_info)
- print("lines", lines)
- print("app_identifier", app_identifier)
- print("previous_value", previous_value)
- from pprint import pprint
-
- print("pregenerated_subscription_payloads", "!" * 50)
- pprint(pregenerated_subscription_payloads)
- print("\n\n")
event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
if app_identifier:
-
return self.__run_tax_webhook(
event_type,
app_identifier,
diff --git a/saleor/tax/utils.py b/saleor/tax/utils.py
index 86a6d80d13..cb6d4a7f00 100644
--- a/saleor/tax/utils.py
+++ b/saleor/tax/utils.py
@@ -128,7 +128,7 @@ def get_tax_app_identifier_for_order(order: "Order"):
return get_tax_app_id(tax_configuration, country_tax_configuration)
-def _get_tax_configuration_for_checkout(
+def get_tax_configuration_for_checkout(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
@@ -158,7 +158,7 @@ def get_charge_taxes_for_checkout(
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
"""Get charge_taxes value for checkout."""
- tax_configuration, country_tax_configuration = _get_tax_configuration_for_checkout(
+ tax_configuration, country_tax_configuration = get_tax_configuration_for_checkout(
checkout_info, lines, database_connection_name=database_connection_name
)
return get_charge_taxes(tax_configuration, country_tax_configuration)
@@ -170,7 +170,7 @@ def get_tax_calculation_strategy_for_checkout(
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
"""Get tax_calculation_strategy value for checkout."""
- tax_configuration, country_tax_configuration = _get_tax_configuration_for_checkout(
+ tax_configuration, country_tax_configuration = get_tax_configuration_for_checkout(
checkout_info, lines, database_connection_name=database_connection_name
)
return get_tax_calculation_strategy(tax_configuration, country_tax_configuration)
@@ -182,7 +182,7 @@ def get_tax_app_identifier_for_checkout(
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
"""Get tax_app_id value for checkout."""
- tax_configuration, country_tax_configuration = _get_tax_configuration_for_checkout(
+ tax_configuration, country_tax_configuration = get_tax_configuration_for_checkout(
checkout_info, lines, database_connection_name=database_connection_name
)
return get_tax_app_id(tax_configuration, country_tax_configuration)
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index 687194f769..caaf1053d5 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -252,7 +252,15 @@ def create_delivery_for_subscription_sync_event(
request=request,
app=webhook.app,
)
+ print("Payload generated from subscription!!!!!!!")
+ print("webhook", webhook.pk)
+ print("app", webhook.app_id)
+ print("subscribable_object", subscribable_object)
+ print("subscribable_object_id", subscribable_object.pk)
+ print("data", data)
else:
+ print("Using pregenerated payload")
+ print("For checkout", subscribable_object.token)
data = pregenerated_payload
if not data: