Skip to content

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

Change the GraphQL API files structure

Marcin Gębalaf6e6c127f46f
diff --git a/saleor/checkout/templatetags/__init__.py b/saleor/checkout/templatetags/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/checkout/templatetags/checkout.py b/saleor/checkout/templatetags/checkout.py
new file mode 100644
index 0000000000..7d63da2992
--- /dev/null
+++ b/saleor/checkout/templatetags/checkout.py
@@ -0,0 +1,17 @@
+from django.template import Library
+
+from ..utils import get_deliveries, get_total
+
+
+register = Library()
+
+
+def get_checkout_deliveries(checkout):
+ return get_deliveries(checkout.cart, checkout.shipping_method)
+
+
+def get_checkout_total(checkout):
+ return get_total(
+ checkout.cart, checkout.shipping_method, checkout.discount)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
new file mode 100644
index 0000000000..cb5abb8941
--- /dev/null
+++ b/saleor/checkout/utils.py
@@ -0,0 +1,49 @@
+from django.conf import settings
+from prices import Price
+
+
+def get_deliveries(cart, shipping_method=None):
+ """Return the cart split into shipment groups.
+
+ Generates tuples consisting of a partition, its shipping cost and its
+ total cost.
+
+ Each partition is a list of tuples containing the cart line, its unit
+ price and the line total.
+ """
+ for partition in cart.partition():
+ if shipping_method and partition.is_shipping_required():
+ shipping_cost = shipping_method.get_total()
+ else:
+ shipping_cost = Price(0, currency=settings.DEFAULT_CURRENCY)
+ total_with_shipping = partition.get_total(
+ discounts=cart.discounts) + shipping_cost
+
+ partition = [
+ (
+ line,
+ line.get_price_per_item(discounts=cart.discounts),
+ line.get_total(discounts=cart.discounts))
+ for line in partition]
+ yield partition, shipping_cost, total_with_shipping
+
+
+def get_subtotal(cart, shipping_method):
+ """Calculate order total without shipping."""
+ deliveries = get_deliveries(cart, shipping_method)
+ zero = Price(0, currency=settings.DEFAULT_CURRENCY)
+ cost_iterator = (
+ total - shipping_cost
+ for shipment, shipping_cost, total in deliveries)
+ total = sum(cost_iterator, zero)
+ return total
+
+
+def get_total(cart, shipping_method, discount=None):
+ """Calculate order total with shipping."""
+ deliveries = get_deliveries(cart, shipping_method)
+ zero = Price(0, currency=settings.DEFAULT_CURRENCY)
+ cost_iterator = (
+ total for shipment, shipping_cost, total in deliveries)
+ total = sum(cost_iterator, zero)
+ return total if discount is None else discount.apply(total)
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index fc0fb275aa..ba502ae1b9 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -1,244 +1,10 @@
-import functools
-import operator
-
-from django.db.models import Q
-from django_prices.templatetags import prices_i18n
import graphene
from graphene import relay
-from graphene_django import DjangoConnectionField, DjangoObjectType
+from graphene_django import DjangoConnectionField
from graphene_django.debug import DjangoDebug
-from ..product.models import (
- AttributeChoiceValue, Category, Product, ProductAttribute, ProductImage,
- ProductVariant)
-from ..product.templatetags.product_images import product_first_image
-from ..product.utils import get_availability, products_visible_to_user
-from .scalars import AttributesFilterScalar
-from .utils import CategoryAncestorsCache, DjangoPkInterface
-
-CONTEXT_CACHE_NAME = '__cache__'
-CACHE_ANCESTORS = 'ancestors'
-
-
-def get_ancestors_from_cache(category, context):
- cache = getattr(context, CONTEXT_CACHE_NAME, None)
- if cache and CACHE_ANCESTORS in cache:
- return cache[CACHE_ANCESTORS].get(category)
- else:
- return category.get_ancestors()
-
-
-class ProductAvailabilityType(graphene.ObjectType):
- available = graphene.Boolean()
- discount = graphene.Field(lambda: PriceType)
- discount_local_currency = graphene.Field(lambda: PriceType)
- price_range = graphene.Field(lambda: PriceRangeType)
- price_range_undiscounted = graphene.Field(lambda: PriceRangeType)
- price_range_local_currency = graphene.Field(lambda: PriceRangeType)
-
-
-class ProductType(DjangoObjectType):
- url = graphene.String()
- thumbnail_url = graphene.String(
- size=graphene.Argument(
- graphene.String,
- description="The size of a thumbnail, for example 255x255"))
- images = graphene.List(lambda: ProductImageType)
- variants = graphene.List(lambda: ProductVariantType)
- availability = graphene.Field(lambda: ProductAvailabilityType)
- price = graphene.Field(lambda: PriceType)
-
- class Meta:
- model = Product
- interfaces = (relay.Node, DjangoPkInterface)
-
- def resolve_thumbnail_url(self, info, **args):
- size = args.get('size')
- if not size:
- size = '255x255'
- return product_first_image(self, size)
-
- def resolve_images(self, info):
- return self.images.all()
-
- def resolve_variants(self, info):
- return self.variants.all()
-
- def resolve_url(self, info):
- return self.get_absolute_url()
-
- def resolve_availability(self, info):
- context = info.context
- a = get_availability(self, context.discounts, context.currency)
- return ProductAvailabilityType(**a._asdict())
-
-
-class CategoryType(DjangoObjectType):
- products = DjangoConnectionField(
- ProductType,
- attributes=graphene.Argument(
- graphene.List(AttributesFilterScalar),
- description="""A list of attribute:value pairs to filter
- the products by"""),
- order_by=graphene.Argument(
- graphene.String,
- description="""A name of field to sort the products by. The negative
- sign in front of name implies descending order."""),
- price_lte=graphene.Argument(
- graphene.Float, description="""Get the products with price lower
- than or equal to the given value"""),
- price_gte=graphene.Argument(
- graphene.Float, description="""Get the products with price greater
- than or equal to the given value"""))
- products_count = graphene.Int()
- url = graphene.String()
- ancestors = graphene.List(lambda: CategoryType)
- children = graphene.List(lambda: CategoryType)
- siblings = graphene.List(lambda: CategoryType)
-
- class Meta:
- model = Category
- interfaces = (relay.Node, DjangoPkInterface)
-
- def resolve_ancestors(self, info):
- return get_ancestors_from_cache(self, info.context)
-
- def resolve_children(self, info):
- return self.children.all()
-
- def resolve_siblings(self, info):
- return self.get_siblings()
-
- def resolve_products_count(self, info):
- return self.products.count()
-
- def resolve_url(self, info):
- ancestors = get_ancestors_from_cache(self, info.context)
- return self.get_absolute_url(ancestors)
-
- def resolve_products(self, info, **args):
- context = info.context
- qs = products_visible_to_user(context.user)
- qs = qs.prefetch_related('images', 'category', 'variants__stock')
- qs = qs.filter(category=self)
-
- attributes_filter, order_by, price_lte, price_gte = map(
- args.get, ['attributes', 'order_by', 'price_lte', 'price_gte'])
-
- if attributes_filter:
- attributes = ProductAttribute.objects.prefetch_related('values')
- attributes_map = {attribute.slug: attribute.pk
- for attribute in attributes}
- values_map = {attr.slug: {value.slug: value.pk
- for value in attr.values.all()}
- for attr in attributes}
- queries = {}
- # Convert attribute:value pairs into a dictionary where
- # attributes are keys and values are grouped in lists
- for attr_name, val_slug in attributes_filter:
- try:
- attr_pk = attributes_map[attr_name]
- except KeyError:
- attr_pk = None
- else:
- try:
- attr_val_pk = values_map[attr_name][val_slug]
- except KeyError:
- attr_val_pk = None
- else:
- if attr_val_pk is not None and attr_pk not in queries:
- queries[attr_pk] = [attr_val_pk]
- else:
- queries[attr_pk].append(attr_val_pk)
- if queries:
- # Combine filters of the same attribute with OR operator
- # and then combine full query with AND operator.
- combine_and = [functools.reduce(operator.or_, [
- Q(**{'variants__attributes__%s' % key: v}) |
- Q(**{'attributes__%s' % key: v})
- for v in values]) for key, values in queries.items()]
- query = functools.reduce(operator.and_, combine_and)
- qs = qs.filter(query).distinct()
-
- if order_by:
- qs = qs.order_by(order_by)
-
- def filter_by_price(queryset, value, operator):
- return [
- obj for obj in queryset
- if operator(
- get_availability(obj, context.discounts)
- .price_range.min_price.gross, value)
- ]
-
- if price_lte:
- qs = filter_by_price(qs, price_lte, operator.le)
-
- if price_gte:
- qs = filter_by_price(qs, price_gte, operator.ge)
- return qs
-
-
-class ProductVariantType(DjangoObjectType):
- stock_quantity = graphene.Int()
- price_override = graphene.Field(lambda: PriceType)
-
- class Meta:
- model = ProductVariant
- interfaces = (relay.Node, DjangoPkInterface)
-
- def resolve_stock_quantity(self, info):
- return self.get_stock_quantity()
-
-
-class ProductImageType(DjangoObjectType):
- url = graphene.String(size=graphene.String())
-
- class Meta:
- model = ProductImage
- interfaces = (relay.Node, DjangoPkInterface)
-
- def resolve_url(self, info, **args):
- size = args.get('size')
- if size:
- return self.image.crop[size].url
- return self.image.url
-
-
-class ProductAttributeValue(DjangoObjectType):
- class Meta:
- model = AttributeChoiceValue
- interfaces = (relay.Node, DjangoPkInterface)
-
-
-class ProductAttributeType(DjangoObjectType):
- values = graphene.List(lambda: ProductAttributeValue)
-
- class Meta:
- model = ProductAttribute
- interfaces = (relay.Node, DjangoPkInterface)
-
- def resolve_values(self, info):
- return self.values.all()
-
-
-class PriceType(graphene.ObjectType):
- currency = graphene.String()
- gross = graphene.Float()
- gross_localized = graphene.String()
- net = graphene.Float()
- net_localized = graphene.String()
-
- def resolve_gross_localized(self, info):
- return prices_i18n.gross(self)
-
- def resolve_net_localized(self, info):
- return prices_i18n.net(self)
-
-
-class PriceRangeType(graphene.ObjectType):
- max_price = graphene.Field(lambda: PriceType)
- min_price = graphene.Field(lambda: PriceType)
+from .product.types import (
+ resolve_category, resolve_attributes, CategoryType, ProductAttributeType)
class Query(graphene.ObjectType):
@@ -254,29 +20,11 @@ class Query(graphene.ObjectType):
def resolve_category(self, info, **args):
pk = args.get('pk')
- categories = Category.tree.filter(pk=pk).get_cached_trees()
- if categories:
- category = categories[0]
- cache = {CACHE_ANCESTORS: CategoryAncestorsCache(category)}
- setattr(info.context, CONTEXT_CACHE_NAME, cache)
- return category
- return None
+ return resolve_category(pk, info)
def resolve_attributes(self, info, **args):
category_pk = args.get('category_pk')
- queryset = ProductAttribute.objects.prefetch_related('values')
- if category_pk:
- # Get attributes that are used with product types
- # within the given category.
- tree = Category.objects.get(
- pk=category_pk).get_descendants(include_self=True)
- product_types = set(
- [obj[0] for obj in Product.objects.filter(
- category__in=tree).values_list('product_type_id')])
- queryset = queryset.filter(
- Q(product_types__in=product_types) |
- Q(product_variant_types__in=product_types))
- return queryset.distinct()
+ return resolve_attributes(category_pk)
def resolve_root(self, info):
# Re-expose the root query object. Workaround for the issue in Relay:
diff --git a/saleor/graphql/core/__init__.py b/saleor/graphql/core/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/core/types.py b/saleor/graphql/core/types.py
new file mode 100644
index 0000000000..a0e59145f3
--- /dev/null
+++ b/saleor/graphql/core/types.py
@@ -0,0 +1,21 @@
+import graphene
+from django_prices.templatetags import prices_i18n
+
+
+class PriceType(graphene.ObjectType):
+ currency = graphene.String()
+ gross = graphene.Float()
+ gross_localized = graphene.String()
+ net = graphene.Float()
+ net_localized = graphene.String()
+
+ def resolve_gross_localized(self, info):
+ return prices_i18n.gross(self)
+
+ def resolve_net_localized(self, info):
+ return prices_i18n.net(self)
+
+
+class PriceRangeType(graphene.ObjectType):
+ max_price = graphene.Field(lambda: PriceType)
+ min_price = graphene.Field(lambda: PriceType)
diff --git a/saleor/graphql/product/__init__.py b/saleor/graphql/product/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/scalars.py b/saleor/graphql/product/scalars.py
similarity index 100%
rename from saleor/graphql/scalars.py
rename to saleor/graphql/product/scalars.py
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
new file mode 100644
index 0000000000..17e2d8b2c3
--- /dev/null
+++ b/saleor/graphql/product/types.py
@@ -0,0 +1,248 @@
+import functools
+import operator
+
+from django.db.models import Q
+import graphene
+from graphene import relay
+from graphene_django import DjangoConnectionField, DjangoObjectType
+
+from ...product.models import (
+ AttributeChoiceValue, Category, Product, ProductAttribute, ProductImage,
+ ProductVariant)
+from ...product.templatetags.product_images import product_first_image
+from ...product.utils import get_availability, products_visible_to_user
+from ..utils import CategoryAncestorsCache, DjangoPkInterface
+from ..core.types import PriceRangeType, PriceType
+from .scalars import AttributesFilterScalar
+
+
+CONTEXT_CACHE_NAME = '__cache__'
+CACHE_ANCESTORS = 'ancestors'
+
+
+def get_ancestors_from_cache(category, context):
+ cache = getattr(context, CONTEXT_CACHE_NAME, None)
+ if cache and CACHE_ANCESTORS in cache:
+ return cache[CACHE_ANCESTORS].get(category)
+ else:
+ return category.get_ancestors()
+
+
+class ProductAvailabilityType(graphene.ObjectType):
+ available = graphene.Boolean()
+ discount = graphene.Field(lambda: PriceType)
+ discount_local_currency = graphene.Field(lambda: PriceType)
+ price_range = graphene.Field(lambda: PriceRangeType)
+ price_range_undiscounted = graphene.Field(lambda: PriceRangeType)
+ price_range_local_currency = graphene.Field(lambda: PriceRangeType)
+
+
+class ProductType(DjangoObjectType):
+ url = graphene.String()
+ thumbnail_url = graphene.String(
+ size=graphene.Argument(
+ graphene.String,
+ description="The size of a thumbnail, for example 255x255"))
+ images = graphene.List(lambda: ProductImageType)
+ variants = graphene.List(lambda: ProductVariantType)
+ availability = graphene.Field(lambda: ProductAvailabilityType)
+ price = graphene.Field(lambda: PriceType)
+
+ class Meta:
+ model = Product
+ interfaces = (relay.Node, DjangoPkInterface)
+
+ def resolve_thumbnail_url(self, info, **args):
+ size = args.get('size')
+ if not size:
+ size = '255x255'
+ return product_first_image(self, size)
+
+ def resolve_images(self, info):
+ return self.images.all()
+
+ def resolve_variants(self, info):
+ return self.variants.all()
+
+ def resolve_url(self, info):
+ return self.get_absolute_url()
+
+ def resolve_availability(self, info):
+ context = info.context
+ a = get_availability(self, context.discounts, context.currency)
+ return ProductAvailabilityType(**a._asdict())
+
+
+class CategoryType(DjangoObjectType):
+ products = DjangoConnectionField(
+ ProductType,
+ attributes=graphene.Argument(
+ graphene.List(AttributesFilterScalar),
+ description="""A list of attribute:value pairs to filter
+ the products by"""),
+ order_by=graphene.Argument(
+ graphene.String,
+ description="""A name of field to sort the products by. The negative
+ sign in front of name implies descending order."""),
+ price_lte=graphene.Argument(
+ graphene.Float, description="""Get the products with price lower
+ than or equal to the given value"""),
+ price_gte=graphene.Argument(
+ graphene.Float, description="""Get the products with price greater
+ than or equal to the given value"""))
+ products_count = graphene.Int()
+ url = graphene.String()
+ ancestors = graphene.List(lambda: CategoryType)
+ children = graphene.List(lambda: CategoryType)
+ siblings = graphene.List(lambda: CategoryType)
+
+ class Meta:
+ model = Category
+ interfaces = (relay.Node, DjangoPkInterface)
+
+ def resolve_ancestors(self, info):
+ return get_ancestors_from_cache(self, info.context)
+
+ def resolve_children(self, info):
+ return self.children.all()
+
+ def resolve_siblings(self, info):
+ return self.get_siblings()
+
+ def resolve_products_count(self, info):
+ return self.products.count()
+
+ def resolve_url(self, info):
+ ancestors = get_ancestors_from_cache(self, info.context)
+ return self.get_absolute_url(ancestors)
+
+ def resolve_products(self, info, **args):
+ context = info.context
+ qs = products_visible_to_user(context.user)
+ qs = qs.prefetch_related('images', 'category', 'variants__stock')
+ qs = qs.filter(category=self)
+
+ attributes_filter, order_by, price_lte, price_gte = map(
+ args.get, ['attributes', 'order_by', 'price_lte', 'price_gte'])
+
+ if attributes_filter:
+ attributes = ProductAttribute.objects.prefetch_related('values')
+ attributes_map = {attribute.slug: attribute.pk
+ for attribute in attributes}
+ values_map = {attr.slug: {value.slug: value.pk
+ for value in attr.values.all()}
+ for attr in attributes}
+ queries = {}
+ # Convert attribute:value pairs into a dictionary where
+ # attributes are keys and values are grouped in lists
+ for attr_name, val_slug in attributes_filter:
+ try:
+ attr_pk = attributes_map[attr_name]
+ except KeyError:
+ attr_pk = None
+ else:
+ try:
+ attr_val_pk = values_map[attr_name][val_slug]
+ except KeyError:
+ attr_val_pk = None
+ else:
+ if attr_val_pk is not None and attr_pk not in queries:
+ queries[attr_pk] = [attr_val_pk]
+ else:
+ queries[attr_pk].append(attr_val_pk)
+ if queries:
+ # Combine filters of the same attribute with OR operator
+ # and then combine full query with AND operator.
+ combine_and = [functools.reduce(operator.or_, [
+ Q(**{'variants__attributes__%s' % key: v}) |
+ Q(**{'attributes__%s' % key: v})
+ for v in values]) for key, values in queries.items()]
+ query = functools.reduce(operator.and_, combine_and)
+ qs = qs.filter(query).distinct()
+
+ if order_by:
+ qs = qs.order_by(order_by)
+
+ def filter_by_price(queryset, value, operator):
+ return [
+ obj for obj in queryset
+ if operator(
+ get_availability(obj, context.discounts)
+ .price_range.min_price.gross, value)
+ ]
+
+ if price_lte:
+ qs = filter_by_price(qs, price_lte, operator.le)
+
+ if price_gte:
+ qs = filter_by_price(qs, price_gte, operator.ge)
+ return qs
+
+
+class ProductVariantType(DjangoObjectType):
+ stock_quantity = graphene.Int()
+ price_override = graphene.Field(lambda: PriceType)
+
+ class Meta:
+ model = ProductVariant
+ interfaces = (relay.Node, DjangoPkInterface)
+
+ def resolve_stock_quantity(self, info):
+ return self.get_stock_quantity()
+
+
+class ProductImageType(DjangoObjectType):
+ url = graphene.String(size=graphene.String())
+
+ class Meta:
+ model = ProductImage
+ interfaces = (relay.Node, DjangoPkInterface)
+
+ def resolve_url(self, info, **args):
+ size = args.get('size')
+ if size:
+ return self.image.crop[size].url
+ return self.image.url
+
+
+class ProductAttributeValue(DjangoObjectType):
+ class Meta:
+ model = AttributeChoiceValue
+ interfaces = (relay.Node, DjangoPkInterface)
+
+
+class ProductAttributeType(DjangoObjectType):
+ values = graphene.List(lambda: ProductAttributeValue)
+
+ class Meta:
+ model = ProductAttribute
+ interfaces = (relay.Node, DjangoPkInterface)
+
+ def resolve_values(self, info):
+ return self.values.all()
+
+
+def resolve_category(pk, info):
+ categories = Category.tree.filter(pk=pk).get_cached_trees()
+ if categories:
+ category = categories[0]
+ cache = {CACHE_ANCESTORS: CategoryAncestorsCache(category)}
+ setattr(info.context, CONTEXT_CACHE_NAME, cache)
+ return category
+ return None
+
+
+def resolve_attributes(category_pk):
+ queryset = ProductAttribute.objects.prefetch_related('values')
+ if category_pk:
+ # Get attributes that are used with product types
+ # within the given category.
+ tree = Category.objects.get(
+ pk=category_pk).get_descendants(include_self=True)
+ product_types = set(
+ [obj[0] for obj in Product.objects.filter(
+ category__in=tree).values_list('product_type_id')])
+ queryset = queryset.filter(
+ Q(product_types__in=product_types) |
+ Q(product_variant_types__in=product_types))
+ return queryset.distinct()