Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge branch 'master' of github.com:mirumee/saleor into feature/default_product_variant
Tomasz Szymanski1581060e48fd
diff --cc CHANGELOG.mdindex 60eeb54bc9,9a0b23514e..395843171e--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -20,7 -20,7 +20,8 @@@ All notable, unreleased changes to thi- Add `PRODUCT_UPDATED` webhook event - #6100 by @tomaszszymanski129- Search orders by graphql PaymentID - #6135 by @korycins- Search orders by custom key provided by payment gateway - #6135 by @korycins+- Default product variant - #6140 by @tomaszszymanski129+ - Allow product variants to be sortable - #6138 by @tomaszszymanski129### Breaking Changesdiff --cc saleor/graphql/product/mutations/products.pyindex 2b62cdc5bb,c7fc79d5fc..b1e8272240--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@@ -1786,45 -1785,75 +1787,114 @@@ class ProductImageReorder(BaseMutation)return ProductImageReorder(product=product, images=images)+class ProductVariantSetDefault(BaseMutation):+ product = graphene.Field(Product)++ class Arguments:+ product_id = graphene.ID(+ required=True,+ description="Id of a product that will have the default variant set.",+ )+ variant_id = graphene.ID(+ required=True, description="Id of a variant that will be set as default.",+ )++ class Meta:+ description = (+ "Set default variant for a product. "+ "Mutation triggers PRODUCT_UPDATED webhook."+ )+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = ProductError+ error_type_field = "product_errors"++ @classmethod+ def perform_mutation(cls, _root, info, product_id, variant_id):+ product = cls.get_node_or_error(+ info, product_id, field="product_id", only_type=Product+ )+ variant = cls.get_node_or_error(+ info,+ variant_id,+ field="variant_id",+ only_type=ProductVariant,+ qs=product.variants.all(),+ )+ variant.set_as_default()+ product.save(update_fields=["updated_at"])+ info.context.plugins.product_updated(product)+ return ProductVariantSetDefault(product=product)+++ class ProductVariantReorder(BaseMutation):+ product = graphene.Field(Product)++ class Arguments:+ product_id = graphene.ID(+ required=True,+ description="Id of product that variants order will be altered.",+ )+ moves = graphene.List(+ ReorderInput,+ required=True,+ description="The list of variant reordering operations.",+ )++ class Meta:+ description = (+ "Reorder the variants of a product. "+ "Mutation updates updated_at on product and "+ "triggers PRODUCT_UPDATED webhook."+ )+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = ProductError+ error_type_field = "product_errors"++ @classmethod+ def perform_mutation(cls, _root, info, product_id, moves):+ pk = from_global_id_strict_type(product_id, only_type=Product, field="id")++ try:+ product = models.Product.objects.prefetch_related("variants").get(pk=pk)+ except ObjectDoesNotExist:+ raise ValidationError(+ {+ "product_id": ValidationError(+ (f"Couldn't resolve to a product type: {product_id}"),+ code=ProductErrorCode.NOT_FOUND,+ )+ }+ )++ variants_m2m = product.variants+ operations = {}++ for move_info in moves:+ variant_pk = from_global_id_strict_type(+ move_info.id, only_type=ProductVariant, field="moves"+ )++ try:+ m2m_info = variants_m2m.get(id=int(variant_pk))+ except ObjectDoesNotExist:+ raise ValidationError(+ {+ "moves": ValidationError(+ f"Couldn't resolve to a variant: {move_info.id}",+ code=ProductErrorCode.NOT_FOUND,+ )+ }+ )+ operations[m2m_info.pk] = move_info.sort_order++ with transaction.atomic():+ perform_reordering(variants_m2m, operations)++ product.save(update_fields=["updated_at"])+ info.context.plugins.product_updated(product)+ return ProductVariantReorder(product=product)++class ProductImageDelete(BaseMutation):product = graphene.Field(Product)image = graphene.Field(ProductImage)diff --cc saleor/graphql/product/schema.pyindex 324832a5ee,088cb2f074..75c7f2cd7f--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@@ -99,7 -99,7 +99,8 @@@ from .mutations.products importProductVariantClearPrivateMeta,ProductVariantCreate,ProductVariantDelete,+ ProductVariantReorder,+ ProductVariantSetDefault,ProductVariantUpdate,ProductVariantUpdateMeta,ProductVariantUpdatePrivateMeta,diff --cc saleor/graphql/product/tests/test_product.pyindex b2b5480f5a,3deb02e366..b130679073--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@@ -1402,108 -1402,74 +1402,176 @@@ def test_create_productassert color_value_slug in values+PRODUCT_VARIANT_SET_DEFAULT_MUTATION = """+ mutation Prod($productId: ID!, $variantId: ID!) {+ productVariantSetDefault(productId: $productId, variantId: $variantId) {+ product {+ defaultVariant {+ id+ }+ }+ productErrors {+ code+ field+ }+ }+ }+"""+++ REORDER_PRODUCT_VARIANTS_MUTATION = """+ mutation ProductVariantReorder($product: ID!, $moves: [ReorderInput]!) {+ productVariantReorder(productId: $product, moves: $moves) {+ productErrors {+ code+ field+ }+ }+ }+ """+++def test_product_variant_set_default(+ staff_api_client, permission_manage_products, product_with_two_variants+):+ assert not product_with_two_variants.variants.filter(default=True).exists()++ first_variant = product_with_two_variants.variants.first()+ first_variant_id = graphene.Node.to_global_id("ProductVariant", first_variant.pk)++ variables = {+ "productId": graphene.Node.to_global_id(+ "Product", product_with_two_variants.pk+ ),+ "variantId": first_variant_id,+ }++ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_SET_DEFAULT_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ assert (+ product_with_two_variants.variants.filter(default=True).first().pk+ == first_variant.pk+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantSetDefault"]+ assert not data["productErrors"]+ assert data["product"]["defaultVariant"]["id"] == first_variant_id+++def test_product_variant_set_default_invalid_id(+ staff_api_client, permission_manage_products, product_with_two_variants+):+ assert not product_with_two_variants.variants.filter(default=True).exists()++ first_variant = product_with_two_variants.variants.first()++ variables = {+ "productId": graphene.Node.to_global_id(+ "Product", product_with_two_variants.pk+ ),+ "variantId": graphene.Node.to_global_id("Product", first_variant.pk),+ }++ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_SET_DEFAULT_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ assert not product_with_two_variants.variants.filter(default=True).exists()+ content = get_graphql_content(response)+ data = content["data"]["productVariantSetDefault"]+ assert data["productErrors"][0]["code"] == ProductErrorCode.INVALID.name+ assert data["productErrors"][0]["field"] == "variantId"+++def test_product_variant_set_default_not_products_variant(+ staff_api_client,+ permission_manage_products,+ product_with_two_variants,+ product_with_single_variant,+):+ assert not product_with_two_variants.variants.filter(default=True).exists()++ foreign_variant = product_with_single_variant.variants.first()++ variables = {+ "productId": graphene.Node.to_global_id(+ "Product", product_with_two_variants.pk+ ),+ "variantId": graphene.Node.to_global_id("ProductVariant", foreign_variant.pk),+ }++ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_SET_DEFAULT_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ assert not product_with_two_variants.variants.filter(default=True).exists()+ content = get_graphql_content(response)+ data = content["data"]["productVariantSetDefault"]+ assert data["productErrors"][0]["code"] == ProductErrorCode.NOT_FOUND.name+ assert data["productErrors"][0]["field"] == "variantId"+++ def test_reorder_variants(+ staff_api_client, product_with_two_variants, permission_manage_products,+ ):+ default_variants = product_with_two_variants.variants.all()+ new_variants = [default_variants[1], default_variants[0]]++ variables = {+ "product": graphene.Node.to_global_id("Product", product_with_two_variants.pk),+ "moves": [+ {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "sortOrder": _order + 1,+ }+ for _order, variant in enumerate(new_variants)+ ],+ }++ response = staff_api_client.post_graphql(+ REORDER_PRODUCT_VARIANTS_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantReorder"]+ assert not data["productErrors"]+ assert list(product_with_two_variants.variants.all()) == new_variants+++ def test_reorder_variants_invalid_variants(+ staff_api_client, product, product_with_two_variants, permission_manage_products,+ ):+ default_variants = product_with_two_variants.variants.all()+ new_variants = [product.variants.first(), default_variants[1]]++ variables = {+ "product": graphene.Node.to_global_id("Product", product_with_two_variants.pk),+ "moves": [+ {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "sortOrder": _order + 1,+ }+ for _order, variant in enumerate(new_variants)+ ],+ }++ response = staff_api_client.post_graphql(+ REORDER_PRODUCT_VARIANTS_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantReorder"]+ assert data["productErrors"][0]["field"] == "moves"+ assert data["productErrors"][0]["code"] == ProductErrorCode.NOT_FOUND.name++@pytest.mark.parametrize("input_slug", ["", None])def test_create_product_no_slug_in_input(staff_api_client,diff --cc saleor/graphql/schema.graphqlindex dc28357b12,abe05671b3..7e96f58457--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@@ -4178,12 -4176,12 +4179,18 @@@ input ProductVariantInputweight: WeightScalar}+ type ProductVariantReorder {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ product: Product+ productErrors: [ProductError!]!+ }++type ProductVariantSetDefault {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ product: Product+ productErrors: [ProductError!]!+}+type ProductVariantStocksCreate {errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")productVariant: ProductVariantdiff --cc saleor/product/migrations/0126_productvariant_default.pyindex 01a1c0135b,0000000000..ac6c29d550mode 100644,000000..100644--- a/saleor/product/migrations/0126_productvariant_default.py+++ b/saleor/product/migrations/0126_productvariant_default.py@@@ -1,18 -1,0 +1,18 @@@- # Generated by Django 3.1.1 on 2020-09-17 15:46++# Generated by Django 3.1.1 on 2020-09-21 08:03++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [- ("product", "0124_auto_20200909_0904"),++ ("product", "0125_auto_20200916_1511"),+ ]++ operations = [+ migrations.AddField(+ model_name="productvariant",+ name="default",+ field=models.BooleanField(default=False),+ ),+ ]diff --cc saleor/product/models.pyindex d680e0c196,a09d37e062..d1e502104a--- a/saleor/product/models.py+++ b/saleor/product/models.py@@@ -466,11 -462,9 +466,14 @@@ class ProductVariant(SortableModel, Modimages = list(self.images.all())return images[0] if images else self.product.get_first_image()+ def get_ordering_queryset(self):+ return self.product.variants.all()++ def set_as_default(self):+ self.product.variants.update(default=False)+ self.default = True+ self.save(update_fields=["default"])+class ProductVariantTranslation(models.Model):language_code = models.CharField(max_length=10)