Skip to content

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

Split dataloaders in checkout and webhooks to avoid circular imports (#16617)

Filip Owczarek7059046306d0
diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.py
deleted file mode 100644
index 81a55c3926..0000000000
--- a/saleor/graphql/checkout/dataloaders.py
+++ /dev/null
@@ -1,800 +0,0 @@
-from collections import defaultdict
-from collections.abc import Iterable
-
-from django.db.models import F
-from promise import Promise
-
-from ...checkout.fetch import (
- CheckoutInfo,
- CheckoutLineInfo,
-)
-from ...checkout.models import Checkout, CheckoutLine, CheckoutMetadata
-from ...checkout.problems import (
- CHANNEL_SLUG,
- CHECKOUT_LINE_PROBLEM_TYPE,
- CHECKOUT_PROBLEM_TYPE,
- COUNTRY_CODE,
- PRODUCT_ID,
- VARIANT_ID,
- get_checkout_lines_problems,
- get_checkout_problems,
-)
-from ...core.db.connection import allow_writer_in_context
-from ...discount import VoucherType
-from ...discount.interface import VariantPromotionRuleInfo
-from ...discount.utils.voucher import apply_voucher_to_line
-from ...payment.models import TransactionItem
-from ...product.models import ProductChannelListing
-from ...warehouse.models import Stock
-from ..account.dataloaders import AddressByIdLoader, UserByUserIdLoader
-from ..channel.dataloaders import ChannelByIdLoader
-from ..core.dataloaders import DataLoader
-from ..discount.dataloaders import (
- CheckoutDiscountByCheckoutIdLoader,
- CheckoutLineDiscountsByCheckoutLineIdLoader,
- PromotionByRuleIdLoader,
- PromotionRuleByIdLoader,
- VoucherCodeByCodeLoader,
- VoucherInfoByVoucherCodeLoader,
-)
-from ..plugins.dataloaders import get_plugin_manager_promise
-from ..product.dataloaders import (
- CollectionsByVariantIdLoader,
- ProductByVariantIdLoader,
- ProductChannelListingByProductIdAndChannelSlugLoader,
- ProductTypeByVariantIdLoader,
- ProductVariantByIdLoader,
- VariantChannelListingByVariantIdAndChannelIdLoader,
- VariantChannelListingPromotionRuleByListingIdLoader,
-)
-from ..shipping.dataloaders import (
- ShippingMethodByIdLoader,
- ShippingMethodChannelListingByChannelSlugLoader,
-)
-from ..tax.dataloaders import TaxClassByVariantIdLoader, TaxConfigurationByChannelId
-from ..translations.dataloaders import (
- PromotionRuleTranslationByIdAndLanguageCodeLoader,
- PromotionTranslationByIdAndLanguageCodeLoader,
-)
-from ..warehouse.dataloaders import (
- StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,
- WarehouseByIdLoader,
-)
-
-
-class CheckoutByTokenLoader(DataLoader[str, Checkout]):
- context_key = "checkout_by_token"
-
- def batch_load(self, keys):
- checkouts = Checkout.objects.using(self.database_connection_name).in_bulk(keys)
- return [checkouts.get(token) for token in keys]
-
-
-class CheckoutLinesInfoByCheckoutTokenLoader(DataLoader[str, list[CheckoutLineInfo]]):
- context_key = "checkoutlinesinfo_by_checkout"
-
- def batch_load(self, keys):
- def with_checkout_lines(results):
- checkouts, checkout_lines = results
-
- variants_pks = set()
- lines_pks = set()
- for lines in checkout_lines:
- for line in lines:
- lines_pks.add(line.id)
- variants_pks.add(line.variant_id)
- lines_pks = list(lines_pks)
- variants_pks = list(variants_pks)
- if not variants_pks:
- return [[] for _ in keys]
-
- channel_pks = [checkout.channel_id for checkout in checkouts]
-
- @allow_writer_in_context(self.context)
- def with_variants_products_collections(results):
- (
- variants,
- products,
- product_types,
- collections,
- tax_classes,
- channel_listings,
- voucher_infos,
- channels,
- checkout_lines_discounts,
- variant_promotion_rules_info,
- ) = results
- variants_map = dict(zip(variants_pks, variants))
- products_map = dict(zip(variants_pks, products))
- product_types_map = dict(zip(variants_pks, product_types))
- collections_map = dict(zip(variants_pks, collections))
- tax_class_map = dict(zip(variants_pks, tax_classes))
- channel_listings_map = dict(
- zip(variant_ids_channel_ids, channel_listings)
- )
- channels = dict(zip(channel_pks, channels))
- checkout_lines_discounts = dict(
- zip(lines_pks, checkout_lines_discounts)
- )
- rules_info_map = dict(zip(lines_pks, variant_promotion_rules_info))
-
- lines_info_map = defaultdict(list)
- voucher_infos_map = {
- voucher_info.voucher_code: voucher_info
- for voucher_info in voucher_infos
- if voucher_info is not None and voucher_info.voucher_code
- }
- for checkout, lines in zip(checkouts, checkout_lines):
- lines_info_map[checkout.pk].extend(
- [
- CheckoutLineInfo(
- line=line,
- variant=variants_map[line.variant_id],
- channel_listing=channel_listings_map[
- (line.variant_id, checkout.channel_id)
- ],
- product=products_map[line.variant_id],
- product_type=product_types_map[line.variant_id],
- collections=sorted(
- collections_map[line.variant_id],
- key=(
- lambda collection: collection.slug
- if collection
- else ""
- ),
- ),
- discounts=checkout_lines_discounts[line.id],
- tax_class=tax_class_map[line.variant_id],
- channel=channels[checkout.channel_id],
- rules_info=rules_info_map[line.id],
- voucher=None,
- voucher_code=None,
- )
- for line in lines
- ]
- )
-
- for checkout in checkouts:
- if not checkout.voucher_code:
- continue
- voucher_info = voucher_infos_map.get(checkout.voucher_code)
- if not voucher_info:
- continue
- voucher = voucher_info.voucher
- if (
- voucher.type == VoucherType.SPECIFIC_PRODUCT
- or voucher.apply_once_per_order
- ):
- apply_voucher_to_line(
- voucher_info=voucher_info,
- lines_info=lines_info_map[checkout.pk],
- )
- return [lines_info_map[key] for key in keys]
-
- checkout_lines_discounts = CheckoutLineDiscountsByCheckoutLineIdLoader(
- self.context
- ).load_many(lines_pks)
- variant_promotion_rules_info = (
- VariantPromotionRuleInfoByCheckoutLineIdLoader(self.context).load_many(
- lines_pks
- )
- )
- variants = ProductVariantByIdLoader(self.context).load_many(variants_pks)
- products = ProductByVariantIdLoader(self.context).load_many(variants_pks)
- product_types = ProductTypeByVariantIdLoader(self.context).load_many(
- variants_pks
- )
- collections = CollectionsByVariantIdLoader(self.context).load_many(
- variants_pks
- )
- tax_classes = TaxClassByVariantIdLoader(self.context).load_many(
- variants_pks
- )
-
- voucher_codes = {
- checkout.voucher_code for checkout in checkouts if checkout.voucher_code
- }
- voucher_infos = VoucherInfoByVoucherCodeLoader(self.context).load_many(
- voucher_codes
- )
-
- variant_ids_channel_ids = []
- for channel_id, lines in zip(channel_pks, checkout_lines):
- variant_ids_channel_ids.extend(
- [(line.variant_id, channel_id) for line in lines]
- )
-
- channel_listings = VariantChannelListingByVariantIdAndChannelIdLoader(
- self.context
- ).load_many(variant_ids_channel_ids)
-
- channels = ChannelByIdLoader(self.context).load_many(channel_pks)
- return Promise.all(
- [
- variants,
- products,
- product_types,
- collections,
- tax_classes,
- channel_listings,
- voucher_infos,
- channels,
- checkout_lines_discounts,
- variant_promotion_rules_info,
- ]
- ).then(with_variants_products_collections)
-
- checkouts = CheckoutByTokenLoader(self.context).load_many(keys)
- checkout_lines = CheckoutLinesByCheckoutTokenLoader(self.context).load_many(
- keys
- )
- return Promise.all([checkouts, checkout_lines]).then(with_checkout_lines)
-
-
-class CheckoutByUserLoader(DataLoader[int, list[Checkout]]):
- context_key = "checkout_by_user"
-
- def batch_load(self, keys):
- checkouts = Checkout.objects.using(self.database_connection_name).filter(
- user_id__in=keys, channel__is_active=True
- )
- checkout_by_user_map = defaultdict(list)
- for checkout in checkouts:
- checkout_by_user_map[checkout.user_id].append(checkout)
- return [checkout_by_user_map[user_id] for user_id in keys]
-
-
-class CheckoutByUserAndChannelLoader(DataLoader[tuple[int, str], list[Checkout]]):
- context_key = "checkout_by_user_and_channel"
-
- def batch_load(self, keys: Iterable[tuple[int, str]]):
- user_ids = [key[0] for key in keys]
- channel_slugs = [key[1] for key in keys]
- checkouts = (
- Checkout.objects.using(self.database_connection_name)
- .filter(
- user_id__in=user_ids,
- channel__slug__in=channel_slugs,
- channel__is_active=True,
- )
- .annotate(channel_slug=F("channel__slug"))
- .order_by("-last_change", "pk")
- )
- checkout_by_user_and_channel_map = defaultdict(list)
- for checkout in checkouts:
- key = (checkout.user_id, checkout.channel_slug)
- checkout_by_user_and_channel_map[key].append(checkout)
- return [checkout_by_user_and_channel_map[key] for key in keys]
-
-
-class VariantPromotionRuleInfoByCheckoutLineIdLoader(DataLoader):
- context_key = "variant_promotion_rule_info_by_checkout_line_id"
-
- def batch_load(self, keys):
- def with_checkout_lines(checkout_lines):
- def with_checkouts(checkouts):
- variants_pks = [line.variant_id for line in checkout_lines]
- if not variants_pks:
- return []
-
- channel_pks = [checkout.channel_id for checkout in checkouts]
-
- def with_channel_listings(channel_listings):
- def with_channel_listing_promotion_rules(
- variant_listing_promotion_rules,
- ):
- rule_ids: list[int] = []
- rule_ids_language_codes: list[tuple[int, str]] = []
- for listing_promotion_rules, language_code in zip(
- variant_listing_promotion_rules, language_codes
- ):
- for listing_promotion_rule in listing_promotion_rules:
- rule_ids.append(
- listing_promotion_rule.promotion_rule_id
- )
- rule_ids_language_codes.append(
- (
- listing_promotion_rule.promotion_rule_id,
- language_code,
- )
- )
-
- def with_promotion_rules(results):
- promotion_rules, promotions, rule_translations = results
-
- promotion_ids_language_codes = [
- (rule.promotion_id, language_code)
- for rule, (_rule_id, language_code) in zip(
- promotion_rules, rule_ids_language_codes
- )
- ]
-
- def with_promotion_translations(promotion_translations):
- channel_listings_map = dict(
- zip(variant_ids_channel_ids, channel_listings)
- )
- listing_promotion_rules_map = dict(
- zip(
- channel_listing_ids,
- variant_listing_promotion_rules,
- )
- )
- rule_map = dict(zip(rule_ids, promotion_rules))
- rule_id_to_promotion_map = dict(
- zip(rule_ids, promotions)
- )
- rule_id_to_rule_translation = dict(
- zip(rule_ids, rule_translations)
- )
- rule_id_to_promotion_translation = dict(
- zip(rule_ids, promotion_translations)
- )
-
- rules_info_map = defaultdict(list)
- for checkout, line in zip(checkouts, checkout_lines):
- channel_listing = channel_listings_map[
- (line.variant_id, checkout.channel_id)
- ]
- listing_promotion_rules = (
- listing_promotion_rules_map[channel_listing.id]
- if channel_listing
- else []
- )
- rules_info_map[line.id] = [
- VariantPromotionRuleInfo(
- rule=rule_map[
- listing_rule.promotion_rule_id
- ],
- variant_listing_promotion_rule=listing_rule,
- promotion=rule_id_to_promotion_map[
- listing_rule.promotion_rule_id
- ],
- rule_translation=rule_id_to_rule_translation[
- listing_rule.promotion_rule_id
- ],
- promotion_translation=rule_id_to_promotion_translation[
- listing_rule.promotion_rule_id
- ],
- )
- for listing_rule in listing_promotion_rules
- ]
-
- return [rules_info_map[key] for key in keys]
-
- return (
- PromotionTranslationByIdAndLanguageCodeLoader(
- self.context
- )
- .load_many(promotion_ids_language_codes)
- .then(with_promotion_translations)
- )
-
- promotion_rules = PromotionRuleByIdLoader(
- self.context
- ).load_many(rule_ids)
- promotions = PromotionByRuleIdLoader(self.context).load_many(
- rule_ids
- )
-
- rules_translations = (
- PromotionRuleTranslationByIdAndLanguageCodeLoader(
- self.context
- ).load_many(rule_ids_language_codes)
- )
- return Promise.all(
- [promotion_rules, promotions, rules_translations]
- ).then(with_promotion_rules)
-
- channel_listing_ids = [
- listing.id for listing in channel_listings if listing
- ]
- return (
- VariantChannelListingPromotionRuleByListingIdLoader(
- self.context
- )
- .load_many(channel_listing_ids)
- .then(with_channel_listing_promotion_rules)
- )
-
- variant_ids_channel_ids = [
- (line.variant_id, channel_id)
- for line, channel_id in zip(checkout_lines, channel_pks)
- ]
- language_codes = [checkout.language_code for checkout in checkouts]
-
- return (
- VariantChannelListingByVariantIdAndChannelIdLoader(self.context)
- .load_many(variant_ids_channel_ids)
- .then(with_channel_listings)
- )
-
- checkout_tokens = [line.checkout_id for line in checkout_lines]
- return (
- CheckoutByTokenLoader(self.context)
- .load_many(checkout_tokens)
- .then(with_checkouts)
- )
-
- return (
- CheckoutLineByIdLoader(self.context)
- .load_many(keys)
- .then(with_checkout_lines)
- )
-
-
-class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
- context_key = "checkoutinfo_by_checkout"
-
- def batch_load(self, keys):
- def with_checkout(data):
- checkouts, checkout_line_infos, checkout_discounts, manager = data
- from ..channel.dataloaders import ChannelByIdLoader
-
- channel_pks = [checkout.channel_id for checkout in checkouts]
-
- def with_channel(channels):
- billing_address_ids = {
- checkout.billing_address_id
- for checkout in checkouts
- if checkout.billing_address_id
- }
- shipping_address_ids = {
- checkout.shipping_address_id
- for checkout in checkouts
- if checkout.shipping_address_id
- }
- addresses = AddressByIdLoader(self.context).load_many(
- billing_address_ids | shipping_address_ids
- )
- users = UserByUserIdLoader(self.context).load_many(
- [checkout.user_id for checkout in checkouts if checkout.user_id]
- )
- shipping_method_ids = [
- checkout.shipping_method_id
- for checkout in checkouts
- if checkout.shipping_method_id
- ]
- shipping_methods = ShippingMethodByIdLoader(self.context).load_many(
- shipping_method_ids
- )
- channel_slugs = [channel.slug for channel in channels]
- shipping_method_channel_listings = (
- ShippingMethodChannelListingByChannelSlugLoader(
- self.context
- ).load_many(channel_slugs)
- )
- collection_point_ids = [
- checkout.collection_point_id
- for checkout in checkouts
- if checkout.collection_point_id
- ]
- collection_points = WarehouseByIdLoader(self.context).load_many(
- collection_point_ids
- )
-
- voucher_codes = VoucherCodeByCodeLoader(self.context).load_many(
- {
- checkout.voucher_code
- for checkout in checkouts
- if checkout.voucher_code
- }
- )
-
- channel_ids = [channel.id for channel in channels]
- tax_configurations = TaxConfigurationByChannelId(
- self.context
- ).load_many(channel_ids)
-
- def with_checkout_info(results):
- (
- addresses,
- users,
- shipping_methods,
- listings_for_channels,
- collection_points,
- voucher_codes,
- tax_configurations,
- ) = results
- address_map = {address.id: address for address in addresses}
- user_map = {user.id: user for user in users}
- shipping_method_map = {
- shipping_method.id: shipping_method
- for shipping_method in shipping_methods
- }
- collection_points_map = {
- collection_point.id: collection_point
- for collection_point in collection_points
- }
-
- voucher_code_map = {
- voucher_code.code: voucher_code
- for voucher_code in voucher_codes
- if voucher_code
- }
- tax_configuration_by_channel_map = {
- tax_configuration.channel_id: tax_configuration
- for tax_configuration in tax_configurations
- }
-
- checkout_info_map = {}
- for key, checkout, channel, checkout_lines, discounts in zip(
- keys,
- checkouts,
- channels,
- checkout_line_infos,
- checkout_discounts,
- ):
- shipping_method = shipping_method_map.get(
- checkout.shipping_method_id
- )
- collection_point = collection_points_map.get(
- checkout.collection_point_id
- )
- voucher_code = voucher_code_map.get(checkout.voucher_code)
-
- shipping_channel_listings = [
- listing
- for channel_listings in listings_for_channels
- for listing in channel_listings
- if listing.channel_id == channel.id
- ]
-
- checkout_info = CheckoutInfo(
- checkout=checkout,
- user=user_map.get(checkout.user_id),
- channel=channel,
- billing_address=address_map.get(
- checkout.billing_address_id
- ),
- shipping_address=address_map.get(
- checkout.shipping_address_id
- ),
- tax_configuration=tax_configuration_by_channel_map[
- channel.id
- ],
- discounts=discounts,
- lines=checkout_lines,
- manager=manager,
- shipping_channel_listings=shipping_channel_listings,
- shipping_method=shipping_method,
- collection_point=collection_point,
- voucher=voucher_code.voucher if voucher_code else None,
- voucher_code=voucher_code,
- database_connection_name=self.database_connection_name,
- )
- checkout_info_map[key] = checkout_info
-
- return [checkout_info_map[key] for key in keys]
-
- return Promise.all(
- [
- addresses,
- users,
- shipping_methods,
- shipping_method_channel_listings,
- collection_points,
- voucher_codes,
- tax_configurations,
- ]
- ).then(with_checkout_info)
-
- return (
- ChannelByIdLoader(self.context)
- .load_many(channel_pks)
- .then(with_channel)
- )
-
- checkouts = CheckoutByTokenLoader(self.context).load_many(keys)
- checkout_line_infos = CheckoutLinesInfoByCheckoutTokenLoader(
- self.context
- ).load_many(keys)
- discounts = CheckoutDiscountByCheckoutIdLoader(self.context).load_many(keys)
- manager = get_plugin_manager_promise(self.context)
- return Promise.all([checkouts, checkout_line_infos, discounts, manager]).then(
- with_checkout
- )
-
-
-class CheckoutLineByIdLoader(DataLoader[str, CheckoutLine]):
- context_key = "checkout_line_by_id"
-
- def batch_load(self, keys):
- checkout_lines = CheckoutLine.objects.using(
- self.database_connection_name
- ).in_bulk(keys)
- return [checkout_lines.get(line_id) for line_id in keys]
-
-
-class CheckoutLinesByCheckoutTokenLoader(DataLoader[str, list[CheckoutLine]]):
- context_key = "checkoutlines_by_checkout"
-
- def batch_load(self, keys):
- lines = CheckoutLine.objects.using(self.database_connection_name).filter(
- checkout_id__in=keys
- )
- line_map = defaultdict(list)
- for line in lines.iterator():
- line_map[line.checkout_id].append(line)
- return [line_map.get(checkout_id, []) for checkout_id in keys]
-
-
-class TransactionItemsByCheckoutIDLoader(DataLoader[str, list[TransactionItem]]):
- context_key = "transaction_items_by_checkout_id"
-
- def batch_load(self, keys):
- transactions = (
- TransactionItem.objects.using(self.database_connection_name)
- .filter(checkout_id__in=keys)
- .order_by("pk")
- )
- transactions_map = defaultdict(list)
- for transaction in transactions:
- transactions_map[transaction.checkout_id].append(transaction)
- return [transactions_map[checkout_id] for checkout_id in keys]
-
-
-class CheckoutMetadataByCheckoutIdLoader(DataLoader[str, CheckoutMetadata]):
- context_key = "checkout_metadata_by_checkout_id"
-
- def batch_load(self, keys):
- checkout_metadata = CheckoutMetadata.objects.using(
- self.database_connection_name
- ).in_bulk(keys, field_name="checkout_id")
- return [checkout_metadata.get(checkout_id) for checkout_id in keys]
-
-
-class ChannelByCheckoutIDLoader(DataLoader):
- context_key = "channel_by_checkout"
-
- def batch_load(self, keys):
- def with_checkouts(checkouts):
- def with_channels(channels):
- channel_map = {channel.id: channel for channel in channels}
- return [
- channel_map.get(checkout.channel_id) if checkout else None
- for checkout in checkouts
- ]
-
- channel_ids = set(checkout.channel_id for checkout in checkouts if checkout)
- return (
- ChannelByIdLoader(self.context)
- .load_many(channel_ids)
- .then(with_channels)
- )
-
- return CheckoutByTokenLoader(self.context).load_many(keys).then(with_checkouts)
-
-
-class CheckoutLinesProblemsByCheckoutIdLoader(
- DataLoader[str, dict[str, list[CHECKOUT_LINE_PROBLEM_TYPE]]]
-):
- context_key = "checkout_lines_problems_by_checkout_id"
-
- def batch_load(self, keys):
- stock_dataloader = (
- StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
- self.context
- )
- )
-
- def _resolve_problems(data):
- checkout_infos, checkout_lines = data
- variant_data_set: set[
- tuple[
- VARIANT_ID,
- CHANNEL_SLUG,
- COUNTRY_CODE,
- ]
- ] = set()
- product_data_set: set[
- tuple[
- PRODUCT_ID,
- CHANNEL_SLUG,
- ]
- ] = set()
- checkout_infos_map = {
- checkout_info.checkout.pk: checkout_info
- for checkout_info in checkout_infos
- }
- for lines in checkout_lines:
- for line in lines:
- variant_data_set.add(
- (
- line.variant.id,
- line.channel.slug,
- checkout_infos_map[line.line.checkout_id].checkout.country,
- )
- )
- product_data_set.add(
- (
- line.product.id,
- line.channel.slug,
- )
- )
- variant_data_list = list(variant_data_set)
- product_data_list = list(product_data_set)
-
- def _prepare_problems(data):
- (
- variant_stocks,
- product_channel_listings,
- ) = data
- variant_stock_map: dict[
- tuple[
- VARIANT_ID,
- CHANNEL_SLUG,
- COUNTRY_CODE,
- ],
- Iterable[Stock],
- ] = dict(zip(variant_data_list, variant_stocks))
- product_channel_listings_map: dict[
- tuple[
- PRODUCT_ID,
- CHANNEL_SLUG,
- ],
- ProductChannelListing,
- ] = dict(zip(product_data_set, product_channel_listings))
-
- problems = {}
-
- for checkout_info, lines in zip(checkout_infos, checkout_lines):
- checkout_id = checkout_info.checkout.pk
- problems[checkout_id] = get_checkout_lines_problems(
- checkout_info,
- lines,
- variant_stock_map,
- product_channel_listings_map,
- )
- return [problems.get(key, []) for key in keys]
-
- variant_stocks = stock_dataloader.load_many(
- [
- (variant_id, country_code, channel_slug)
- for variant_id, channel_slug, country_code in variant_data_list
- ]
- )
- product_channel_listings = (
- ProductChannelListingByProductIdAndChannelSlugLoader(
- self.context
- ).load_many(
- [
- (
- product_id,
- channel_slug,
- )
- for product_id, channel_slug in product_data_list
- ]
- )
- )
-
- return Promise.all([variant_stocks, product_channel_listings]).then(
- _prepare_problems
- )
-
- checkout_infos = CheckoutInfoByCheckoutTokenLoader(self.context).load_many(keys)
- lines = CheckoutLinesInfoByCheckoutTokenLoader(self.context).load_many(keys)
- return Promise.all([checkout_infos, lines]).then(_resolve_problems)
-
-
-class CheckoutProblemsByCheckoutIdDataloader(
- DataLoader[str, dict[str, list[CHECKOUT_PROBLEM_TYPE]]]
-):
- context_key = "checkout_problems_by_checkout_id"
-
- def batch_load(self, keys):
- line_problems_dataloader = CheckoutLinesProblemsByCheckoutIdLoader(self.context)
-
- def _resolve_problems(
- checkouts_lines_problems: list[dict[str, list[CHECKOUT_LINE_PROBLEM_TYPE]]],
- ):
- checkout_problems = defaultdict(list)
- for checkout_pk, checkout_lines_problems in zip(
- keys, checkouts_lines_problems
- ):
- checkout_problems[checkout_pk] = get_checkout_problems(
- checkout_lines_problems
- )
-
- return [checkout_problems.get(key, []) for key in keys]
-
- return line_problems_dataloader.load_many(keys).then(_resolve_problems)
diff --git a/saleor/graphql/checkout/dataloaders/__init__.py b/saleor/graphql/checkout/dataloaders/__init__.py
new file mode 100644
index 0000000000..822da82f67
--- /dev/null
+++ b/saleor/graphql/checkout/dataloaders/__init__.py
@@ -0,0 +1,35 @@
+from .checkout_infos import (
+ CheckoutInfoByCheckoutTokenLoader,
+ CheckoutLinesInfoByCheckoutTokenLoader,
+)
+from .models import (
+ ChannelByCheckoutIDLoader,
+ CheckoutByTokenLoader,
+ CheckoutByUserAndChannelLoader,
+ CheckoutByUserLoader,
+ CheckoutLineByIdLoader,
+ CheckoutLinesByCheckoutTokenLoader,
+ CheckoutMetadataByCheckoutIdLoader,
+ TransactionItemsByCheckoutIDLoader,
+)
+from .problems import (
+ CheckoutLinesProblemsByCheckoutIdLoader,
+ CheckoutProblemsByCheckoutIdDataloader,
+)
+from .promotion_rule_infos import VariantPromotionRuleInfoByCheckoutLineIdLoader
+
+__all__ = [
+ "ChannelByCheckoutIDLoader",
+ "CheckoutByTokenLoader",
+ "CheckoutByUserAndChannelLoader",
+ "CheckoutByUserLoader",
+ "CheckoutInfoByCheckoutTokenLoader",
+ "CheckoutLineByIdLoader",
+ "CheckoutLinesByCheckoutTokenLoader",
+ "CheckoutLinesInfoByCheckoutTokenLoader",
+ "CheckoutLinesProblemsByCheckoutIdLoader",
+ "CheckoutMetadataByCheckoutIdLoader",
+ "CheckoutProblemsByCheckoutIdDataloader",
+ "TransactionItemsByCheckoutIDLoader",
+ "VariantPromotionRuleInfoByCheckoutLineIdLoader",
+]
diff --git a/saleor/graphql/checkout/dataloaders/checkout_infos.py b/saleor/graphql/checkout/dataloaders/checkout_infos.py
new file mode 100644
index 0000000000..73d5f4c09c
--- /dev/null
+++ b/saleor/graphql/checkout/dataloaders/checkout_infos.py
@@ -0,0 +1,371 @@
+from collections import defaultdict
+
+from promise import Promise
+
+from ....checkout.fetch import (
+ CheckoutInfo,
+ CheckoutLineInfo,
+)
+from ....core.db.connection import allow_writer_in_context
+from ....discount import VoucherType
+from ....discount.utils.voucher import apply_voucher_to_line
+from ...account.dataloaders import AddressByIdLoader, UserByUserIdLoader
+from ...channel.dataloaders import ChannelByIdLoader
+from ...core.dataloaders import DataLoader
+from ...discount.dataloaders import (
+ CheckoutDiscountByCheckoutIdLoader,
+ CheckoutLineDiscountsByCheckoutLineIdLoader,
+ VoucherCodeByCodeLoader,
+ VoucherInfoByVoucherCodeLoader,
+)
+from ...plugins.dataloaders import get_plugin_manager_promise
+from ...product.dataloaders import (
+ CollectionsByVariantIdLoader,
+ ProductByVariantIdLoader,
+ ProductTypeByVariantIdLoader,
+ ProductVariantByIdLoader,
+ VariantChannelListingByVariantIdAndChannelIdLoader,
+)
+from ...shipping.dataloaders import (
+ ShippingMethodByIdLoader,
+ ShippingMethodChannelListingByChannelSlugLoader,
+)
+from ...tax.dataloaders import TaxClassByVariantIdLoader, TaxConfigurationByChannelId
+from ...warehouse.dataloaders import (
+ WarehouseByIdLoader,
+)
+from .models import CheckoutByTokenLoader, CheckoutLinesByCheckoutTokenLoader
+from .promotion_rule_infos import VariantPromotionRuleInfoByCheckoutLineIdLoader
+
+
+class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
+ context_key = "checkoutinfo_by_checkout"
+
+ def batch_load(self, keys):
+ def with_checkout(data):
+ checkouts, checkout_line_infos, checkout_discounts, manager = data
+
+ channel_pks = [checkout.channel_id for checkout in checkouts]
+
+ def with_channel(channels):
+ billing_address_ids = {
+ checkout.billing_address_id
+ for checkout in checkouts
+ if checkout.billing_address_id
+ }
+ shipping_address_ids = {
+ checkout.shipping_address_id
+ for checkout in checkouts
+ if checkout.shipping_address_id
+ }
+ addresses = AddressByIdLoader(self.context).load_many(
+ billing_address_ids | shipping_address_ids
+ )
+ users = UserByUserIdLoader(self.context).load_many(
+ [checkout.user_id for checkout in checkouts if checkout.user_id]
+ )
+ shipping_method_ids = [
+ checkout.shipping_method_id
+ for checkout in checkouts
+ if checkout.shipping_method_id
+ ]
+ shipping_methods = ShippingMethodByIdLoader(self.context).load_many(
+ shipping_method_ids
+ )
+ channel_slugs = [channel.slug for channel in channels]
+ shipping_method_channel_listings = (
+ ShippingMethodChannelListingByChannelSlugLoader(
+ self.context
+ ).load_many(channel_slugs)
+ )
+ collection_point_ids = [
+ checkout.collection_point_id
+ for checkout in checkouts
+ if checkout.collection_point_id
+ ]
+ collection_points = WarehouseByIdLoader(self.context).load_many(
+ collection_point_ids
+ )
+
+ voucher_codes = VoucherCodeByCodeLoader(self.context).load_many(
+ {
+ checkout.voucher_code
+ for checkout in checkouts
+ if checkout.voucher_code
+ }
+ )
+
+ channel_ids = [channel.id for channel in channels]
+ tax_configurations = TaxConfigurationByChannelId(
+ self.context
+ ).load_many(channel_ids)
+
+ def with_checkout_info(results):
+ (
+ addresses,
+ users,
+ shipping_methods,
+ listings_for_channels,
+ collection_points,
+ voucher_codes,
+ tax_configurations,
+ ) = results
+ address_map = {address.id: address for address in addresses}
+ user_map = {user.id: user for user in users}
+ shipping_method_map = {
+ shipping_method.id: shipping_method
+ for shipping_method in shipping_methods
+ }
+ collection_points_map = {
+ collection_point.id: collection_point
+ for collection_point in collection_points
+ }
+
+ voucher_code_map = {
+ voucher_code.code: voucher_code
+ for voucher_code in voucher_codes
+ if voucher_code
+ }
+ tax_configuration_by_channel_map = {
+ tax_configuration.channel_id: tax_configuration
+ for tax_configuration in tax_configurations
+ }
+
+ checkout_info_map = {}
+ for key, checkout, channel, checkout_lines, discounts in zip(
+ keys,
+ checkouts,
+ channels,
+ checkout_line_infos,
+ checkout_discounts,
+ ):
+ shipping_method = shipping_method_map.get(
+ checkout.shipping_method_id
+ )
+ collection_point = collection_points_map.get(
+ checkout.collection_point_id
+ )
+ voucher_code = voucher_code_map.get(checkout.voucher_code)
+
+ shipping_channel_listings = [
+ listing
+ for channel_listings in listings_for_channels
+ for listing in channel_listings
+ if listing.channel_id == channel.id
+ ]
+
+ checkout_info = CheckoutInfo(
+ checkout=checkout,
+ user=user_map.get(checkout.user_id),
+ channel=channel,
+ billing_address=address_map.get(
+ checkout.billing_address_id
+ ),
+ shipping_address=address_map.get(
+ checkout.shipping_address_id
+ ),
+ tax_configuration=tax_configuration_by_channel_map[
+ channel.id
+ ],
+ discounts=discounts,
+ lines=checkout_lines,
+ manager=manager,
+ shipping_channel_listings=shipping_channel_listings,
+ shipping_method=shipping_method,
+ collection_point=collection_point,
+ voucher=voucher_code.voucher if voucher_code else None,
+ voucher_code=voucher_code,
+ database_connection_name=self.database_connection_name,
+ )
+ checkout_info_map[key] = checkout_info
+
+ return [checkout_info_map[key] for key in keys]
+
+ return Promise.all(
+ [
+ addresses,
+ users,
+ shipping_methods,
+ shipping_method_channel_listings,
+ collection_points,
+ voucher_codes,
+ tax_configurations,
+ ]
+ ).then(with_checkout_info)
+
+ return (
+ ChannelByIdLoader(self.context)
+ .load_many(channel_pks)
+ .then(with_channel)
+ )
+
+ checkouts = CheckoutByTokenLoader(self.context).load_many(keys)
+ checkout_line_infos = CheckoutLinesInfoByCheckoutTokenLoader(
+ self.context
+ ).load_many(keys)
+ discounts = CheckoutDiscountByCheckoutIdLoader(self.context).load_many(keys)
+ manager = get_plugin_manager_promise(self.context)
+ return Promise.all([checkouts, checkout_line_infos, discounts, manager]).then(
+ with_checkout
+ )
+
+
+class CheckoutLinesInfoByCheckoutTokenLoader(DataLoader[str, list[CheckoutLineInfo]]):
+ context_key = "checkoutlinesinfo_by_checkout"
+
+ def batch_load(self, keys):
+ def with_checkout_lines(results):
+ checkouts, checkout_lines = results
+
+ variants_pks = set()
+ lines_pks = set()
+ for lines in checkout_lines:
+ for line in lines:
+ lines_pks.add(line.id)
+ variants_pks.add(line.variant_id)
+ lines_pks = list(lines_pks)
+ variants_pks = list(variants_pks)
+ if not variants_pks:
+ return [[] for _ in keys]
+
+ channel_pks = [checkout.channel_id for checkout in checkouts]
+
+ @allow_writer_in_context(self.context)
+ def with_variants_products_collections(results):
+ (
+ variants,
+ products,
+ product_types,
+ collections,
+ tax_classes,
+ channel_listings,
+ voucher_infos,
+ channels,
+ checkout_lines_discounts,
+ variant_promotion_rules_info,
+ ) = results
+ variants_map = dict(zip(variants_pks, variants))
+ products_map = dict(zip(variants_pks, products))
+ product_types_map = dict(zip(variants_pks, product_types))
+ collections_map = dict(zip(variants_pks, collections))
+ tax_class_map = dict(zip(variants_pks, tax_classes))
+ channel_listings_map = dict(
+ zip(variant_ids_channel_ids, channel_listings)
+ )
+ channels = dict(zip(channel_pks, channels))
+ checkout_lines_discounts = dict(
+ zip(lines_pks, checkout_lines_discounts)
+ )
+ rules_info_map = dict(zip(lines_pks, variant_promotion_rules_info))
+
+ lines_info_map = defaultdict(list)
+ voucher_infos_map = {
+ voucher_info.voucher_code: voucher_info
+ for voucher_info in voucher_infos
+ if voucher_info is not None and voucher_info.voucher_code
+ }
+ for checkout, lines in zip(checkouts, checkout_lines):
+ lines_info_map[checkout.pk].extend(
+ [
+ CheckoutLineInfo(
+ line=line,
+ variant=variants_map[line.variant_id],
+ channel_listing=channel_listings_map[
+ (line.variant_id, checkout.channel_id)
+ ],
+ product=products_map[line.variant_id],
+ product_type=product_types_map[line.variant_id],
+ collections=sorted(
+ collections_map[line.variant_id],
+ key=(
+ lambda collection: (
+ collection.slug if collection else ""
+ )
+ ),
+ ),
+ discounts=checkout_lines_discounts[line.id],
+ tax_class=tax_class_map[line.variant_id],
+ channel=channels[checkout.channel_id],
+ rules_info=rules_info_map[line.id],
+ voucher=None,
+ voucher_code=None,
+ )
+ for line in lines
+ ]
+ )
+
+ for checkout in checkouts:
+ if not checkout.voucher_code:
+ continue
+ voucher_info = voucher_infos_map.get(checkout.voucher_code)
+ if not voucher_info:
+ continue
+ voucher = voucher_info.voucher
+ if (
+ voucher.type == VoucherType.SPECIFIC_PRODUCT
+ or voucher.apply_once_per_order
+ ):
+ apply_voucher_to_line(
+ voucher_info=voucher_info,
+ lines_info=lines_info_map[checkout.pk],
+ )
+ return [lines_info_map[key] for key in keys]
+
+ checkout_lines_discounts = CheckoutLineDiscountsByCheckoutLineIdLoader(
+ self.context
+ ).load_many(lines_pks)
+ variant_promotion_rules_info = (
+ VariantPromotionRuleInfoByCheckoutLineIdLoader(self.context).load_many(
+ lines_pks
+ )
+ )
+ variants = ProductVariantByIdLoader(self.context).load_many(variants_pks)
+ products = ProductByVariantIdLoader(self.context).load_many(variants_pks)
+ product_types = ProductTypeByVariantIdLoader(self.context).load_many(
+ variants_pks
+ )
+ collections = CollectionsByVariantIdLoader(self.context).load_many(
+ variants_pks
+ )
+ tax_classes = TaxClassByVariantIdLoader(self.context).load_many(
+ variants_pks
+ )
+
+ voucher_codes = {
+ checkout.voucher_code for checkout in checkouts if checkout.voucher_code
+ }
+ voucher_infos = VoucherInfoByVoucherCodeLoader(self.context).load_many(
+ voucher_codes
+ )
+
+ variant_ids_channel_ids = []
+ for channel_id, lines in zip(channel_pks, checkout_lines):
+ variant_ids_channel_ids.extend(
+ [(line.variant_id, channel_id) for line in lines]
+ )
+
+ channel_listings = VariantChannelListingByVariantIdAndChannelIdLoader(
+ self.context
+ ).load_many(variant_ids_channel_ids)
+
+ channels = ChannelByIdLoader(self.context).load_many(channel_pks)
+ return Promise.all(
+ [
+ variants,
+ products,
+ product_types,
+ collections,
+ tax_classes,
+ channel_listings,
+ voucher_infos,
+ channels,
+ checkout_lines_discounts,
+ variant_promotion_rules_info,
+ ]
+ ).then(with_variants_products_collections)
+
+ checkouts = CheckoutByTokenLoader(self.context).load_many(keys)
+ checkout_lines = CheckoutLinesByCheckoutTokenLoader(self.context).load_many(
+ keys
+ )
+ return Promise.all([checkouts, checkout_lines]).then(with_checkout_lines)
diff --git a/saleor/graphql/checkout/dataloaders/models.py b/saleor/graphql/checkout/dataloaders/models.py
new file mode 100644
index 0000000000..f2c070d9c6
--- /dev/null
+++ b/saleor/graphql/checkout/dataloaders/models.py
@@ -0,0 +1,123 @@
+from collections import defaultdict
+from collections.abc import Iterable
+
+from django.db.models import F
+
+from ....checkout.models import Checkout, CheckoutLine, CheckoutMetadata
+from ....payment.models import TransactionItem
+from ...channel.dataloaders import ChannelByIdLoader
+from ...core.dataloaders import DataLoader
+
+
+class CheckoutByTokenLoader(DataLoader[str, Checkout]):
+ context_key = "checkout_by_token"
+
+ def batch_load(self, keys):
+ checkouts = Checkout.objects.using(self.database_connection_name).in_bulk(keys)
+ return [checkouts.get(token) for token in keys]
+
+
+class CheckoutByUserLoader(DataLoader[int, list[Checkout]]):
+ context_key = "checkout_by_user"
+
+ def batch_load(self, keys):
+ checkouts = Checkout.objects.using(self.database_connection_name).filter(
+ user_id__in=keys, channel__is_active=True
+ )
+ checkout_by_user_map = defaultdict(list)
+ for checkout in checkouts:
+ checkout_by_user_map[checkout.user_id].append(checkout)
+ return [checkout_by_user_map[user_id] for user_id in keys]
+
+
+class CheckoutByUserAndChannelLoader(DataLoader[tuple[int, str], list[Checkout]]):
+ context_key = "checkout_by_user_and_channel"
+
+ def batch_load(self, keys: Iterable[tuple[int, str]]):
+ user_ids = [key[0] for key in keys]
+ channel_slugs = [key[1] for key in keys]
+ checkouts = (
+ Checkout.objects.using(self.database_connection_name)
+ .filter(
+ user_id__in=user_ids,
+ channel__slug__in=channel_slugs,
+ channel__is_active=True,
+ )
+ .annotate(channel_slug=F("channel__slug"))
+ .order_by("-last_change", "pk")
+ )
+ checkout_by_user_and_channel_map = defaultdict(list)
+ for checkout in checkouts:
+ key = (checkout.user_id, checkout.channel_slug)
+ checkout_by_user_and_channel_map[key].append(checkout)
+ return [checkout_by_user_and_channel_map[key] for key in keys]
+
+
+class CheckoutLineByIdLoader(DataLoader[str, CheckoutLine]):
+ context_key = "checkout_line_by_id"
+
+ def batch_load(self, keys):
+ checkout_lines = CheckoutLine.objects.using(
+ self.database_connection_name
+ ).in_bulk(keys)
+ return [checkout_lines.get(line_id) for line_id in keys]
+
+
+class CheckoutLinesByCheckoutTokenLoader(DataLoader[str, list[CheckoutLine]]):
+ context_key = "checkoutlines_by_checkout"
+
+ def batch_load(self, keys):
+ lines = CheckoutLine.objects.using(self.database_connection_name).filter(
+ checkout_id__in=keys
+ )
+ line_map = defaultdict(list)
+ for line in lines.iterator():
+ line_map[line.checkout_id].append(line)
+ return [line_map.get(checkout_id, []) for checkout_id in keys]
+
+
+class ChannelByCheckoutIDLoader(DataLoader):
+ context_key = "channel_by_checkout"
+
+ def batch_load(self, keys):
+ def with_checkouts(checkouts):
+ def with_channels(channels):
+ channel_map = {channel.id: channel for channel in channels}
+ return [
+ channel_map.get(checkout.channel_id) if checkout else None
+ for checkout in checkouts
+ ]
+
+ channel_ids = set(checkout.channel_id for checkout in checkouts if checkout)
+ return (
+ ChannelByIdLoader(self.context)
+ .load_many(channel_ids)
+ .then(with_channels)
+ )
+
+ return CheckoutByTokenLoader(self.context).load_many(keys).then(with_checkouts)
+
+
+class CheckoutMetadataByCheckoutIdLoader(DataLoader[str, CheckoutMetadata]):
+ context_key = "checkout_metadata_by_checkout_id"
+
+ def batch_load(self, keys):
+ checkout_metadata = CheckoutMetadata.objects.using(
+ self.database_connection_name
+ ).in_bulk(keys, field_name="checkout_id")
+ return [checkout_metadata.get(checkout_id) for checkout_id in keys]
+
+
+class TransactionItemsByCheckoutIDLoader(DataLoader[str, list[TransactionItem]]):
+ context_key = "transaction_items_by_checkout_id"
+
+ def batch_load(self, keys):
+ transactions = (
+ TransactionItem.objects.using(self.database_connection_name)
+ .filter(checkout_id__in=keys)
+ .order_by("pk")
+ )
+ transactions_map = defaultdict(list)
+ for transaction in transactions:
+ transactions_map[transaction.checkout_id].append(transaction)
+ return [transactions_map[checkout_id] for checkout_id in keys]
diff --git a/saleor/graphql/checkout/dataloaders/problems.py b/saleor/graphql/checkout/dataloaders/problems.py
new file mode 100644
index 0000000000..7c5b11cfeb
--- /dev/null
+++ b/saleor/graphql/checkout/dataloaders/problems.py
@@ -0,0 +1,163 @@
+from collections import defaultdict
+from collections.abc import Iterable
+
+from promise import Promise
+
+from ....checkout.problems import (
+ CHANNEL_SLUG,
+ CHECKOUT_LINE_PROBLEM_TYPE,
+ CHECKOUT_PROBLEM_TYPE,
+ COUNTRY_CODE,
+ PRODUCT_ID,
+ VARIANT_ID,
+ get_checkout_lines_problems,
+ get_checkout_problems,
+)
+from ....product.models import ProductChannelListing
+from ....warehouse.models import Stock
+from ...core.dataloaders import DataLoader
+from ...product.dataloaders import (
+ ProductChannelListingByProductIdAndChannelSlugLoader,
+)
+from ...warehouse.dataloaders import (
+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,
+)
+from .checkout_infos import (
+ CheckoutInfoByCheckoutTokenLoader,
+ CheckoutLinesInfoByCheckoutTokenLoader,
+)
+
+
+class CheckoutLinesProblemsByCheckoutIdLoader(
+ DataLoader[str, dict[str, list[CHECKOUT_LINE_PROBLEM_TYPE]]]
+):
+ context_key = "checkout_lines_problems_by_checkout_id"
+
+ def batch_load(self, keys):
+ stock_dataloader = (
+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
+ self.context
+ )
+ )
+
+ def _resolve_problems(data):
+ checkout_infos, checkout_lines = data
+ variant_data_set: set[
+ tuple[
+ VARIANT_ID,
+ CHANNEL_SLUG,
+ COUNTRY_CODE,
+ ]
+ ] = set()
+ product_data_set: set[
+ tuple[
+ PRODUCT_ID,
+ CHANNEL_SLUG,
+ ]
+ ] = set()
+ checkout_infos_map = {
+ checkout_info.checkout.pk: checkout_info
+ for checkout_info in checkout_infos
+ }
+ for lines in checkout_lines:
+ for line in lines:
+ variant_data_set.add(
+ (
+ line.variant.id,
+ line.channel.slug,
+ checkout_infos_map[line.line.checkout_id].checkout.country,
+ )
+ )
+ product_data_set.add(
+ (
+ line.product.id,
+ line.channel.slug,
+ )
+ )
+ variant_data_list = list(variant_data_set)
+ product_data_list = list(product_data_set)
+
+ def _prepare_problems(data):
+ (
+ variant_stocks,
+ product_channel_listings,
+ ) = data
+ variant_stock_map: dict[
+ tuple[
+ VARIANT_ID,
+ CHANNEL_SLUG,
+ COUNTRY_CODE,
+ ],
+ Iterable[Stock],
+ ] = dict(zip(variant_data_list, variant_stocks))
+ product_channel_listings_map: dict[
+ tuple[
+ PRODUCT_ID,
+ CHANNEL_SLUG,
+ ],
+ ProductChannelListing,
+ ] = dict(zip(product_data_set, product_channel_listings))
+
+ problems = {}
+
+ for checkout_info, lines in zip(checkout_infos, checkout_lines):
+ checkout_id = checkout_info.checkout.pk
+ problems[checkout_id] = get_checkout_lines_problems(
+ checkout_info,
+ lines,
+ variant_stock_map,
+ product_channel_listings_map,
+ )
+ return [problems.get(key, []) for key in keys]
+
+ variant_stocks = stock_dataloader.load_many(
+ [
+ (variant_id, country_code, channel_slug)
+ for variant_id, channel_slug, country_code in variant_data_list
+ ]
+ )
+ product_channel_listings = (
+ ProductChannelListingByProductIdAndChannelSlugLoader(
+ self.context
+ ).load_many(
+ [
+ (
+ product_id,
+ channel_slug,
+ )
+ for product_id, channel_slug in product_data_list
+ ]
+ )
+ )
+
+ return Promise.all([variant_stocks, product_channel_listings]).then(
+ _prepare_problems
+ )
+
+ checkout_infos = CheckoutInfoByCheckoutTokenLoader(self.context).load_many(keys)
+ lines = CheckoutLinesInfoByCheckoutTokenLoader(self.context).load_many(keys)
+ return Promise.all([checkout_infos, lines]).then(_resolve_problems)
+
+
+class CheckoutProblemsByCheckoutIdDataloader(
+ DataLoader[str, dict[str, list[CHECKOUT_PROBLEM_TYPE]]]
+):
+ context_key = "checkout_problems_by_checkout_id"
+
+ def batch_load(self, keys):
+ line_problems_dataloader = CheckoutLinesProblemsByCheckoutIdLoader(self.context)
+
+ def _resolve_problems(
+ checkouts_lines_problems: list[dict[str, list[CHECKOUT_LINE_PROBLEM_TYPE]]],
+ ):
+ checkout_problems = defaultdict(list)
+ for checkout_pk, checkout_lines_problems in zip(
+ keys, checkouts_lines_problems
+ ):
+ checkout_problems[checkout_pk] = get_checkout_problems(
+ checkout_lines_problems
+ )
+
+ return [checkout_problems.get(key, []) for key in keys]
+
+ return line_problems_dataloader.load_many(keys).then(_resolve_problems)
diff --git a/saleor/graphql/checkout/dataloaders/promotion_rule_infos.py b/saleor/graphql/checkout/dataloaders/promotion_rule_infos.py
new file mode 100644
index 0000000000..5f7c660bf0
--- /dev/null
+++ b/saleor/graphql/checkout/dataloaders/promotion_rule_infos.py
@@ -0,0 +1,174 @@
+from collections import defaultdict
+
+from promise import Promise
+
+from ....discount.interface import VariantPromotionRuleInfo
+from ...core.dataloaders import DataLoader
+from ...discount.dataloaders import (
+ PromotionByRuleIdLoader,
+ PromotionRuleByIdLoader,
+)
+from ...product.dataloaders import (
+ VariantChannelListingByVariantIdAndChannelIdLoader,
+ VariantChannelListingPromotionRuleByListingIdLoader,
+)
+from ...translations.dataloaders import (
+ PromotionRuleTranslationByIdAndLanguageCodeLoader,
+ PromotionTranslationByIdAndLanguageCodeLoader,
+)
+from .models import CheckoutByTokenLoader, CheckoutLineByIdLoader
+
+
+class VariantPromotionRuleInfoByCheckoutLineIdLoader(DataLoader):
+ context_key = "variant_promotion_rule_info_by_checkout_line_id"
+
+ def batch_load(self, keys):
+ def with_checkout_lines(checkout_lines):
+ def with_checkouts(checkouts):
+ variants_pks = [line.variant_id for line in checkout_lines]
+ if not variants_pks:
+ return []
+
+ channel_pks = [checkout.channel_id for checkout in checkouts]
+
+ def with_channel_listings(channel_listings):
+ def with_channel_listing_promotion_rules(
+ variant_listing_promotion_rules,
+ ):
+ rule_ids: list[int] = []
+ rule_ids_language_codes: list[tuple[int, str]] = []
+ for listing_promotion_rules, language_code in zip(
+ variant_listing_promotion_rules, language_codes
+ ):
+ for listing_promotion_rule in listing_promotion_rules:
+ rule_ids.append(
+ listing_promotion_rule.promotion_rule_id
+ )
+ rule_ids_language_codes.append(
+ (
+ listing_promotion_rule.promotion_rule_id,
+ language_code,
+ )
+ )
+
+ def with_promotion_rules(results):
+ promotion_rules, promotions, rule_translations = results
+
+ promotion_ids_language_codes = [
+ (rule.promotion_id, language_code)
+ for rule, (_rule_id, language_code) in zip(
+ promotion_rules, rule_ids_language_codes
+ )
+ ]
+
+ def with_promotion_translations(promotion_translations):
+ channel_listings_map = dict(
+ zip(variant_ids_channel_ids, channel_listings)
+ )
+ listing_promotion_rules_map = dict(
+ zip(
+ channel_listing_ids,
+ variant_listing_promotion_rules,
+ )
+ )
+ rule_map = dict(zip(rule_ids, promotion_rules))
+ rule_id_to_promotion_map = dict(
+ zip(rule_ids, promotions)
+ )
+ rule_id_to_rule_translation = dict(
+ zip(rule_ids, rule_translations)
+ )
+ rule_id_to_promotion_translation = dict(
+ zip(rule_ids, promotion_translations)
+ )
+
+ rules_info_map = defaultdict(list)
+ for checkout, line in zip(checkouts, checkout_lines):
+ channel_listing = channel_listings_map[
+ (line.variant_id, checkout.channel_id)
+ ]
+ listing_promotion_rules = (
+ listing_promotion_rules_map[channel_listing.id]
+ if channel_listing
+ else []
+ )
+ rules_info_map[line.id] = [
+ VariantPromotionRuleInfo(
+ rule=rule_map[
+ listing_rule.promotion_rule_id
+ ],
+ variant_listing_promotion_rule=listing_rule,
+ promotion=rule_id_to_promotion_map[
+ listing_rule.promotion_rule_id
+ ],
+ rule_translation=rule_id_to_rule_translation[
+ listing_rule.promotion_rule_id
+ ],
+ promotion_translation=rule_id_to_promotion_translation[
+ listing_rule.promotion_rule_id
+ ],
+ )
+ for listing_rule in listing_promotion_rules
+ ]
+
+ return [rules_info_map[key] for key in keys]
+
+ return (
+ PromotionTranslationByIdAndLanguageCodeLoader(
+ self.context
+ )
+ .load_many(promotion_ids_language_codes)
+ .then(with_promotion_translations)
+ )
+
+ promotion_rules = PromotionRuleByIdLoader(
+ self.context
+ ).load_many(rule_ids)
+ promotions = PromotionByRuleIdLoader(self.context).load_many(
+ rule_ids
+ )
+
+ rules_translations = (
+ PromotionRuleTranslationByIdAndLanguageCodeLoader(
+ self.context
+ ).load_many(rule_ids_language_codes)
+ )
+ return Promise.all(
+ [promotion_rules, promotions, rules_translations]
+ ).then(with_promotion_rules)
+
+ channel_listing_ids = [
+ listing.id for listing in channel_listings if listing
+ ]
+ return (
+ VariantChannelListingPromotionRuleByListingIdLoader(
+ self.context
+ )
+ .load_many(channel_listing_ids)
+ .then(with_channel_listing_promotion_rules)
+ )
+
+ variant_ids_channel_ids = [
+ (line.variant_id, channel_id)
+ for line, channel_id in zip(checkout_lines, channel_pks)
+ ]
+ language_codes = [checkout.language_code for checkout in checkouts]
+
+ return (
+ VariantChannelListingByVariantIdAndChannelIdLoader(self.context)
+ .load_many(variant_ids_channel_ids)
+ .then(with_channel_listings)
+ )
+
+ checkout_tokens = [line.checkout_id for line in checkout_lines]
+ return (
+ CheckoutByTokenLoader(self.context)
+ .load_many(checkout_tokens)
+ .then(with_checkouts)
+ )
+
+ return (
+ CheckoutLineByIdLoader(self.context)
+ .load_many(keys)
+ .then(with_checkout_lines)
+ )
diff --git a/saleor/graphql/webhook/dataloaders/__init__.py b/saleor/graphql/webhook/dataloaders/__init__.py
new file mode 100644
index 0000000000..6bc545f027
--- /dev/null
+++ b/saleor/graphql/webhook/dataloaders/__init__.py
@@ -0,0 +1,15 @@
+from .models import (
+ PayloadByIdLoader,
+ WebhookEventsByWebhookIdLoader,
+ WebhooksByAppIdLoader,
+)
+from .pregenerated_payload_for_checkout_tax import (
+ PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader,
+)
+
+__all__ = [
+ "PayloadByIdLoader",
+ "PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader",
+ "WebhookEventsByWebhookIdLoader",
+ "WebhooksByAppIdLoader",
+]
diff --git a/saleor/graphql/webhook/dataloaders/models.py b/saleor/graphql/webhook/dataloaders/models.py
new file mode 100644
index 0000000000..759ff19ff8
--- /dev/null
+++ b/saleor/graphql/webhook/dataloaders/models.py
@@ -0,0 +1,47 @@
+from collections import defaultdict
+
+from ....core.models import EventPayload
+from ....webhook.models import Webhook, WebhookEvent
+from ...core.dataloaders import DataLoader
+
+
+class PayloadByIdLoader(DataLoader[str, str]):
+ context_key = "payload_by_id"
+
+ def batch_load(self, keys):
+ payloads = EventPayload.objects.using(self.database_connection_name).in_bulk(
+ keys
+ )
+
+ return [
+ payloads[payload_id].get_payload() if payloads.get(payload_id) else None
+ for payload_id in keys
+ ]
+
+
+class WebhookEventsByWebhookIdLoader(DataLoader):
+ context_key = "webhook_events_by_webhook_id"
+
+ def batch_load(self, keys):
+ webhook_events = WebhookEvent.objects.using(
+ self.database_connection_name
+ ).filter(webhook_id__in=keys)
+
+ webhook_events_map = defaultdict(list)
+ for event in webhook_events:
+ webhook_events_map[event.webhook_id].append(event)
+
+ return [webhook_events_map.get(webhook_id, []) for webhook_id in keys]
+
+
+class WebhooksByAppIdLoader(DataLoader):
+ context_key = "webhooks_by_app_id"
+
+ def batch_load(self, keys):
+ webhooks = Webhook.objects.using(self.database_connection_name).filter(
+ app_id__in=keys
+ )
+ webhooks_by_app_map = defaultdict(list)
+ 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]
diff --git a/saleor/graphql/webhook/dataloaders.py b/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py
similarity index 70%
rename from saleor/graphql/webhook/dataloaders.py
rename to saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py
index 9ef0a291cd..cb05bcd590 100644
--- a/saleor/graphql/webhook/dataloaders.py
+++ b/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py
@@ -4,71 +4,27 @@ from typing import Any
from django.utils import timezone
from promise import Promise
-from ...core.db.connection import allow_writer_in_context
-from ...core.models import EventPayload
-from ...tax import TaxCalculationStrategy
-from ...tax.utils import (
+from ....core.db.connection import allow_writer_in_context
+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 (
+from ....webhook.event_types import WebhookEventSyncType
+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 (
+from ...core.dataloaders import DataLoader
+from ...utils import get_user_or_app_from_context
+from ..subscription_payload import (
generate_payload_promise_from_subscription,
initialize_request,
)
-from .utils import get_subscription_query_hash
-
-
-class PayloadByIdLoader(DataLoader[str, str]):
- context_key = "payload_by_id"
-
- def batch_load(self, keys):
- payloads = EventPayload.objects.using(self.database_connection_name).in_bulk(
- keys
- )
-
- return [
- payloads[payload_id].get_payload() if payloads.get(payload_id) else None
- for payload_id in keys
- ]
-
-
-class WebhookEventsByWebhookIdLoader(DataLoader):
- context_key = "webhook_events_by_webhook_id"
-
- def batch_load(self, keys):
- webhook_events = WebhookEvent.objects.using(
- self.database_connection_name
- ).filter(webhook_id__in=keys)
-
- webhook_events_map = defaultdict(list)
- for event in webhook_events:
- webhook_events_map[event.webhook_id].append(event)
-
- return [webhook_events_map.get(webhook_id, []) for webhook_id in keys]
-
-
-class WebhooksByAppIdLoader(DataLoader):
- context_key = "webhooks_by_app_id"
-
- def batch_load(self, keys):
- webhooks = Webhook.objects.using(self.database_connection_name).filter(
- app_id__in=keys
- )
- webhooks_by_app_map = defaultdict(list)
- 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]
+from ..utils import get_subscription_query_hash
class PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(DataLoader):
@@ -141,7 +97,7 @@ class PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(DataLoader):
webhook.subscription_query
)
checkout = checkout_info.checkout
- checkout_token = str(checkout.pk)
+ checkout_token = str(checkout.token)
promise_payload = (
generate_payload_promise_from_subscription(