Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Full shiping method exclusion by zip codes backend (#6554)
Tomasz Szymański179370ebae3c
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex e940e2f943..7afa4510b8 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -28,6 +28,7 @@ from ...core.transactions import transaction_with_commit_on_errorsfrom ...order import models as order_modelsfrom ...payment import models as payment_modelsfrom ...product import models as product_models+from ...shipping import models as shipping_modelsfrom ...warehouse.availability import check_stock_quantity, get_available_quantityfrom ..account.i18n import I18nMixinfrom ..account.types import AddressInput@@ -770,6 +771,9 @@ class CheckoutShippingMethodUpdate(BaseMutation):shipping_method_id,only_type=ShippingMethod,field="shipping_method_id",+ qs=shipping_models.ShippingMethod.objects.prefetch_related(+ "zip_code_rules"+ ),)lines = list(checkout)@@ -779,7 +783,6 @@ class CheckoutShippingMethodUpdate(BaseMutation):method=shipping_method,discounts=info.context.discounts,)-if not shipping_method_is_valid:raise ValidationError({diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 2009b84d1e..85ba80920d 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -9,6 +9,7 @@ import grapheneimport pytestfrom django.core.exceptions import ValidationErrorfrom django.test import override_settings+from django_countries.fields import Countryfrom prices import Money, TaxedMoneyfrom ....account.models import User@@ -27,6 +28,7 @@ from ....payment.interface import GatewayResponsefrom ....plugins.manager import PluginsManagerfrom ....plugins.tests.sample_plugins import ActiveDummyPaymentGatewayfrom ....product.models import ProductChannelListing+from ....shipping import models as shipping_modelsfrom ....warehouse.models import Stockfrom ...tests.utils import assert_no_permission, get_graphql_contentfrom ..mutations import (@@ -1188,6 +1190,25 @@ def test_checkout_available_shipping_methods(assert data["availableShippingMethods"][0]["name"] == shipping_method.name+def test_checkout_available_shipping_methods_excluded_zip_codes(+ api_client, checkout_with_item, address, shipping_zone+):+ address.country = Country("GB")+ address.postal_code = "BH16 7HF"+ address.save()+ checkout_with_item.shipping_address = address+ checkout_with_item.save()+ shipping_method = shipping_zone.shipping_methods.first()+ shipping_method.zip_code_rules.create(start="BH16 7HA", end="BH16 7HG")++ query = GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS+ variables = {"token": checkout_with_item.token}+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]+ assert data["availableShippingMethods"] == []++@pytest.mark.parametrize("expected_price_type, expected_price, display_gross_prices",(("gross", 13, True), ("net", 10, False)),@@ -2557,6 +2578,38 @@ def test_checkout_shipping_method_update(assert checkout.shipping_method is None+@patch("saleor.shipping.models.check_shipping_method_for_zip_code")+def test_checkout_shipping_method_update_excluded_zip_code(+ mock_check_zip_code, staff_api_client, shipping_method, checkout_with_item, address+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_SHIPPING_METHOD+ mock_check_zip_code.return_value = True++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query, {"checkoutId": checkout_id, "shippingMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]++ checkout.refresh_from_db()++ assert data["errors"] == [+ {+ "field": "shippingMethod",+ "message": "This shipping method is not applicable.",+ }+ ]+ assert checkout.shipping_method is None+ assert (+ mock_check_zip_code.call_count == shipping_models.ShippingMethod.objects.count()+ )++def test_query_checkout_line(checkout_with_item, user_api_client):query = """query checkoutLine($id: ID) {diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex b4cfa0e084..037968bc01 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -19,6 +19,7 @@ from ....order.actions import (from ....order.error_codes import OrderErrorCodefrom ....order.utils import get_valid_shipping_methods_for_order, update_order_pricesfrom ....payment import CustomPaymentChoices, PaymentError, TransactionKind, gateway+from ....shipping import models as shipping_modelsfrom ...account.types import AddressInputfrom ...core.mutations import BaseMutation, ModelMutationfrom ...core.scalars import PositiveDecimal@@ -250,6 +251,9 @@ class OrderUpdateShipping(BaseMutation):data["shipping_method"],field="shipping_method",only_type=ShippingMethod,+ qs=shipping_models.ShippingMethod.objects.prefetch_related(+ "zip_code_rules"+ ),)clean_order_update_shipping(order, method)diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 13192ff3f5..f224f10abd 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -393,17 +393,7 @@ def test_order_query_in_pln_channel(assert expected_method.type.upper() == method["type"]-def test_order_query_without_available_shipping_methods(- staff_api_client,- permission_manage_orders,- order,- shipping_method_channel_PLN,- channel_USD,-):- order.channel = channel_USD- order.shipping_method = shipping_method_channel_PLN- order.save()- query = """+ORDERS_QUERY_SHIPPING_METHODS = """query OrdersQuery {orders(first: 1) {edges {@@ -415,15 +405,45 @@ def test_order_query_without_available_shipping_methods(}}}- """+"""+++def test_order_query_without_available_shipping_methods(+ staff_api_client,+ permission_manage_orders,+ order,+ shipping_method_channel_PLN,+ channel_USD,+):+ order.channel = channel_USD+ order.shipping_method = shipping_method_channel_PLN+ order.save()staff_api_client.user.user_permissions.add(permission_manage_orders)- response = staff_api_client.post_graphql(query)+ response = staff_api_client.post_graphql(ORDERS_QUERY_SHIPPING_METHODS)content = get_graphql_content(response)order_data = content["data"]["orders"]["edges"][0]["node"]assert len(order_data["availableShippingMethods"]) == 0+def test_order_query_shipping_methods_excluded_zip_codes(+ staff_api_client,+ permission_manage_orders,+ order_with_lines_channel_PLN,+ channel_PLN,+):+ order = order_with_lines_channel_PLN+ order.shipping_method.zip_code_rules.create(start="HB3", end="HB6")+ order.shipping_address.postal_code = "HB5"+ order.shipping_address.save(update_fields=["postal_code"])++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDERS_QUERY_SHIPPING_METHODS)+ content = get_graphql_content(response)+ order_data = content["data"]["orders"]["edges"][0]["node"]+ assert order_data["availableShippingMethods"] == []++@pytest.mark.parametrize("expected_price_type, expected_price, display_gross_prices",(("gross", 13, True), ("net", 10, False)),@@ -3500,6 +3520,40 @@ def test_order_update_shipping_incorrect_shipping_method()+def test_order_update_shipping_excluded_shipping_method_zip_code(+ staff_api_client,+ permission_manage_orders,+ order,+ staff_user,+ shipping_method_excldued_by_zip_code,+):+ order.shipping_method = shipping_method_excldued_by_zip_code+ shipping_total = shipping_method_excldued_by_zip_code.channel_listings.get(+ channel_id=order.channel_id,+ ).get_total()++ shipping_price = TaxedMoney(shipping_total, shipping_total)+ order.shipping_price = shipping_price+ order.shipping_method_name = "Example shipping"+ order.save()++ query = ORDER_UPDATE_SHIPPING_QUERY+ order_id = graphene.Node.to_global_id("Order", order.id)+ method_id = graphene.Node.to_global_id(+ "ShippingMethod", shipping_method_excldued_by_zip_code.id+ )+ variables = {"order": order_id, "shippingMethod": method_id}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderUpdateShipping"]+ assert data["errors"][0]["field"] == "shippingMethod"+ assert data["errors"][0]["message"] == (+ "Shipping method cannot be used with this order."+ )++def test_draft_order_clear_shipping_method(staff_api_client, draft_order, permission_manage_orders):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 5a90a9a8d5..e73baff3d1 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2557,6 +2557,8 @@ type Mutation {shopAddressUpdate(input: AddressInput): ShopAddressUpdateorderSettingsUpdate(input: OrderSettingsUpdateInput!): OrderSettingsUpdateshippingMethodChannelListingUpdate(id: ID!, input: ShippingMethodChannelListingInput!): ShippingMethodChannelListingUpdate+ shippingMethodZipCodeRulesCreate(input: ShippingZipCodeRulesCreateInput!, shippingMethodId: ID!): ShippingZipCodeRulesCreate+ shippingMethodZipCodeRulesDelete(id: ID!): ShippingZipCodeRulesDeleteshippingPriceCreate(input: ShippingPriceInput!): ShippingPriceCreateshippingPriceDelete(id: ID!): ShippingPriceDeleteshippingPriceBulkDelete(ids: [ID]!): ShippingPriceBulkDelete@@ -4621,6 +4623,7 @@ type ShippingMethod implements Node & ObjectWithMetadata {price: MoneymaximumOrderPrice: MoneyminimumOrderPrice: Money+ zipCodeRules: [ShippingMethodZipCodeRule]excludedProducts(before: String, after: String, first: Int, last: Int): ProductCountableConnection}@@ -4668,6 +4671,12 @@ enum ShippingMethodTypeEnum {WEIGHT}+type ShippingMethodZipCodeRule implements Node {+ start: String+ end: String+ id: ID!+}+type ShippingPriceBulkDelete {errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")count: Int!@@ -4725,6 +4734,29 @@ type ShippingPriceUpdate {shippingErrors: [ShippingError!]!}+type ShippingZipCodeRulesCreate {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ zipCodeRules: [ShippingMethodZipCodeRule]+ shippingMethod: ShippingMethod+ shippingErrors: [ShippingError!]!+}++input ShippingZipCodeRulesCreateInput {+ zipCodeRules: [ShippingZipCodeRulesCreateInputRange]!+}++input ShippingZipCodeRulesCreateInputRange {+ start: String!+ end: String+}++type ShippingZipCodeRulesDelete {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ shippingMethod: ShippingMethod+ shippingErrors: [ShippingError!]!+ shippingMethodZipCodeRule: ShippingMethodZipCodeRule+}+type ShippingZone implements Node & ObjectWithMetadata {id: ID!name: String!diff --git a/saleor/graphql/shipping/dataloaders.py b/saleor/graphql/shipping/dataloaders.pyindex 9fbccc59ca..d6848ac106 100644--- a/saleor/graphql/shipping/dataloaders.py+++ b/saleor/graphql/shipping/dataloaders.py@@ -2,7 +2,11 @@ from collections import defaultdictfrom django.db.models import F-from ...shipping.models import ShippingMethod, ShippingMethodChannelListing+from ...shipping.models import (+ ShippingMethod,+ ShippingMethodChannelListing,+ ShippingMethodZipCodeRule,+)from ..core.dataloaders import DataLoader@@ -30,6 +34,20 @@ class ShippingMethodsByShippingZoneIdLoader(DataLoader):]+class ZipCodeRulesByShippingMethodIdLoader(DataLoader):+ context_key = "zip_code_rules_by_shipping_method"++ def batch_load(self, keys):+ zip_code_rules = ShippingMethodZipCodeRule.objects.filter(+ shipping_method_id__in=keys+ )++ zip_code_rules_map = defaultdict(list)+ for zip_code in zip_code_rules:+ zip_code_rules_map[zip_code.shipping_method_id].append(zip_code)+ return [zip_code_rules_map[shipping_method_id] for shipping_method_id in keys]++class ShippingMethodsByShippingZoneIdAndChannelSlugLoader(DataLoader):context_key = "shippingmethod_by_shippingzone_and_channel"diff --git a/saleor/graphql/shipping/mutations/shippings.py b/saleor/graphql/shipping/mutations/shippings.pyindex ebdb532b65..8bb59fa52c 100644--- a/saleor/graphql/shipping/mutations/shippings.py+++ b/saleor/graphql/shipping/mutations/shippings.py@@ -18,7 +18,7 @@ from ...core.utils import get_duplicates_idsfrom ...product import types as product_typesfrom ...utils import resolve_global_ids_to_primary_keysfrom ..enums import ShippingMethodTypeEnum-from ..types import ShippingMethod, ShippingZone+from ..types import ShippingMethod, ShippingMethodZipCodeRule, ShippingZoneclass ShippingPriceInput(graphene.InputObjectType):@@ -161,6 +161,87 @@ class ShippingZoneUpdate(ShippingZoneMixin, ModelMutation):return response+class ShippingZipCodeRulesCreateInputRange(graphene.InputObjectType):+ start = graphene.String(required=True, description="Start range of the zip code.")+ end = graphene.String(required=False, description="End range of the zip code.")+++class ShippingZipCodeRulesCreateInput(graphene.InputObjectType):+ zip_code_rules = graphene.List(+ ShippingZipCodeRulesCreateInputRange,+ required=True,+ description="Zip code rules for shipping method.",+ )+++class ShippingZipCodeRulesCreate(BaseMutation):+ zip_code_rules = graphene.List(+ ShippingMethodZipCodeRule, description="A shipping method zip code range.",+ )+ shipping_method = graphene.Field(+ ShippingMethod, description="Related shipping method."+ )++ class Arguments:+ shipping_method_id = graphene.ID(+ required=True, description="ID of a shipping method to assign."+ )+ input = ShippingZipCodeRulesCreateInput(+ description="Fields required to create a shipping zip codes.", required=True+ )++ class Meta:+ description = "Create a new zip code exclusion range for shipping method."+ 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["shipping_method_id"], only_type=ShippingMethod+ )+ instances = []+ for zip_range in data["input"]["zip_code_rules"]:+ instance = models.ShippingMethodZipCodeRule.objects.create(+ shipping_method=shipping_method,+ start=zip_range["start"],+ end=zip_range.get("end"),+ )+ instances.append(instance)+ return ShippingZipCodeRulesCreate(+ zip_code_rules=instances,+ shipping_method=ChannelContext(node=shipping_method, channel_slug=None),+ )+++class ShippingZipCodeRulesDelete(ModelDeleteMutation):+ shipping_method = graphene.Field(+ ShippingMethod, description="Shipping method of deleted zip code rule."+ )++ class Arguments:+ id = graphene.ID(+ required=True, description="ID of a shipping method zip code to delete."+ )++ class Meta:+ description = "Deletes a shipping method zip code."+ model = models.ShippingMethodZipCodeRule+ permissions = (ShippingPermissions.MANAGE_SHIPPING,)+ error_type_class = ShippingError+ error_type_field = "shipping_errors"++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ instance = cls.get_instance(info, **data)+ shipping_method = instance.shipping_method+ super().perform_mutation(_root, info, **data)+ return ShippingZipCodeRulesDelete(+ shipping_method=ChannelContext(node=shipping_method, channel_slug=None)+ )++class ShippingZoneDelete(ModelDeleteMutation):class Arguments:id = graphene.ID(required=True, description="ID of a shipping zone to delete.")diff --git a/saleor/graphql/shipping/schema.py b/saleor/graphql/shipping/schema.pyindex 9f45458d64..3267db8846 100644--- a/saleor/graphql/shipping/schema.py+++ b/saleor/graphql/shipping/schema.py@@ -13,6 +13,8 @@ from .mutations.shippings import (ShippingPriceExcludeProducts,ShippingPriceRemoveProductFromExclude,ShippingPriceUpdate,+ ShippingZipCodeRulesCreate,+ ShippingZipCodeRulesDelete,ShippingZoneCreate,ShippingZoneDelete,ShippingZoneUpdate,@@ -52,6 +54,8 @@ class ShippingQueries(graphene.ObjectType):class ShippingMutations(graphene.ObjectType):shipping_method_channel_listing_update = ShippingMethodChannelListingUpdate.Field()+ shipping_method_zip_code_rules_create = ShippingZipCodeRulesCreate.Field()+ shipping_method_zip_code_rules_delete = ShippingZipCodeRulesDelete.Field()shipping_price_create = ShippingPriceCreate.Field()shipping_price_delete = ShippingPriceDelete.Field()shipping_price_bulk_delete = ShippingPriceBulkDelete.Field()diff --git a/saleor/graphql/shipping/tests/test_shipping_method.py b/saleor/graphql/shipping/tests/test_shipping_method.pyindex 7101153c27..8127020ed4 100644--- a/saleor/graphql/shipping/tests/test_shipping_method.py+++ b/saleor/graphql/shipping/tests/test_shipping_method.py@@ -15,6 +15,10 @@ SHIPPING_ZONE_QUERY = """shippingZone(id: $id, channel:$channel) {nameshippingMethods {+ zipCodeRules {+ start+ end+ }channelListings {idprice {@@ -54,6 +58,8 @@ def test_shipping_zone_query():# givenshipping = shipping_zone+ method = shipping.shipping_methods.first()+ code = method.zip_code_rules.create(start="HB2", end="HB6")query = SHIPPING_ZONE_QUERYID = graphene.Node.to_global_id("ShippingZone", shipping.id)variables = {"id": ID, "channel": channel_USD.slug}@@ -69,6 +75,9 @@ def test_shipping_zone_query(assert shipping_data["name"] == shipping.namenum_of_shipping_methods = shipping_zone.shipping_methods.count()assert len(shipping_data["shippingMethods"]) == num_of_shipping_methods+ assert shipping_data["shippingMethods"][0]["zipCodeRules"] == [+ {"start": code.start, "end": code.end}+ ]price_range = resolve_price_range(channel_slug=channel_USD.slug)data_price_range = shipping_data["priceRange"]assert data_price_range["start"]["amount"] == price_range.start.amount@@ -379,6 +388,104 @@ def test_create_duplicated_default_shipping_zone(assert data["shippingErrors"][0]["code"] == ShippingErrorCode.ALREADY_EXISTS.name+CREATE_SHIPPING_METHOD_ZIP_CODE_MUTATION = """+ mutation createZipCode(+ $shippingMethodId: ID!, $zipCodeRules: [ShippingZipCodeRulesCreateInputRange]!+ ){+ shippingMethodZipCodeRulesCreate(+ shippingMethodId: $shippingMethodId+ input: {+ zipCodeRules: $zipCodeRules+ }+ ){+ zipCodeRules {+ start+ end+ }+ shippingMethod {+ id+ name+ }+ shippingErrors {+ field+ code+ }+ }+ }+"""+++def test_create_shipping_method_zip_code(+ staff_api_client, shipping_method, permission_manage_shipping+):+ shipping_method_id = graphene.Node.to_global_id(+ "ShippingMethod", shipping_method.pk+ )+ zip_code_rules = [+ {"start": "HB3", "end": "HB6"},+ {"start": "HB8", "end": None},+ ]+ variables = {"shippingMethodId": shipping_method_id, "zipCodeRules": zip_code_rules}+ response = staff_api_client.post_graphql(+ CREATE_SHIPPING_METHOD_ZIP_CODE_MUTATION,+ variables,+ permissions=[permission_manage_shipping],+ )+ content = get_graphql_content(response)+ assert not content["data"]["shippingMethodZipCodeRulesCreate"]["shippingErrors"]+ zip_code_rules_data = content["data"]["shippingMethodZipCodeRulesCreate"][+ "zipCodeRules"+ ]+ shipping_method_data = content["data"]["shippingMethodZipCodeRulesCreate"][+ "shippingMethod"+ ]+ assert shipping_method_data["id"] == shipping_method_id+ assert shipping_method_data["name"] == shipping_method.name+ assert zip_code_rules_data == zip_code_rules+++DELETE_SHIPPING_METHOD_ZIP_CODE_MUTATION = """+ mutation deleteZipCode(+ $id: ID!+ ){+ shippingMethodZipCodeRulesDelete(+ id: $id+ ){+ shippingMethod {+ id+ name+ }+ shippingErrors {+ field+ code+ }+ }+ }+"""+++def test_delete_shipping_method_zip_code(+ staff_api_client, shipping_method_excldued_by_zip_code, permission_manage_shipping+):+ shipping_zip_code_id = graphene.Node.to_global_id(+ "ShippingMethodZipCodeRule",+ shipping_method_excldued_by_zip_code.zip_code_rules.first().id,+ )+ response = staff_api_client.post_graphql(+ DELETE_SHIPPING_METHOD_ZIP_CODE_MUTATION,+ {"id": shipping_zip_code_id},+ permissions=[permission_manage_shipping],+ )+ content = get_graphql_content(response)+ data = content["data"]["shippingMethodZipCodeRulesDelete"]+ assert data["shippingErrors"] == []+ assert data["shippingMethod"]["id"] == graphene.Node.to_global_id(+ "ShippingMethod", shipping_method_excldued_by_zip_code.id+ )+ assert data["shippingMethod"]["name"] == shipping_method_excldued_by_zip_code.name+ assert not shipping_method_excldued_by_zip_code.zip_code_rules.exists()++UPDATE_SHIPPING_ZONE_QUERY = """mutation updateShipping($id: ID!diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.pyindex 1f16daaec2..dfbe46f82b 100644--- a/saleor/graphql/shipping/types.py+++ b/saleor/graphql/shipping/types.py@@ -25,6 +25,7 @@ from .dataloaders import (ShippingMethodChannelListingByShippingMethodIdLoader,ShippingMethodsByShippingZoneIdAndChannelSlugLoader,ShippingMethodsByShippingZoneIdLoader,+ ZipCodeRulesByShippingMethodIdLoader,)from .enums import ShippingMethodTypeEnum@@ -47,6 +48,20 @@ class ShippingMethodChannelListing(CountableDjangoObjectType):return ChannelByIdLoader(info.context).load(root.channel_id)+class ShippingMethodZipCodeRule(CountableDjangoObjectType):+ start = graphene.String(description="Start address range.")+ end = graphene.String(description="End address range.")++ class Meta:+ description = "Represents shipping method zip code."+ interfaces = [relay.Node]+ model = models.ShippingMethodZipCodeRule+ only_fields = [+ "start",+ "end",+ ]++class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):type = ShippingMethodTypeEnum(description="Type of the shipping method.")translation = TranslationField(@@ -67,6 +82,10 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):minimum_order_price = graphene.Field(Money, description="The price of the cheapest variant (including discounts).")+ zip_code_rules = graphene.List(+ ShippingMethodZipCodeRule,+ description="Zip code exclude range of the shipping method.",+ )excluded_products = ChannelContextFilterConnectionField("saleor.graphql.product.types.products.Product",description="List of excluded products for the shipping method.",@@ -141,6 +160,12 @@ class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):):return convert_weight_to_default_weight_unit(root.node.maximum_order_weight)+ @staticmethod+ def resolve_zip_code_rules(+ root: ChannelContext[models.ShippingMethod], info, **_kwargs+ ):+ return ZipCodeRulesByShippingMethodIdLoader(info.context).load(root.node.id)+@staticmethoddef resolve_minimum_order_weight(root: ChannelContext[models.ShippingMethod], *_argsdiff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 219e1c8992..260195fdc3 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -309,7 +309,7 @@ def sum_order_totals(qs, currency_code):def get_valid_shipping_methods_for_order(order: Order):return ShippingMethod.objects.applicable_shipping_methods_for_instance(- order, channel_id=order.channel_id, price=order.get_subtotal().gross+ order, channel_id=order.channel_id, price=order.get_subtotal().gross,)diff --git a/saleor/shipping/migrations/0024_shippingmethodzipcoderule.py b/saleor/shipping/migrations/0024_shippingmethodzipcoderule.pynew file mode 100644index 0000000000..f066cd3a7b--- /dev/null+++ b/saleor/shipping/migrations/0024_shippingmethodzipcoderule.py@@ -0,0 +1,39 @@+# Generated by Django 3.1.3 on 2020-11-30 13:41++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("shipping", "0023_shippingmethod_excluded_products"),+ ]++ operations = [+ migrations.CreateModel(+ name="ShippingMethodZipCodeRule",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("start", models.CharField(max_length=32)),+ ("end", models.CharField(blank=True, max_length=32, null=True)),+ (+ "shipping_method",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="zip_code_rules",+ to="shipping.shippingmethod",+ ),+ ),+ ],+ options={"unique_together": {("shipping_method", "start", "end")},}, # noqa+ ),+ ]diff --git a/saleor/shipping/models.py b/saleor/shipping/models.pyindex d8a6ebdc72..6273a6ac40 100644--- a/saleor/shipping/models.py+++ b/saleor/shipping/models.py@@ -20,6 +20,7 @@ from ..core.weight import (zero_weight,)from . import ShippingMethodType+from .zip_codes import check_shipping_method_for_zip_codeif TYPE_CHECKING:# flake8: noqa@@ -142,13 +143,22 @@ class ShippingMethodQueryset(models.QuerySet):return Nonelines = instance.lines.prefetch_related("variant__product").all()instance_product_ids = set(lines.values_list("variant__product", flat=True))- return self.applicable_shipping_methods(++ applicable_methods = 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,- )+ ).prefetch_related("zip_code_rules")++ excluded_methods_by_zip_code = []+ for method in applicable_methods:+ if check_shipping_method_for_zip_code(instance.shipping_address, method):+ excluded_methods_by_zip_code.append(method.pk)+ if excluded_methods_by_zip_code:+ return applicable_methods.exclude(pk__in=excluded_methods_by_zip_code)+ return applicable_methodsclass ShippingMethod(ModelWithMetadata):@@ -191,6 +201,17 @@ class ShippingMethod(ModelWithMetadata):)+class ShippingMethodZipCodeRule(models.Model):+ shipping_method = models.ForeignKey(+ ShippingMethod, on_delete=models.CASCADE, related_name="zip_code_rules"+ )+ start = models.CharField(max_length=32)+ end = models.CharField(max_length=32, blank=True, null=True)++ class Meta:+ unique_together = ("shipping_method", "start", "end")++class ShippingMethodChannelListing(models.Model):shipping_method = models.ForeignKey(ShippingMethod,diff --git a/saleor/shipping/tests/test_zip_codes.py b/saleor/shipping/tests/test_zip_codes.pynew file mode 100644index 0000000000..50aeb755a2--- /dev/null+++ b/saleor/shipping/tests/test_zip_codes.py@@ -0,0 +1,62 @@+import pytest++from ..zip_codes import check_zip_code_in_excluded_range+++ "code, start, end, in_range",+ [+ ["BH3 2BC", "BH2 1AA", "BH4 9ZZ", True],+ ["BH20 2BC", "BH2 1AA", "BH4 9ZZ", False],+ ["BH16 7HF", "BH16 7HA", "BH16 7HG", True],+ ["BH16 7HA", "BH16 7HA", "BH16 7HB", True],+ ["BH17 7HF", "BH16 7HA", "BH17 7HG", True],+ ["BH15 7HF", "BH10 7HA", "BH20 7HG", True],+ ["BH16 7HF", "BH16 7HA", None, True],+ ["BH16 7HA", "BH16 7HA", None, True],+ ["BH16 7HZ", "BH16 7HA", "BH16 7HG", False],+ ["BH16 7HB", "BH16 7HC", "BH16 7HD", False],+ ["BH16 7HB", "BH16 7HC", None, False],+ ],+)+def test_check_zip_code_for_uk(code, start, end, in_range):+ assert check_zip_code_in_excluded_range("GB", code, start, end) is in_range+++ "code, start, end, in_range",+ [+ ["IM16 7HF", "IM16 7HA", "IM16 7HG", True], # Isle of Man+ ["IM16 7HZ", "IM16 7HA", "IM16 7HG", False],+ ["GY16 7HF", "GY16 7HA", "GY16 7HG", True], # Jersey+ ["GY16 7HZ", "GY16 7HA", "GY16 7HG", False],+ ["GG16 7HF", "GG16 7HA", "GG16 7HG", True], # Guernsey+ ["GG16 7HZ", "GG16 7HA", "GG16 7HG", False],+ ],+)+def test_check_zip_code_for_uk_fallbacks(code, start, end, in_range):+ assert check_zip_code_in_excluded_range("GB", code, start, end) is in_range+++ "code, start, end, in_range",+ [+ ["A65 2F0A", "A65 2F0A", "A65 2F0A", True],+ ["A65 2F0B", "A65 2F0A", "A65 2F0C", True],+ ["A65 2F0B", "A65 2F0C", "A65 2F0D", False],+ ],+)+def test_check_zip_code_for_ireland(code, start, end, in_range):+ assert check_zip_code_in_excluded_range("IR", code, start, end) is in_range+++ "code, start, end, in_range",+ [+ ["64-620", "50-000", "65-000", True],+ ["64-620", "64-200", "64-650", True],+ ["64-620", "63-200", "63-650", False],+ ],+)+def test_check_zip_code_for_other_countries(code, start, end, in_range):+ assert check_zip_code_in_excluded_range("PL", code, start, end) is in_rangediff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.pyindex 5ffc1c5060..8e7f909872 100644--- a/saleor/shipping/utils.py+++ b/saleor/shipping/utils.py@@ -1,14 +1,16 @@from django_countries import countries-from .models import ShippingZone-def default_shipping_zone_exists(zone_pk=None):+ from .models import ShippingZone+return ShippingZone.objects.exclude(pk=zone_pk).filter(default=True)def get_countries_without_shipping_zone():"""Return countries that are not assigned to any shipping zone."""+ from .models import ShippingZone+covered_countries = set()for zone in ShippingZone.objects.all():covered_countries.update({c.code for c in zone.countries})diff --git a/saleor/shipping/zip_codes.py b/saleor/shipping/zip_codes.pynew file mode 100644index 0000000000..914b430a83--- /dev/null+++ b/saleor/shipping/zip_codes.py@@ -0,0 +1,88 @@+import re+++def group_values(pattern, *values):+ result = []+ for value in values:+ try:+ val = re.match(pattern, value)+ except TypeError:+ result.append(None)+ else:+ result.append(val.groups() if val else None)+ return result+++def cast_tuple_index_to_type(index, target_type, *tuples):+ """Cast tuple index to type.++ Return list of tuples same as received but with index item casted to+ tagret_type.+ """+ result = []+ for _tuple in tuples:+ to_result = []+ try:+ for i, entry in enumerate(_tuple):+ to_result.append(entry if i != index else target_type(entry))+ except TypeError:+ pass+ result.append(tuple(to_result))+ return result+++def compare_values(code, start, end):+ if not code or not start:+ return False+ if not end:+ return start <= code+ return start <= code <= end+++def check_uk_zip_code(code, start, end):+ """Check zip code for uk, split the code by regex.++ Example zip codes: BH20 2BC (UK), IM16 7HF (Isle of Man).+ """+ pattern = r"^([A-Z]{1,2})([0-9]+)([A-Z]?) ?([0-9][A-Z]{2})$"+ code, start, end = group_values(pattern, code, start, end)+ # replace second item of each tuple with it's value casted to int+ code, start, end = cast_tuple_index_to_type(1, int, code, start, end)+ return compare_values(code, start, end)+++def check_irish_zip_code(code, start, end):+ """Check zip code for Ireland, split the code by regex.++ Example zip codes: A65 2F0A, A61 2F0G.+ """+ pattern = r"([\dA-Z]{3}) ?([\dA-Z]{4})"+ code, start, end = group_values(pattern, code, start, end)+ return compare_values(code, start, end)+++def check_any_zip_code(code, start, end):+ """Fallback for any country not present in country_func_map.++ Perform simple lexicographical comparison without splitting to sections.+ """+ return compare_values(code, start, end)+++def check_zip_code_in_excluded_range(country, code, start, end):+ country_func_map = {+ "GB": check_uk_zip_code, # United Kingdom+ "IR": check_irish_zip_code, # Ireland+ }+ return country_func_map.get(country, check_any_zip_code)(code, start, end)+++def check_shipping_method_for_zip_code(customer_shipping_address, method):+ country = customer_shipping_address.country.code+ postal_code = customer_shipping_address.postal_code+ for zip_code in method.zip_code_rules.all():+ if check_zip_code_in_excluded_range(+ country, postal_code, zip_code.start, zip_code.end+ ):+ return True+ return Falsediff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 52a0e2070d..f8bb89fc54 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -695,6 +695,12 @@ def shipping_method(shipping_zone, channel_USD):return method+def shipping_method_excldued_by_zip_code(shipping_method):+ shipping_method.zip_code_rules.create(start="HB2", end="HB6")+ return shipping_method++@pytest.fixturedef shipping_method_channel_PLN(shipping_zone, channel_PLN):method = ShippingMethod.objects.create(