Skip to content

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

Models and mutations for sortable collections products

NyanKiyoshi5e925107ed7d
diff --git a/saleor/core/models.py b/saleor/core/models.py
index b53e72eb0a..c499e21bb5 100644
--- a/saleor/core/models.py
+++ b/saleor/core/models.py
@@ -4,29 +4,62 @@ from django.db import models
from django.db.models import F, Max, Q
-class SortableModel(models.Model):
- sort_order = models.PositiveIntegerField(editable=False, db_index=True)
-
+class _BaseSortableModel(models.Model):
class Meta:
abstract = True
def get_ordering_queryset(self):
raise NotImplementedError("Unknown ordering queryset")
+ @property
+ def _sort_order_field_name(self):
+ return "sort_order"
+
+ @property
+ def _sort_order(self):
+ return getattr(self, self._sort_order_field_name)
+
+ @_sort_order.setter
+ def _sort_order(self, value):
+ setattr(self, self._sort_order_field_name, value)
+
+ def _get_max_sort_order(self, qs):
+ existing_max = qs.aggregate(Max(self._sort_order_field_name))
+ existing_max = existing_max.get(f"{self._sort_order_field_name}__max")
+ return existing_max
+
+ def get_max_sort_order(self):
+ return self._get_max_sort_order(self.get_ordering_queryset())
+
def save(self, *args, **kwargs):
- if self.sort_order is None:
+ if self._sort_order is None:
qs = self.get_ordering_queryset()
- existing_max = qs.aggregate(Max("sort_order"))
- existing_max = existing_max.get("sort_order__max")
- self.sort_order = 0 if existing_max is None else existing_max + 1
+ existing_max = self._get_max_sort_order(qs)
+ self._sort_order = 0 if existing_max is None else existing_max + 1
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
qs = self.get_ordering_queryset()
- qs.filter(sort_order__gt=self.sort_order).update(sort_order=F("sort_order") - 1)
+ qs.filter(**{f"{self._sort_order_field_name}__gt": self._sort_order}).update(
+ **{self._sort_order_field_name: F(self._sort_order_field_name) - 1}
+ )
super().delete(*args, **kwargs)
+class SortableModel(_BaseSortableModel):
+ sort_order = models.PositiveIntegerField(editable=False, db_index=True)
+
+ class Meta:
+ abstract = True
+
+
+class SortableModelNullable(_BaseSortableModel):
+ sort_order = models.PositiveIntegerField(editable=False, db_index=True, null=True)
+
+ class Meta:
+ abstract = True
+
+
class PublishedQuerySet(models.QuerySet):
def published(self):
today = datetime.date.today()
@@ -44,6 +77,13 @@ class PublishedQuerySet(models.QuerySet):
return self.all()
return self.published()
+ def collection_sorted(self, user):
+ qs = self.visible_to_user(user).prefetch_related(
+ "collections__products__collectionproduct"
+ )
+ qs = qs.order_by(F("collectionproduct__sort_order").desc(nulls_last=True))
+ return qs
+
class PublishableModel(models.Model):
publication_date = models.DateField(blank=True, null=True)
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 97a0934fdf..e122b8ec2b 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -1,3 +1,5 @@
+from typing import List, Tuple
+
import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -16,8 +18,19 @@ from ...core.enums import TaxRateType
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.scalars import Decimal, WeightScalar
from ...core.types import SeoInput, Upload
-from ...core.utils import clean_seo_fields, validate_image_file
-from ..types import Category, Collection, Product, ProductImage, ProductVariant
+from ...core.utils import (
+ clean_seo_fields,
+ from_global_id_strict_type,
+ validate_image_file,
+)
+from ..types import (
+ Category,
+ Collection,
+ MoveProductInput,
+ Product,
+ ProductImage,
+ ProductVariant,
+)
from ..utils import attributes_to_hstore
@@ -191,6 +204,75 @@ class CollectionDelete(ModelDeleteMutation):
permissions = ("product.manage_products",)
+class CollectionReorderProducts(BaseMutation):
+ collection = graphene.Field(
+ Collection, description="Collection from which products are reordered."
+ )
+
+ class Meta:
+ description = "Reorder the products of a collection"
+ permissions = ("product.manage_products",)
+
+ class Arguments:
+ collection_id = graphene.Argument(
+ graphene.ID, required=True, description="ID of a collection."
+ )
+ moves = graphene.List(
+ MoveProductInput,
+ required=True,
+ description="The collection products position operations.",
+ )
+
+ @classmethod
+ def get_operations(
+ cls, info, collection_id: int, moves: List[MoveProductInput]
+ ) -> List[Tuple[models.CollectionProduct, int]]:
+ operations = []
+ current_rel_pos = None
+
+ for move_info in moves:
+ product_id = from_global_id_strict_type(
+ info, move_info.product_id, only_type=Product, field="moves"
+ )
+
+ try:
+ node = models.CollectionProduct.objects.get(
+ product_id=product_id, collection_id=collection_id
+ )
+ except models.CollectionProduct.DoesNotExist:
+ raise ValidationError(
+ {"moves": "Couldn't resolve to a product: %s" % product_id}
+ )
+
+ if current_rel_pos is None:
+ # This case should never happen,
+ # except when products were migrated from a previous version
+ # or using unit-tests because of the usage of `bulk_create`
+ if node.sort_order is None:
+ current_rel_pos = node.get_max_sort_order() or 0
+ else:
+ current_rel_pos = node.sort_order
+ else:
+ current_rel_pos += 1
+
+ sort_position = max(0, current_rel_pos + move_info.sort_order)
+ operations.append((node, sort_position))
+
+ return operations
+
+ @classmethod
+ def perform_mutation(cls, _root, info, collection_id, moves):
+ collection = cls.get_node_or_error(
+ info, collection_id, field="collection_id", only_type=Collection
+ )
+
+ for node, new_position in cls.get_operations(info, collection.id, moves):
+ node.sort_order = new_position
+ node.save(update_fields=["sort_order"])
+
+ return CollectionReorderProducts(collection=collection)
+
+
class CollectionAddProducts(BaseMutation):
collection = graphene.Field(
Collection, description="Collection to which products will be added."
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 6204bba932..ab75ccd633 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -48,6 +48,7 @@ from .mutations.products import (
CollectionCreate,
CollectionDelete,
CollectionRemoveProducts,
+ CollectionReorderProducts,
CollectionUpdate,
ProductCreate,
ProductDelete,
@@ -278,6 +279,7 @@ class ProductMutations(graphene.ObjectType):
collection_add_products = CollectionAddProducts.Field()
collection_create = CollectionCreate.Field()
collection_delete = CollectionDelete.Field()
+ collection_reorder_products = CollectionReorderProducts.Field()
collection_bulk_delete = CollectionBulkDelete.Field()
collection_bulk_publish = CollectionBulkPublish.Field()
collection_remove_products = CollectionRemoveProducts.Field()
diff --git a/saleor/graphql/product/types/__init__.py b/saleor/graphql/product/types/__init__.py
index 0c13108754..5b4790db7a 100644
--- a/saleor/graphql/product/types/__init__.py
+++ b/saleor/graphql/product/types/__init__.py
@@ -4,6 +4,7 @@ from .digital_contents import DigitalContent, DigitalContentUrl
from .products import (
Category,
Collection,
+ MoveProductInput,
Product,
ProductImage,
ProductOrder,
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index f0447c1f36..2e33c91e73 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -50,6 +50,16 @@ def prefetch_products(info, *_args, **_kwargs):
)
+def prefetch_products_collection_sorted(info, *_args, **_kwargs):
+ user = info.context.user
+ qs = models.Product.objects.collection_sorted(user)
+ return Prefetch(
+ "products",
+ queryset=gql_optimizer.query(qs, info),
+ to_attr="prefetched_products",
+ )
+
+
def resolve_attribute_list(attributes_hstore, attributes_qs):
"""Resolve attributes dict into a list of `SelectedAttribute`s.
keys = list(attributes.keys())
@@ -588,7 +598,7 @@ class Collection(CountableDjangoObjectType):
PrefetchingConnectionField(
Product, description="List of products in this collection."
),
- prefetch_related=prefetch_products,
+ prefetch_related=prefetch_products_collection_sorted,
)
background_image = graphene.Field(
Image, size=graphene.Int(description="Size of the image")
@@ -762,3 +772,15 @@ class ProductImage(CountableDjangoObjectType):
else:
url = root.image.url
return info.context.build_absolute_uri(url)
+
+
+class MoveProductInput(graphene.InputObjectType):
+ product_id = graphene.ID(
+ description="The ID of the product to move.", required=True
+ )
+ sort_order = graphene.Int(
+ description=(
+ "The relative sorting position of the product (from -inf to +inf) "
+ "starting from the first given product's actual position."
+ )
+ )
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 8a80e652ae..71a98029c2 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -563,6 +563,11 @@ type CollectionRemoveProducts {
collection: Collection
}
+type CollectionReorderProducts {
+ errors: [Error!]
+ collection: Collection
+}
+
type CollectionTranslate {
errors: [Error!]
collection: Collection
@@ -1411,6 +1416,11 @@ type MoneyRange {
stop: Money
}
+input MoveProductInput {
+ productId: ID!
+ sortOrder: Int
+}
+
type Mutations {
authorizationKeyAdd(input: AuthorizationKeyInput!, keyType: AuthorizationKeyType!): AuthorizationKeyAdd
authorizationKeyDelete(keyType: AuthorizationKeyType!): AuthorizationKeyDelete
@@ -1446,6 +1456,7 @@ type Mutations {
collectionAddProducts(collectionId: ID!, products: [ID]!): CollectionAddProducts
collectionCreate(input: CollectionCreateInput!): CollectionCreate
collectionDelete(id: ID!): CollectionDelete
+ collectionReorderProducts(collectionId: ID!, moves: [MoveProductInput]!): CollectionReorderProducts
collectionBulkDelete(ids: [ID]!): CollectionBulkDelete
collectionBulkPublish(ids: [ID]!, isPublished: Boolean!): CollectionBulkPublish
collectionRemoveProducts(collectionId: ID!, products: [ID]!): CollectionRemoveProducts
diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.py
index b9d78d9dfb..af5e5c164f 100644
--- a/saleor/graphql/utils.py
+++ b/saleor/graphql/utils.py
@@ -62,7 +62,7 @@ def _resolve_graphene_type(type_name):
raise AssertionError("Could not resolve the type {}".format(type_name))
-def get_nodes(ids, graphene_type=None):
+def get_nodes(ids, graphene_type=None, qs=None):
"""Return a list of nodes.
If the `graphene_type` argument is provided, the IDs will be validated
@@ -78,7 +78,10 @@ def get_nodes(ids, graphene_type=None):
if nodes_type and not graphene_type:
graphene_type = _resolve_graphene_type(nodes_type)
- nodes = list(graphene_type._meta.model.objects.filter(pk__in=pks))
+ if qs is None:
+ qs = graphene_type._meta.model.objects
+
+ nodes = list(qs.filter(pk__in=pks))
nodes.sort(key=lambda e: pks.index(str(e.pk))) # preserve order in pks
if not nodes:
diff --git a/saleor/menu/models.py b/saleor/menu/models.py
index 3b1a2763bb..878aff7b1f 100644
--- a/saleor/menu/models.py
+++ b/saleor/menu/models.py
@@ -27,7 +27,11 @@ class Menu(models.Model):
return self.name
-class MenuItem(MPTTModel, SortableModel):
+class _MenuItemMeta(type(MPTTModel), type(SortableModel)):
+ pass
+
+
+class MenuItem(MPTTModel, SortableModel, metaclass=_MenuItemMeta):
menu = models.ForeignKey(Menu, related_name="items", on_delete=models.CASCADE)
name = models.CharField(max_length=128)
parent = models.ForeignKey(
diff --git a/saleor/product/migrations/0049_collection.py b/saleor/product/migrations/0049_collection.py
index dc8bd89aea..8066c3b391 100644
--- a/saleor/product/migrations/0049_collection.py
+++ b/saleor/product/migrations/0049_collection.py
@@ -10,6 +10,21 @@ class Migration(migrations.Migration):
dependencies = [("product", "0048_product_class_to_type")]
operations = [
+ migrations.CreateModel(
+ name="CollectionProduct",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ )
+ ],
+ options={"db_table": "product_collection_products"},
+ ),
migrations.CreateModel(
name="Collection",
fields=[
@@ -27,9 +42,26 @@ class Migration(migrations.Migration):
(
"products",
models.ManyToManyField(
- blank=True, related_name="collections", to="product.Product"
+ blank=True,
+ related_name="collections",
+ through="product.CollectionProduct",
+ to="product.Product",
),
),
],
- )
+ ),
+ migrations.AddField(
+ model_name="collectionproduct",
+ name="collection",
+ field=models.ForeignKey(
+ on_delete=models.deletion.CASCADE, to="product.Collection"
+ ),
+ ),
+ migrations.AddField(
+ model_name="collectionproduct",
+ name="product",
+ field=models.ForeignKey(
+ on_delete=models.deletion.CASCADE, to="product.Product"
+ ),
+ ),
]
diff --git a/saleor/product/migrations/0093_auto_20190521_0124.py b/saleor/product/migrations/0093_auto_20190521_0124.py
new file mode 100644
index 0000000000..3b7fd08862
--- /dev/null
+++ b/saleor/product/migrations/0093_auto_20190521_0124.py
@@ -0,0 +1,35 @@
+# Generated by Django 2.2.1 on 2019-05-21 06:24
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("product", "0092_auto_20190507_0309")]
+
+ operations = [
+ migrations.AddField(
+ model_name="collectionproduct",
+ name="sort_order",
+ field=models.PositiveIntegerField(db_index=True, editable=False, null=True),
+ ),
+ migrations.AlterField(
+ model_name="collectionproduct",
+ name="product",
+ field=models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="collectionproduct",
+ to="product.Product",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="collectionproduct",
+ name="collection",
+ field=models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="collectionproduct",
+ to="product.Collection",
+ ),
+ ),
+ migrations.AlterModelTable(name="collectionproduct", table=None),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 8dc7423d39..37716f70d3 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -23,7 +23,7 @@ from saleor.core.utils import build_absolute_uri
from ..core import TaxRateType
from ..core.exceptions import InsufficientStock
-from ..core.models import PublishableModel, SortableModel
+from ..core.models import PublishableModel, SortableModel, SortableModelNullable
from ..core.utils.taxes import apply_tax_to_price
from ..core.utils.translations import TranslationProxy
from ..core.weight import WeightUnits, zero_weight
@@ -192,6 +192,9 @@ class Product(SeoModel, PublishableModel):
price = apply_tax_to_price(taxes, tax_rate, price)
return TaxedMoneyRange(start=price, stop=price)
+ def get_ordering_queryset(self):
+ return self.category.products.all()
+
class ProductTranslation(SeoModelTranslation):
language_code = models.CharField(max_length=10)
@@ -533,10 +536,28 @@ class VariantImage(models.Model):
)
+class CollectionProduct(SortableModelNullable):
+ collection = models.ForeignKey(
+ "Collection", related_name="collectionproduct", on_delete=models.CASCADE
+ )
+ product = models.ForeignKey(
+ Product, related_name="collectionproduct", on_delete=models.CASCADE
+ )
+
+ def get_ordering_queryset(self):
+ return self.product.collectionproduct.all()
+
+
class Collection(SeoModel, PublishableModel):
name = models.CharField(max_length=128, unique=True)
slug = models.SlugField(max_length=128)
- products = models.ManyToManyField(Product, blank=True, related_name="collections")
+ products = models.ManyToManyField(
+ Product,
+ blank=True,
+ related_name="collections",
+ through=CollectionProduct,
+ through_fields=["collection", "product"],
+ )
background_image = VersatileImageField(
upload_to="collection-backgrounds", blank=True, null=True
)
diff --git a/tests/api/test_product_sorting.py b/tests/api/test_product_sorting.py
new file mode 100644
index 0000000000..0e5c5ecc1e
--- /dev/null
+++ b/tests/api/test_product_sorting.py
@@ -0,0 +1,186 @@
+from typing import Dict, List
+
+import graphene
+import pytest
+from prices import Money
+
+from saleor.product.models import CollectionProduct, Product
+from tests.api.utils import get_graphql_content
+
+GET_SORTED_PRODUCTS_COLLECTION_QUERY = """
+query CollectionProducts($id: ID!) {
+ collection(id: $id) {
+ products(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+}
+"""
+
+COLLECTION_RESORT_QUERY = """
+mutation ReorderCollectionProducts($collectionId: ID!, $moves: [MoveProductInput]!) {
+ collectionReorderProducts(collectionId: $collectionId, moves: $moves) {
+ collection {
+ products(first: 10) {
+ edges {
+ node {
+ name
+ id
+ }
+ }
+ }
+ }
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+def _assert_product_are_correctly_ordered(expected: List[Product], nodes: List[Dict]):
+ assert len(nodes) == len(expected), "Size differs"
+ expected_ids = [p.pk for p in expected]
+ nodes_ids = [int(graphene.Node.from_global_id(p["node"]["id"])[1]) for p in nodes]
+ assert nodes_ids == expected_ids
+
+
[email protected]("wanted_pos, expected_pos", ((-100, 0), (+100, 100)))
+def test_sort_products_within_category_with_out_of_bound_value(
+ staff_api_client,
+ collection,
+ product,
+ permission_manage_products,
+ wanted_pos,
+ expected_pos,
+):
+ product.collections.add(collection)
+ moves = [
+ {
+ "productId": graphene.Node.to_global_id("Product", product.pk),
+ "sortOrder": wanted_pos,
+ }
+ ]
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ COLLECTION_RESORT_QUERY,
+ {
+ "collectionId": graphene.Node.to_global_id("Collection", collection.pk),
+ "moves": moves,
+ },
+ permissions=[permission_manage_products],
+ )
+ )
+
+ # Look if the order is as expected
+ assert product.collectionproduct.first().sort_order == expected_pos
+
+
+def test_sort_products_within_collection(
+ staff_api_client,
+ staff_user,
+ collection,
+ collection_with_products,
+ permission_manage_products,
+):
+ expected_product_order = list(Product.objects.collection_sorted(user=staff_user))
+ assert Product.objects.count() == len(expected_product_order)
+
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ products = get_graphql_content(
+ staff_api_client.post_graphql(
+ GET_SORTED_PRODUCTS_COLLECTION_QUERY, {"id": collection_id}
+ )
+ )["data"]["collection"]["products"]["edges"]
+
+ # Ensure the default the order is in place and well returned by default
+ _assert_product_are_correctly_ordered(expected_product_order, products)
+
+ # Reorder the items
+ product_move_1 = expected_product_order.pop(2)
+ product_move_2 = expected_product_order.pop(0)
+
+ expected_product_order.insert(0, product_move_1)
+ expected_product_order.insert(2, product_move_2)
+
+ moves = [
+ {
+ "productId": graphene.Node.to_global_id("Product", product_move_1.pk),
+ "sortOrder": -1,
+ },
+ {
+ "productId": graphene.Node.to_global_id("Product", product_move_2.pk),
+ "sortOrder": +2,
+ },
+ ]
+ products = get_graphql_content(
+ staff_api_client.post_graphql(
+ COLLECTION_RESORT_QUERY,
+ {"collectionId": collection_id, "moves": moves},
+ permissions=[permission_manage_products],
+ )
+ )["data"]["collectionReorderProducts"]["collection"]["products"]["edges"]
+
+ # Look if the order is right
+ _assert_product_are_correctly_ordered(expected_product_order, products)
+
+
+def test_sort_products_within_collection_null_sort_order_is_ordered_to_last(
+ staff_api_client,
+ staff_user,
+ collection,
+ category,
+ product_type,
+ permission_manage_products,
+):
+ db_products = CollectionProduct.objects.bulk_create(
+ [
+ CollectionProduct(
+ collection=collection,
+ product=Product.objects.create(
+ price=Money(10, "USD"), product_type=product_type, category=category
+ ),
+ ),
+ CollectionProduct(
+ collection=collection,
+ sort_order=1,
+ product=Product.objects.create(
+ price=Money(10, "USD"), product_type=product_type, category=category
+ ),
+ ),
+ ]
+ )
+
+ assert db_products[0].sort_order is None
+ assert db_products[1].sort_order == 1
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ null_product_id = graphene.Node.to_global_id("Product", db_products[0].product.pk)
+
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ products = get_graphql_content(
+ staff_api_client.post_graphql(
+ GET_SORTED_PRODUCTS_COLLECTION_QUERY, {"id": collection_id}
+ )
+ )["data"]["collection"]["products"]["edges"]
+
+ assert len(products) == len(db_products)
+ assert products[-1]["node"]["id"] == null_product_id
+
+ products = get_graphql_content(
+ staff_api_client.post_graphql(
+ COLLECTION_RESORT_QUERY,
+ {
+ "collectionId": collection_id,
+ "moves": [{"productId": null_product_id, "sortOrder": -len(products)}],
+ },
+ )
+ )["data"]["collectionReorderProducts"]["collection"]["products"]["edges"]
+
+ # Ensure it was properly pushed to the top
+ assert products[0]["node"]["id"] == null_product_id
diff --git a/tests/conftest.py b/tests/conftest.py
index d9f5483977..17127f7b1a 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -38,6 +38,7 @@ from saleor.product.models import (
AttributeValue,
Category,
Collection,
+ CollectionProduct,
DigitalContent,
DigitalContentUrl,
Product,
@@ -861,6 +862,15 @@ def collection(db):
return collection
+def collection_with_products(db, collection, product_list_published):
+ for sort_order, product in enumerate(product_list_published):
+ CollectionProduct(
+ collection=collection, product=product, sort_order=sort_order
+ ).save()
+ return product_list_published
+
+
@pytest.fixture
def collection_with_image(db, image, media_root):
collection = Collection.objects.create(