Skip to content

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

Add exclude products mutation, and exclude products field (#6506)

Maciej Korycinski12007c00e480
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c10a31dd09..1b4b98b3a5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add generic FileUpload mutation - #6470 by @IKarbowiak
- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki
- Fix password reset request - #6351 by @Manfred-Madelaine-pro, Ambroise and Pierre
+- Add possibility to exclude products from shipping method - #6506 by @korycins
# 2.11.1
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 481f9b0227..8deb6e6e16 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2561,6 +2561,8 @@ type Mutation {
shippingPriceBulkDelete(ids: [ID]!): ShippingPriceBulkDelete
shippingPriceUpdate(id: ID!, input: ShippingPriceInput!): ShippingPriceUpdate
shippingPriceTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): ShippingPriceTranslate
+ shippingPriceExcludeProducts(id: ID!, input: ShippingPriceExcludeProductsInput!): ShippingPriceExcludeProducts
+ shippingPriceRemoveProductFromExclude(id: ID!, products: [ID]!): ShippingPriceRemoveProductFromExclude
shippingZoneCreate(input: ShippingZoneCreateInput!): ShippingZoneCreate
shippingZoneDelete(id: ID!): ShippingZoneDelete
shippingZoneBulkDelete(ids: [ID]!): ShippingZoneBulkDelete
@@ -4582,6 +4584,7 @@ type ShippingMethod implements Node & ObjectWithMetadata {
price: Money
maximumOrderPrice: Money
minimumOrderPrice: Money
+ excludedProducts(before: String, after: String, first: Int, last: Int): ProductCountableConnection
}
type ShippingMethodChannelListing implements Node {
@@ -4648,6 +4651,16 @@ type ShippingPriceDelete {
shippingErrors: [ShippingError!]!
}
+type ShippingPriceExcludeProducts {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ shippingMethod: ShippingMethod
+ shippingErrors: [ShippingError!]!
+}
+
+input ShippingPriceExcludeProductsInput {
+ products: [ID]!
+}
+
input ShippingPriceInput {
name: String
minimumOrderWeight: WeightScalar
@@ -4656,6 +4669,12 @@ input ShippingPriceInput {
shippingZone: ID
}
+type ShippingPriceRemoveProductFromExclude {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ shippingMethod: ShippingMethod
+ shippingErrors: [ShippingError!]!
+}
+
type ShippingPriceTranslate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
translationErrors: [TranslationError!]!
diff --git a/saleor/graphql/shipping/mutations/shippings.py b/saleor/graphql/shipping/mutations/shippings.py
index 73e86a8f70..ebdb532b65 100644
--- a/saleor/graphql/shipping/mutations/shippings.py
+++ b/saleor/graphql/shipping/mutations/shippings.py
@@ -3,6 +3,7 @@ from django.core.exceptions import ValidationError
from django.db import transaction
from ....core.permissions import ShippingPermissions
+from ....product import models as product_models
from ....shipping import models
from ....shipping.error_codes import ShippingErrorCode
from ....shipping.utils import (
@@ -14,6 +15,8 @@ from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.scalars import WeightScalar
from ...core.types.common import ShippingError
from ...core.utils import get_duplicates_ids
+from ...product import types as product_types
+from ...utils import resolve_global_ids_to_primary_keys
from ..enums import ShippingMethodTypeEnum
from ..types import ShippingMethod, ShippingZone
@@ -319,3 +322,93 @@ class ShippingPriceDelete(BaseMutation):
shipping_method=ChannelContext(node=shipping_method, channel_slug=None),
shipping_zone=ChannelContext(node=shipping_zone, channel_slug=None),
)
+
+
+class ShippingPriceExcludeProductsInput(graphene.InputObjectType):
+ products = graphene.List(
+ graphene.ID,
+ description="List of products which will be excluded.",
+ required=True,
+ )
+
+
+class ShippingPriceExcludeProducts(BaseMutation):
+ shipping_method = graphene.Field(
+ ShippingMethod,
+ description="A shipping method with new list of excluded products.",
+ )
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a shipping price.")
+
+ input = ShippingPriceExcludeProductsInput(
+ description="Exclude products input.", required=True
+ )
+
+ class Meta:
+ description = "Exclude products from shipping price."
+ permissions = (ShippingPermissions.MANAGE_SHIPPING,)
+ error_type_class = ShippingError
+ error_type_field = "shipping_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ shipping_method = cls.get_node_or_error(
+ info, data.get("id"), only_type=ShippingMethod
+ )
+ input = data.get("input")
+ product_ids = input.get("products", [])
+
+ _, product_db_ids = resolve_global_ids_to_primary_keys(
+ product_ids, product_types.Product
+ )
+
+ product_to_exclude = product_models.Product.objects.filter(
+ id__in=product_db_ids
+ )
+
+ current_excluded_products = shipping_method.excluded_products.all()
+ shipping_method.excluded_products.set(
+ (current_excluded_products | product_to_exclude).distinct()
+ )
+ return ShippingPriceExcludeProducts(
+ shipping_method=ChannelContext(node=shipping_method, channel_slug=None)
+ )
+
+
+class ShippingPriceRemoveProductFromExclude(BaseMutation):
+ shipping_method = graphene.Field(
+ ShippingMethod,
+ description="A shipping method with new list of excluded products.",
+ )
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a shipping price.")
+ products = graphene.List(
+ graphene.ID,
+ required=True,
+ description="List of products which will be removed from excluded list.",
+ )
+
+ class Meta:
+ description = "Remove product from excluded list for shipping price."
+ permissions = (ShippingPermissions.MANAGE_SHIPPING,)
+ error_type_class = ShippingError
+ error_type_field = "shipping_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ shipping_method = cls.get_node_or_error(
+ info, data.get("id"), only_type=ShippingMethod
+ )
+ product_ids = data.get("products")
+ if product_ids:
+ _, product_db_ids = resolve_global_ids_to_primary_keys(
+ product_ids, product_types.Product
+ )
+ shipping_method.excluded_products.set(
+ shipping_method.excluded_products.exclude(id__in=product_db_ids)
+ )
+ return ShippingPriceExcludeProducts(
+ shipping_method=ChannelContext(node=shipping_method, channel_slug=None)
+ )
diff --git a/saleor/graphql/shipping/schema.py b/saleor/graphql/shipping/schema.py
index aad318435d..9f45458d64 100644
--- a/saleor/graphql/shipping/schema.py
+++ b/saleor/graphql/shipping/schema.py
@@ -10,6 +10,8 @@ from .mutations.channels import ShippingMethodChannelListingUpdate
from .mutations.shippings import (
ShippingPriceCreate,
ShippingPriceDelete,
+ ShippingPriceExcludeProducts,
+ ShippingPriceRemoveProductFromExclude,
ShippingPriceUpdate,
ShippingZoneCreate,
ShippingZoneDelete,
@@ -55,6 +57,10 @@ class ShippingMutations(graphene.ObjectType):
shipping_price_bulk_delete = ShippingPriceBulkDelete.Field()
shipping_price_update = ShippingPriceUpdate.Field()
shipping_price_translate = ShippingPriceTranslate.Field()
+ shipping_price_exclude_products = ShippingPriceExcludeProducts.Field()
+ shipping_price_remove_product_from_exclude = (
+ ShippingPriceRemoveProductFromExclude.Field()
+ )
shipping_zone_create = ShippingZoneCreate.Field()
shipping_zone_delete = ShippingZoneDelete.Field()
diff --git a/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py b/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py
index b0124f9753..3dca69c16a 100644
--- a/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py
+++ b/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py
@@ -1,3 +1,4 @@
+import graphene
import pytest
from ....tests.utils import get_graphql_content
@@ -79,3 +80,167 @@ def test_vouchers_query_without_channel_slug(
check_no_permissions=False,
)
)
+
+
+EXCLUDE_PRODUCTS_MUTATION = """
+ mutation shippingPriceRemoveProductFromExclude(
+ $id: ID!, $input:ShippingPriceExcludeProductsInput!
+ ) {
+ shippingPriceExcludeProducts(
+ id: $id
+ input: $input) {
+ shippingErrors {
+ field
+ code
+ }
+ shippingMethod {
+ id
+ excludedProducts(first:10){
+ totalCount
+ edges{
+ node{
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+"""
+
+
[email protected]_queries(autouse=False)
+def test_exclude_products_for_shipping_method(
+ shipping_method,
+ published_collection,
+ product_list_published,
+ product_list,
+ categories_tree_with_published_products,
+ collection,
+ staff_api_client,
+ permission_manage_shipping,
+):
+ # product_list has products with slugs slug:test-product-a, slug:test-product-b,
+ # slug:test-product-c
+ product_db_ids = [p.pk for p in product_list]
+ product_ids = [graphene.Node.to_global_id("Product", p) for p in product_db_ids]
+
+ expected_product_ids = [
+ graphene.Node.to_global_id("Product", p.pk) for p in product_list
+ ]
+
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ variables = {
+ "id": shipping_method_id,
+ "input": {"products": product_ids},
+ }
+
+ response = staff_api_client.post_graphql(
+ EXCLUDE_PRODUCTS_MUTATION, variables, permissions=[permission_manage_shipping]
+ )
+
+ content = get_graphql_content(response)
+ shipping_method = content["data"]["shippingPriceExcludeProducts"]["shippingMethod"]
+ excluded_products = shipping_method["excludedProducts"]
+ total_count = excluded_products["totalCount"]
+ excluded_product_ids = {p["node"]["id"] for p in excluded_products["edges"]}
+ assert len(expected_product_ids) == total_count == 3
+ assert excluded_product_ids == set(expected_product_ids)
+
+
[email protected]_queries(autouse=False)
+def test_exclude_products_for_shipping_method_already_has_excluded_products(
+ shipping_method,
+ product_list,
+ product,
+ staff_api_client,
+ permission_manage_shipping,
+):
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ shipping_method.excluded_products.add(product, product_list[0])
+ product_ids = [graphene.Node.to_global_id("Product", p.pk) for p in product_list]
+ variables = {"id": shipping_method_id, "input": {"products": product_ids}}
+ response = staff_api_client.post_graphql(
+ EXCLUDE_PRODUCTS_MUTATION, variables, permissions=[permission_manage_shipping]
+ )
+ content = get_graphql_content(response)
+ shipping_method = content["data"]["shippingPriceExcludeProducts"]["shippingMethod"]
+ excluded_products = shipping_method["excludedProducts"]
+ total_count = excluded_products["totalCount"]
+ expected_product_ids = product_ids
+ expected_product_ids.append(graphene.Node.to_global_id("Product", product.pk))
+ excluded_product_ids = {p["node"]["id"] for p in excluded_products["edges"]}
+ assert len(expected_product_ids) == total_count
+ assert excluded_product_ids == set(expected_product_ids)
+
+
+REMOVE_PRODUCTS_FROM_EXCLUDED_PRODUCTS_MUTATION = """
+ mutation shippingPriceRemoveProductFromExclude(
+ $id: ID!, $products: [ID]!
+ ) {
+ shippingPriceRemoveProductFromExclude(
+ id: $id
+ products: $products) {
+ shippingErrors {
+ field
+ code
+ }
+ shippingMethod {
+ id
+ excludedProducts(first:10){
+ totalCount
+ edges{
+ node{
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+"""
+
+
[email protected]_queries(autouse=False)
+def test_remove_products_from_excluded_products_for_shipping_method(
+ shipping_method,
+ product_list,
+ staff_api_client,
+ permission_manage_shipping,
+ product,
+):
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ shipping_method.excluded_products.set(product_list)
+ shipping_method.excluded_products.add(product)
+
+ product_ids = [
+ graphene.Node.to_global_id("Product", product.pk),
+ ]
+ variables = {"id": shipping_method_id, "products": product_ids}
+ response = staff_api_client.post_graphql(
+ REMOVE_PRODUCTS_FROM_EXCLUDED_PRODUCTS_MUTATION,
+ variables,
+ permissions=[permission_manage_shipping],
+ )
+
+ content = get_graphql_content(response)
+ shipping_method = content["data"]["shippingPriceRemoveProductFromExclude"][
+ "shippingMethod"
+ ]
+ excluded_products = shipping_method["excludedProducts"]
+ total_count = excluded_products["totalCount"]
+ expected_product_ids = {
+ graphene.Node.to_global_id("Product", p.pk) for p in product_list
+ }
+ excluded_product_ids = {p["node"]["id"] for p in excluded_products["edges"]}
+ assert total_count == len(expected_product_ids)
+ assert excluded_product_ids == expected_product_ids
diff --git a/saleor/graphql/shipping/tests/test_shipping_method.py b/saleor/graphql/shipping/tests/test_shipping_method.py
index 29293be5ab..7101153c27 100644
--- a/saleor/graphql/shipping/tests/test_shipping_method.py
+++ b/saleor/graphql/shipping/tests/test_shipping_method.py
@@ -907,3 +907,190 @@ def test_delete_shipping_method(
assert data["shippingZone"]["id"] == shipping_zone_id
with pytest.raises(shipping_method._meta.model.DoesNotExist):
shipping_method.refresh_from_db()
+
+
+EXCLUDE_PRODUCTS_MUTATION = """
+ mutation shippingPriceRemoveProductFromExclude(
+ $id: ID!, $input:ShippingPriceExcludeProductsInput!
+ ) {
+ shippingPriceExcludeProducts(
+ id: $id
+ input: $input) {
+ shippingErrors {
+ field
+ code
+ }
+ shippingMethod {
+ id
+ excludedProducts(first:10){
+ totalCount
+ edges{
+ node{
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+"""
+
+
[email protected]("requestor", ["staff", "app"])
+def test_exclude_products_for_shipping_method_only_products(
+ requestor,
+ app_api_client,
+ shipping_method,
+ product_list,
+ staff_api_client,
+ permission_manage_shipping,
+):
+ api = staff_api_client if requestor == "staff" else app_api_client
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ product_ids = [graphene.Node.to_global_id("Product", p.pk) for p in product_list]
+ variables = {"id": shipping_method_id, "input": {"products": product_ids}}
+ response = api.post_graphql(
+ EXCLUDE_PRODUCTS_MUTATION, variables, permissions=[permission_manage_shipping]
+ )
+ content = get_graphql_content(response)
+ shipping_method = content["data"]["shippingPriceExcludeProducts"]["shippingMethod"]
+ excluded_products = shipping_method["excludedProducts"]
+ total_count = excluded_products["totalCount"]
+ excluded_product_ids = {p["node"]["id"] for p in excluded_products["edges"]}
+ assert len(product_ids) == total_count
+ assert excluded_product_ids == set(product_ids)
+
+
[email protected]("requestor", ["staff", "app"])
+def test_exclude_products_for_shipping_method_already_has_excluded_products(
+ requestor,
+ shipping_method,
+ product_list,
+ product,
+ staff_api_client,
+ permission_manage_shipping,
+ app_api_client,
+):
+ api = staff_api_client if requestor == "staff" else app_api_client
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ shipping_method.excluded_products.add(product, product_list[0])
+ product_ids = [graphene.Node.to_global_id("Product", p.pk) for p in product_list]
+ variables = {"id": shipping_method_id, "input": {"products": product_ids}}
+ response = api.post_graphql(
+ EXCLUDE_PRODUCTS_MUTATION, variables, permissions=[permission_manage_shipping]
+ )
+ content = get_graphql_content(response)
+ shipping_method = content["data"]["shippingPriceExcludeProducts"]["shippingMethod"]
+ excluded_products = shipping_method["excludedProducts"]
+ total_count = excluded_products["totalCount"]
+ expected_product_ids = product_ids
+ expected_product_ids.append(graphene.Node.to_global_id("Product", product.pk))
+ excluded_product_ids = {p["node"]["id"] for p in excluded_products["edges"]}
+ assert len(expected_product_ids) == total_count
+ assert excluded_product_ids == set(expected_product_ids)
+
+
+REMOVE_PRODUCTS_FROM_EXCLUDED_PRODUCTS_MUTATION = """
+ mutation shippingPriceRemoveProductFromExclude(
+ $id: ID!, $products: [ID]!
+ ) {
+ shippingPriceRemoveProductFromExclude(
+ id: $id
+ products: $products) {
+ shippingErrors {
+ field
+ code
+ }
+ shippingMethod {
+ id
+ excludedProducts(first:10){
+ totalCount
+ edges{
+ node{
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+"""
+
+
[email protected]("requestor", ["staff", "app"])
+def test_remove_products_from_excluded_products_for_shipping_method_delete_all_products(
+ requestor,
+ shipping_method,
+ product_list,
+ staff_api_client,
+ permission_manage_shipping,
+ app_api_client,
+):
+ api = staff_api_client if requestor == "staff" else app_api_client
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ shipping_method.excluded_products.set(product_list)
+
+ product_ids = [graphene.Node.to_global_id("Product", p.pk) for p in product_list]
+ variables = {"id": shipping_method_id, "products": product_ids}
+ response = api.post_graphql(
+ REMOVE_PRODUCTS_FROM_EXCLUDED_PRODUCTS_MUTATION,
+ variables,
+ permissions=[permission_manage_shipping],
+ )
+
+ content = get_graphql_content(response)
+ shipping_method = content["data"]["shippingPriceRemoveProductFromExclude"][
+ "shippingMethod"
+ ]
+ excluded_products = shipping_method["excludedProducts"]
+ total_count = excluded_products["totalCount"]
+ excluded_product_ids = {p["node"]["id"] for p in excluded_products["edges"]}
+ assert total_count == 0
+ assert len(excluded_product_ids) == 0
+
+
[email protected]("requestor", ["staff", "app"])
+def test_remove_products_from_excluded_products_for_shipping_method(
+ requestor,
+ shipping_method,
+ product_list,
+ staff_api_client,
+ permission_manage_shipping,
+ product,
+ app_api_client,
+):
+ api = staff_api_client if requestor == "staff" else app_api_client
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ shipping_method.excluded_products.set(product_list)
+ shipping_method.excluded_products.add(product)
+
+ product_ids = [
+ graphene.Node.to_global_id("Product", product.pk),
+ ]
+ variables = {"id": shipping_method_id, "products": product_ids}
+ response = api.post_graphql(
+ REMOVE_PRODUCTS_FROM_EXCLUDED_PRODUCTS_MUTATION,
+ variables,
+ permissions=[permission_manage_shipping],
+ )
+
+ content = get_graphql_content(response)
+ shipping_method = content["data"]["shippingPriceRemoveProductFromExclude"][
+ "shippingMethod"
+ ]
+ excluded_products = shipping_method["excludedProducts"]
+ total_count = excluded_products["totalCount"]
+ expected_product_ids = {
+ graphene.Node.to_global_id("Product", p.pk) for p in product_list
+ }
+ excluded_product_ids = {p["node"]["id"] for p in excluded_products["edges"]}
+ assert total_count == len(expected_product_ids)
+ assert excluded_product_ids == expected_product_ids
diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.py
index 9a4d8f90fb..1f16daaec2 100644
--- a/saleor/graphql/shipping/types.py
+++ b/saleor/graphql/shipping/types.py
@@ -4,6 +4,7 @@ from graphene import relay
from ...core.permissions import ShippingPermissions
from ...core.weight import convert_weight_to_default_weight_unit
from ...shipping import models
+from ..channel import ChannelQsContext
from ..channel.dataloaders import ChannelByIdLoader
from ..channel.types import (
ChannelContext,
@@ -11,6 +12,7 @@ from ..channel.types import (
ChannelContextTypeWithMetadata,
)
from ..core.connection import CountableDjangoObjectType
+from ..core.fields import ChannelContextFilterConnectionField
from ..core.types import CountryDisplay, Money, MoneyRange
from ..decorators import permission_required
from ..meta.types import ObjectWithMetadata
@@ -65,6 +67,10 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
minimum_order_price = graphene.Field(
Money, description="The price of the cheapest variant (including discounts)."
)
+ excluded_products = ChannelContextFilterConnectionField(
+ "saleor.graphql.product.types.products.Product",
+ description="List of excluded products for the shipping method.",
+ )
class Meta:
default_resolver = ChannelContextType.resolver_with_context
@@ -150,6 +156,13 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
root.node.id
)
+ @staticmethod
+ @permission_required(ShippingPermissions.MANAGE_SHIPPING)
+ def resolve_excluded_products(
+ root: ChannelContext[models.ShippingMethod], _info, **_kwargs
+ ):
+ return ChannelQsContext(qs=root.node.excluded_products.all(), channel_slug=None)
+
class ShippingZone(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
price_range = graphene.Field(
diff --git a/saleor/shipping/migrations/0023_shippingmethod_excluded_products.py b/saleor/shipping/migrations/0023_shippingmethod_excluded_products.py
new file mode 100644
index 0000000000..7bedd784bd
--- /dev/null
+++ b/saleor/shipping/migrations/0023_shippingmethod_excluded_products.py
@@ -0,0 +1,19 @@
+# Generated by Django 3.1.3 on 2020-11-17 12:21
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0135_collection_channel_listing"),
+ ("shipping", "0022_shipping_method_channel_listing"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="shippingmethod",
+ name="excluded_products",
+ field=models.ManyToManyField(blank=True, to="product.Product"),
+ ),
+ ]
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 1048484c35..d8a6ebdc72 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Union
+from typing import TYPE_CHECKING, List, Union
from django.conf import settings
from django.db import models
@@ -96,13 +96,19 @@ class ShippingMethodQueryset(models.QuerySet):
"price_amount"
)
+ def exclude_shipping_methods_for_excluded_products(
+ self, qs, product_ids: List[int]
+ ):
+ """Exclude the ShippingMethods which have excluded given products."""
+ return qs.exclude(excluded_products__id__in=product_ids)
+
def applicable_shipping_methods(
- self, price: Money, channel_id, weight, country_code
+ self, price: Money, channel_id, weight, country_code, product_ids=None
):
"""Return the ShippingMethods that can be used on an order with shipment.
It is based on the given country code, and by shipping methods that are
- applicable to the given price & weight total.
+ applicable to the given price, weight and products.
"""
qs = self.filter(
shipping_zone__countries__contains=country_code,
@@ -110,6 +116,13 @@ class ShippingMethodQueryset(models.QuerySet):
)
qs = self.applicable_shipping_methods_by_channel(qs, channel_id)
qs = qs.prefetch_related("shipping_zone")
+
+ # Products IDs are used to exclude shipping methods that may be not applicable
+ # to some of these products, based on exclusion rules defined in shipping method
+ # instances.
+ if product_ids:
+ qs = self.exclude_shipping_methods_for_excluded_products(qs, product_ids)
+
price_based_methods = _applicable_price_based_methods(price, qs)
weight_based_methods = _applicable_weight_based_methods(weight, qs)
shipping_methods = price_based_methods | weight_based_methods
@@ -127,12 +140,14 @@ class ShippingMethodQueryset(models.QuerySet):
return None
if not instance.shipping_address:
return None
-
+ lines = instance.lines.prefetch_related("variant__product").all()
+ instance_product_ids = set(lines.values_list("variant__product", flat=True))
return self.applicable_shipping_methods(
price=price,
channel_id=channel_id,
weight=instance.get_total_weight(),
country_code=country_code or instance.shipping_address.country.code,
+ product_ids=instance_product_ids,
)
@@ -152,6 +167,9 @@ class ShippingMethod(ModelWithMetadata):
maximum_order_weight = MeasurementField(
measurement=Weight, unit_choices=WeightUnits.CHOICES, blank=True, null=True
)
+ excluded_products = models.ManyToManyField(
+ "product.Product", blank=True
+ ) # type: ignore
objects = ShippingMethodQueryset.as_manager()
translated = TranslationProxy()
diff --git a/saleor/shipping/tests/test_shipping.py b/saleor/shipping/tests/test_shipping.py
index ecda0211e1..a1456a0bcb 100644
--- a/saleor/shipping/tests/test_shipping.py
+++ b/saleor/shipping/tests/test_shipping.py
@@ -174,6 +174,45 @@ def test_applicable_shipping_methods(shipping_zone, channel_USD):
assert weight_method in result
+def test_applicable_shipping_methods_with_excluded_products(
+ shipping_zone, channel_USD, product, product_with_single_variant
+):
+ excluded_method = shipping_zone.shipping_methods.create(
+ type=ShippingMethodType.PRICE_BASED,
+ )
+ excluded_method.excluded_products.add(product)
+ weight_method = shipping_zone.shipping_methods.create(
+ minimum_order_weight=Weight(kg=1),
+ maximum_order_weight=Weight(kg=10),
+ type=ShippingMethodType.WEIGHT_BASED,
+ )
+ ShippingMethodChannelListing.objects.bulk_create(
+ [
+ ShippingMethodChannelListing(
+ shipping_method=weight_method,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ ),
+ ShippingMethodChannelListing(
+ minimum_order_price=Money("1.0", "USD"),
+ maximum_order_price=Money("10.0", "USD"),
+ shipping_method=excluded_method,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ ),
+ ]
+ )
+ result = ShippingMethod.objects.applicable_shipping_methods(
+ price=Money("5.0", "USD"),
+ weight=Weight(kg=5),
+ country_code="PL",
+ channel_id=channel_USD.id,
+ product_ids=[product.id, product_with_single_variant.id],
+ )
+ assert excluded_method not in result
+ assert weight_method in result
+
+
def test_applicable_shipping_methods_not_in_channel(shipping_zone, channel_USD):
price_method = shipping_zone.shipping_methods.create(
type=ShippingMethodType.PRICE_BASED,