Skip to content

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

Sync webhooks for filtering shipping methods (port to 3.1) (#8970)

Krzysztof Kuligdf7dde7d7fba
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 728e348494..6ce4e8ad1e 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -20,7 +20,10 @@ from ..discount import DiscountInfo, VoucherType
from ..discount.utils import fetch_active_discounts
from ..shipping.interface import ShippingMethodData
from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
-from ..shipping.utils import convert_to_shipping_method_data
+from ..shipping.utils import (
+ convert_to_shipping_method_data,
+ initialize_shipping_method_active_status,
+)
from ..warehouse import WarehouseClickAndCollectOption
from ..warehouse.models import Warehouse
@@ -522,8 +525,10 @@ def update_delivery_method_lists_for_checkout_info(
Availability of shipping methods according to plugins is indicated
by the `active` field.
"""
- checkout_info.all_shipping_methods = SimpleLazyObject(
- lambda: list(
+
+ def _resolve_all_shipping_methods():
+ # Fetch all shipping method from all sources, including sync webhooks
+ all_methods = list(
itertools.chain(
get_valid_internal_shipping_method_list_for_checkout_info(
checkout_info,
@@ -538,6 +543,15 @@ def update_delivery_method_lists_for_checkout_info(
),
)
)
+ # Filter shipping methods using sync webhooks
+ excluded_methods = manager.excluded_shipping_methods_for_checkout(
+ checkout_info.checkout, all_methods
+ )
+ initialize_shipping_method_active_status(all_methods, excluded_methods)
+ return all_methods
+
+ checkout_info.all_shipping_methods = SimpleLazyObject(
+ _resolve_all_shipping_methods
) # type: ignore
checkout_info.valid_pick_up_points = SimpleLazyObject(
lambda: (
diff --git a/saleor/core/tests/test_serializer.py b/saleor/core/tests/test_serializer.py
new file mode 100644
index 0000000000..a85abedbb8
--- /dev/null
+++ b/saleor/core/tests/test_serializer.py
@@ -0,0 +1,33 @@
+import json
+
+from measurement.measures import Weight
+
+from ..taxes import zero_money
+from ..utils.json_serializer import CustomJsonEncoder
+
+
+def test_custom_json_encoder_dumps_money_objects():
+ # given
+ currency = "usd"
+ input = {"money": zero_money(currency)}
+
+ # when
+ serialized_data = json.dumps(input, cls=CustomJsonEncoder)
+
+ # then
+ data = json.loads(serialized_data)
+ assert data["money"]["_type"] == "Money"
+ assert data["money"]["amount"] == "0"
+ assert data["money"]["currency"] == currency
+
+
+def test_custom_json_encoder_dumps_weight_objects():
+ # given
+ input = {"weight": Weight(kg=5)}
+
+ # when
+ serialized_data = json.dumps(input, cls=CustomJsonEncoder)
+
+ # then
+ data = json.loads(serialized_data)
+ assert data["weight"] == "5.0:kg"
diff --git a/saleor/core/utils/json_serializer.py b/saleor/core/utils/json_serializer.py
index a558f32573..0fae131e7c 100644
--- a/saleor/core/utils/json_serializer.py
+++ b/saleor/core/utils/json_serializer.py
@@ -1,6 +1,7 @@
from django.core.serializers.json import DjangoJSONEncoder
from django.core.serializers.json import Serializer as JsonSerializer
from draftjs_sanitizer import SafeJSONEncoder
+from measurement.measures import Weight
from prices import Money
MONEY_TYPE = "Money"
@@ -16,6 +17,9 @@ class CustomJsonEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, Money):
return {"_type": MONEY_TYPE, "amount": obj.amount, "currency": obj.currency}
+ # Mirror implementation of django_measurement.MeasurementField.value_to_string
+ if isinstance(obj, Weight):
+ return "%s:%s" % (obj.value, obj.unit)
return super().default(obj)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 9c26ca613a..dc48693131 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -38,6 +38,7 @@ from ....checkout.utils import (
from ....core.payments import PaymentInterface
from ....payment import TransactionKind
from ....payment.interface import GatewayResponse
+from ....plugins.base_plugin import ExcludedShippingMethod
from ....plugins.manager import get_plugins_manager
from ....plugins.tests.sample_plugins import ActiveDummyPaymentGateway
from ....product.models import ProductChannelListing, ProductVariant
@@ -279,7 +280,6 @@ def test_checkout_create_with_inactive_channel(
def test_checkout_create_with_zero_quantity(
api_client, stock, graphql_address_data, channel_USD
):
-
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
test_email = "[email protected]"
@@ -304,7 +304,6 @@ def test_checkout_create_with_zero_quantity(
def test_checkout_create_with_unavailable_variant(
api_client, stock, graphql_address_data, channel_USD
):
-
variant = stock.product_variant
variant.channel_listings.filter(channel=channel_USD).update(price_amount=None)
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -2149,7 +2148,6 @@ def test_available_collection_points_for_preorders_and_regular_variants_in_check
checkout_with_preorders_and_regular_variant,
warehouses_for_cc,
):
-
expected_collection_points = [{"name": warehouses_for_cc[1].name}]
response = staff_api_client.post_graphql(
QUERY_GET_ALL_COLLECTION_POINTS_FROM_CHECKOUT,
@@ -3002,6 +3000,32 @@ def test_checkout_shipping_address_update_without_phone_country_prefix(
assert not data["errors"]
+ "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"
+)
+def test_checkout_shipping_address_update_exclude_shipping_method(
+ mocked_webhook,
+ user_api_client,
+ checkout_with_items_and_shipping,
+ graphql_address_data,
+ settings,
+):
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ checkout = checkout_with_items_and_shipping
+ shipping_method = checkout.shipping_method
+ assert shipping_method is not None
+ webhook_reason = "hello-there"
+ mocked_webhook.return_value = [
+ ExcludedShippingMethod(shipping_method.id, webhook_reason)
+ ]
+ shipping_address = graphql_address_data
+ variables = {"token": checkout.token, "shippingAddress": shipping_address}
+
+ user_api_client.post_graphql(MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables)
+ checkout.refresh_from_db()
+ assert checkout.shipping_method is None
+
+
def test_checkout_billing_address_update(
user_api_client, checkout_with_item, graphql_address_data
):
@@ -3131,7 +3155,6 @@ TRANSACTION_CONFIRM_GATEWAY_RESPONSE = GatewayResponse(
error=None,
)
-
QUERY_CHECKOUT_USER_ID = """
query getCheckout($token: UUID!) {
checkout(token: $token) {
@@ -3758,6 +3781,43 @@ def test_checkout_delivery_method_with_empty_fields_results_None(
assert checkout.collection_point is None
+ "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"
+)
+def test_checkout_shipping_method_update_excluded_webhook(
+ mocked_webhook,
+ staff_api_client,
+ shipping_method,
+ checkout_with_item,
+ address,
+):
+ # given
+ webhook_reason = "spanish-inquisition"
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.save(update_fields=["shipping_address"])
+ query = MUTATION_UPDATE_SHIPPING_METHOD
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ mocked_webhook.return_value = [
+ ExcludedShippingMethod(shipping_method.id, webhook_reason)
+ ]
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, {"token": checkout_with_item.token, "shippingMethodId": method_id}
+ )
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+
+ checkout.refresh_from_db()
+
+ # then
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "shippingMethod"
+ assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
+ assert checkout.shipping_method is None
+
+
# Deprecated
@patch("saleor.shipping.postal_codes.is_shipping_method_applicable_for_postal_code")
def test_checkout_shipping_method_update_excluded_postal_code(
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index f9b913d56e..01de5d7525 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -321,7 +321,11 @@ class Checkout(ModelObjectType):
@classmethod
@traced_resolver
def resolve_shipping_methods(cls, root: models.Checkout, info):
- return cls.resolve_available_shipping_methods(root, info)
+ return (
+ CheckoutInfoByCheckoutTokenLoader(info.context)
+ .load(root.token)
+ .then(lambda checkout_info: checkout_info.all_shipping_methods)
+ )
@staticmethod
def resolve_delivery_method(root: models.Checkout, info):
@@ -437,19 +441,10 @@ class Checkout(ModelObjectType):
@staticmethod
@traced_resolver
def resolve_available_shipping_methods(root: models.Checkout, info):
- channel = ChannelByIdLoader(info.context).load(root.channel_id)
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token)
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(root.token)
- discounts = DiscountsByDateTimeLoader(info.context).load(
- info.context.request_time
- )
-
- def calculate_available_shipping_methods(data):
- lines, checkout_info, discounts, channel = data
- return checkout_info.valid_shipping_methods
-
- return Promise.all([lines, checkout_info, discounts, channel]).then(
- calculate_available_shipping_methods
+ return (
+ CheckoutInfoByCheckoutTokenLoader(info.context)
+ .load(root.token)
+ .then(lambda checkout_info: checkout_info.valid_shipping_methods)
)
@staticmethod
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 161b126482..771affe78f 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -456,7 +456,7 @@ class DraftOrderComplete(BaseMutation):
cls.validate_order(order)
country = get_order_country(order)
- validate_draft_order(order, country)
+ validate_draft_order(order, country, info.context.plugins)
cls.update_user_fields(order)
order.status = OrderStatus.UNFULFILLED
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index d524426be1..ab5bf02af4 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -29,11 +29,11 @@ from ....order.utils import (
add_variant_to_order,
change_order_line_quantity,
delete_order_line,
- get_valid_shipping_methods_for_order,
recalculate_order,
update_order_prices,
)
from ....payment import PaymentError, TransactionKind, gateway
+from ....plugins.manager import PluginsManager
from ....shipping import models as shipping_models
from ....shipping.interface import ShippingMethodData
from ....shipping.utils import convert_to_shipping_method_data
@@ -51,6 +51,7 @@ from ...product.types import ProductVariant
from ...shipping.types import ShippingMethod
from ..types import Order, OrderEvent, OrderLine
from ..utils import (
+ get_shipping_method_availability_error,
validate_product_is_published_in_channel,
validate_variant_channel_listings,
)
@@ -58,7 +59,9 @@ from ..utils import (
ORDER_EDITABLE_STATUS = (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED)
-def clean_order_update_shipping(order, method: ShippingMethodData):
+def clean_order_update_shipping(
+ order, method: ShippingMethodData, manager: "PluginsManager"
+):
if not order.shipping_address:
raise ValidationError(
{
@@ -70,21 +73,9 @@ def clean_order_update_shipping(order, method: ShippingMethodData):
}
)
- valid_methods_ids = {
- method.id
- for method in get_valid_shipping_methods_for_order(
- order, order.channel.shipping_method_listings.all()
- )
- }
- if valid_methods_ids is None or method.id not in valid_methods_ids:
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "Shipping method cannot be used with this order.",
- code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
- )
- }
- )
+ error = get_shipping_method_availability_error(order, method, manager)
+ if error:
+ raise ValidationError({"shipping_method": error})
def clean_order_cancel(order):
@@ -389,7 +380,7 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
method,
shipping_channel_listing,
)
- clean_order_update_shipping(order, shipping_method_data)
+ clean_order_update_shipping(order, shipping_method_data, info.context.plugins)
order.shipping_method = method
shipping_price = info.context.plugins.calculate_order_shipping(order)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 0b463fadce..d00301706a 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -37,7 +37,8 @@ from ....order.search import (
)
from ....payment import ChargeStatus, PaymentError
from ....payment.models import Payment
-from ....plugins.manager import PluginsManager
+from ....plugins.base_plugin import ExcludedShippingMethod
+from ....plugins.manager import PluginsManager, get_plugins_manager
from ....product.models import ProductVariant, ProductVariantChannelListing
from ....shipping.models import ShippingMethod, ShippingMethodChannelListing
from ....warehouse.models import Allocation, PreorderAllocation, Stock, Warehouse
@@ -3120,14 +3121,14 @@ def test_can_finalize_order_product_available_for_purchase_from_tomorrow(
def test_validate_draft_order(draft_order):
# should not raise any errors
- assert validate_draft_order(draft_order, "US") is None
+ assert validate_draft_order(draft_order, "US", get_plugins_manager()) is None
def test_validate_draft_order_without_sku(draft_order):
ProductVariant.objects.update(sku=None)
draft_order.lines.update(product_sku=None)
# should not raise any errors
- assert validate_draft_order(draft_order, "US") is None
+ assert validate_draft_order(draft_order, "US", get_plugins_manager()) is None
def test_validate_draft_order_wrong_shipping(draft_order):
@@ -3137,7 +3138,7 @@ def test_validate_draft_order_wrong_shipping(draft_order):
shipping_zone.save()
assert order.shipping_address.country.code not in shipping_zone.countries
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
msg = "Shipping method is not valid for chosen shipping address"
assert e.value.error_dict["shipping"][0].message == msg
@@ -3145,7 +3146,7 @@ def test_validate_draft_order_wrong_shipping(draft_order):
def test_validate_draft_order_no_order_lines(order, shipping_method):
order.shipping_method = shipping_method
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
msg = "Could not create order without any products."
assert e.value.error_dict["lines"][0].message == msg
@@ -3159,7 +3160,7 @@ def test_validate_draft_order_non_existing_variant(draft_order):
assert line.variant is None
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
msg = "Could not create orders with non-existing products."
assert e.value.error_dict["lines"][0].message == msg
@@ -3174,7 +3175,7 @@ def test_validate_draft_order_with_unpublished_product(draft_order):
line.refresh_from_db()
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
msg = "Can't finalize draft with unpublished product."
error = e.value.error_dict["lines"][0]
@@ -3190,7 +3191,7 @@ def test_validate_draft_order_with_unavailable_for_purchase_product(draft_order)
line.refresh_from_db()
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
msg = "Can't finalize draft with product unavailable for purchase."
error = e.value.error_dict["lines"][0]
@@ -3210,7 +3211,7 @@ def test_validate_draft_order_with_product_available_for_purchase_in_future(
line.refresh_from_db()
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
msg = "Can't finalize draft with product unavailable for purchase."
error = e.value.error_dict["lines"][0]
@@ -3228,7 +3229,7 @@ def test_validate_draft_order_out_of_stock_variant(draft_order):
stock.save(update_fields=["quantity"])
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
msg = "Insufficient product stock: SKU_AA"
assert e.value.error_dict["lines"][0].message == msg
@@ -3238,7 +3239,7 @@ def test_validate_draft_order_no_shipping_address(draft_order):
order.shipping_address = None
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
error = e.value.error_dict["order"][0]
assert error.message == "Can't finalize draft with no shipping address."
assert error.code == OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value
@@ -3249,7 +3250,7 @@ def test_validate_draft_order_no_billing_address(draft_order):
order.billing_address = None
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
error = e.value.error_dict["order"][0]
assert error.message == "Can't finalize draft with no billing address."
assert error.code == OrderErrorCode.BILLING_ADDRESS_NOT_SET.value
@@ -3260,7 +3261,7 @@ def test_validate_draft_order_no_shipping_method(draft_order):
order.shipping_method = None
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US")
+ validate_draft_order(order, "US", get_plugins_manager())
error = e.value.error_dict["shipping"][0]
assert error.message == "Shipping method is required."
assert error.code == OrderErrorCode.SHIPPING_METHOD_REQUIRED.value
@@ -3272,7 +3273,7 @@ def test_validate_draft_order_no_shipping_method_shipping_not_required(draft_ord
required_mock = Mock(return_value=False)
order.is_shipping_required = required_mock
- assert validate_draft_order(order, "US") is None
+ assert validate_draft_order(order, "US", get_plugins_manager()) is None
def test_validate_draft_order_no_shipping_address_no_method_shipping_not_required(
@@ -3284,7 +3285,7 @@ def test_validate_draft_order_no_shipping_address_no_method_shipping_not_require
required_mock = Mock(return_value=False)
order.is_shipping_required = required_mock
- assert validate_draft_order(order, "US") is None
+ assert validate_draft_order(order, "US", get_plugins_manager()) is None
DRAFT_ORDER_COMPLETE_MUTATION = """
@@ -3293,6 +3294,7 @@ DRAFT_ORDER_COMPLETE_MUTATION = """
errors {
field
code
+ message
variants
}
order {
@@ -3644,6 +3646,69 @@ def test_draft_order_complete_not_available_shipping_method(
assert {error["field"] for error in data["errors"]} == {"shipping", "lines"}
[email protected]("saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_order")
+def test_draft_order_complete_with_excluded_shipping_method(
+ mocked_webhook,
+ draft_order,
+ shipping_method,
+ staff_api_client,
+ permission_manage_orders,
+ settings,
+):
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ webhook_reason = "archives-are-incomplete"
+ mocked_webhook.return_value = [
+ ExcludedShippingMethod(str(shipping_method.id), webhook_reason)
+ ]
+ order = draft_order
+ order.status = OrderStatus.DRAFT
+ order.shipping_method = shipping_method
+ order.save()
+ query = DRAFT_ORDER_COMPLETE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderComplete"]
+ assert (
+ data["errors"][0]["code"] == OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
+ )
+ assert data["errors"][0]["field"] == "shipping"
+
+
[email protected]("saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_order")
+def test_draft_order_complete_with_not_excluded_shipping_method(
+ mocked_webhook,
+ draft_order,
+ shipping_method,
+ staff_api_client,
+ permission_manage_orders,
+ settings,
+):
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ webhook_reason = "archives-are-incomplete"
+ other_shipping_method_id = "1337"
+ assert other_shipping_method_id != shipping_method.id
+ mocked_webhook.return_value = [
+ ExcludedShippingMethod(other_shipping_method_id, webhook_reason)
+ ]
+ order = draft_order
+ order.status = OrderStatus.DRAFT
+ order.shipping_method = shipping_method
+ order.save()
+ query = DRAFT_ORDER_COMPLETE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderComplete"]
+ assert len(data["errors"]) == 0
+
+
def test_draft_order_complete_out_of_stock_variant(
staff_api_client, permission_manage_orders, staff_user, draft_order
):
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index cf833d1a57..43e8d755e7 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1026,11 +1026,11 @@ class Order(ModelObjectType):
@staticmethod
@traced_resolver
- def resolve_can_finalize(root: models.Order, _info):
+ def resolve_can_finalize(root: models.Order, info):
if root.status == OrderStatus.DRAFT:
country = get_order_country(root)
try:
- validate_draft_order(root, country)
+ validate_draft_order(root, country, info.context.plugins)
except ValidationError:
return False
return True
@@ -1125,7 +1125,9 @@ class Order(ModelObjectType):
def resolve_shipping_methods(cls, root: models.Order, info):
def with_channel(channel):
def with_listings(channel_listings):
- return get_valid_shipping_methods_for_order(root, channel_listings)
+ return get_valid_shipping_methods_for_order(
+ root, channel_listings, info.context.plugins
+ )
return (
ShippingMethodChannelListingByChannelSlugLoader(info.context)
@@ -1195,11 +1197,11 @@ class Order(ModelObjectType):
return graphene.Node.to_global_id("Order", root.original_id)
@traced_resolver
- def resolve_errors(root, _info, **_kwargs):
+ def resolve_errors(root, info, **_kwargs):
if root.status == OrderStatus.DRAFT:
country = get_order_country(root)
try:
- validate_draft_order(root, country)
+ validate_draft_order(root, country, info.context.plugins)
except ValidationError as e:
return validation_error_to_error_type(e, OrderError)
return []
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index ec79aebcad..d0fa901147 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -1,12 +1,16 @@
from collections import defaultdict
-from typing import TYPE_CHECKING, Dict, Iterable, List
+from typing import TYPE_CHECKING, Dict, Iterable, List, Optional
import graphene
from django.core.exceptions import ValidationError
from ...core.exceptions import InsufficientStock
from ...order.error_codes import OrderErrorCode
+from ...order.utils import get_valid_shipping_methods_for_order
+from ...plugins.manager import PluginsManager
from ...product.models import Product, ProductChannelListing, ProductVariant
+from ...shipping.interface import ShippingMethodData
+from ...shipping.utils import convert_to_shipping_method_data
from ...warehouse.availability import check_stock_and_preorder_quantity
from ..core.validators import validate_variants_available_in_channel
@@ -27,8 +31,36 @@ def validate_total_quantity(order: "Order", errors: T_ERRORS):
)
-def validate_shipping_method(order: "Order", errors: T_ERRORS):
- error = None
+def get_shipping_method_availability_error(
+ order: "Order",
+ method: Optional["ShippingMethodData"],
+ manager: "PluginsManager",
+):
+ """Validate whether shipping method is still available for the order."""
+ if method:
+ valid_methods_ids = {
+ m.id
+ for m in get_valid_shipping_methods_for_order(
+ order,
+ order.channel.shipping_method_listings.all(),
+ manager,
+ )
+ if m.active
+ }
+ is_valid = method.id in valid_methods_ids
+ else:
+ is_valid = False
+
+ if not is_valid:
+ return ValidationError(
+ "Shipping method cannot be used with this order.",
+ code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
+ )
+
+
+def validate_shipping_method(
+ order: "Order", errors: T_ERRORS, manager: "PluginsManager"
+):
if not order.shipping_method:
error = ValidationError(
"Shipping method is required.",
@@ -48,6 +80,18 @@ def validate_shipping_method(order: "Order", errors: T_ERRORS):
"Shipping method not available in given channel.",
code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
)
+ else:
+ error = get_shipping_method_availability_error(
+ order,
+ convert_to_shipping_method_data(
+ order.shipping_method,
+ order.channel.shipping_method_listings.filter(
+ shipping_method=order.shipping_method
+ ).last(),
+ ),
+ manager,
+ )
+
if error:
errors["shipping"].append(error)
@@ -205,7 +249,7 @@ def validate_channel_is_active(channel: "Channel", errors: T_ERRORS):
)
-def validate_draft_order(order: "Order", country: str):
+def validate_draft_order(order: "Order", country: str, manager: "PluginsManager"):
"""Check if the given order contains the proper data.
- Has proper customer data,
@@ -220,7 +264,7 @@ def validate_draft_order(order: "Order", country: str):
validate_billing_address(order, errors)
if order.is_shipping_required():
validate_shipping_address(order, errors)
- validate_shipping_method(order, errors)
+ validate_shipping_method(order, errors, manager)
validate_total_quantity(order, errors)
validate_order_lines(order, country, errors)
validate_channel_is_active(order.channel, errors)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 288323bbf2..30816781a6 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -7580,6 +7580,8 @@ enum WebhookEventTypeEnum {
PAYMENT_REFUND
PAYMENT_VOID
SHIPPING_LIST_METHODS_FOR_CHECKOUT
+ ORDER_FILTER_SHIPPING_METHODS
+ CHECKOUT_FILTER_SHIPPING_METHODS
}
enum WebhookEventTypeSyncEnum {
@@ -7591,6 +7593,8 @@ enum WebhookEventTypeSyncEnum {
PAYMENT_REFUND
PAYMENT_VOID
SHIPPING_LIST_METHODS_FOR_CHECKOUT
+ ORDER_FILTER_SHIPPING_METHODS
+ CHECKOUT_FILTER_SHIPPING_METHODS
}
enum WebhookSampleEventTypeEnum {
diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.py
index a1622dab05..0791dfbdab 100644
--- a/saleor/graphql/shipping/types.py
+++ b/saleor/graphql/shipping/types.py
@@ -345,17 +345,13 @@ class ShippingMethod(graphene.ObjectType):
class Meta:
interfaces = [relay.Node, ObjectWithMetadata]
description = (
- (
- "Shipping methods that can be used as means of shipping"
- "for orders and checkouts."
- ),
+ "Shipping methods that can be used as means of shipping"
+ "for orders and checkouts."
)
@staticmethod
def resolve_id(root: ShippingMethodData, _info):
- if root.is_external:
- return root.id
- return graphene.Node.to_global_id("ShippingMethod", root.id)
+ return root.graphql_id
@staticmethod
def resolve_maximum_order_weight(root: ShippingMethodData, *_args):
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index f89fa795ec..e7e3019f8d 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -175,7 +175,7 @@ def test_get_valid_shipping_methods_for_order(order_line_with_one_allocation, ad
# when
valid_shipping_methods = get_valid_shipping_methods_for_order(
- order, order.channel.shipping_method_listings.all()
+ order, order.channel.shipping_method_listings.all(), get_plugins_manager()
)
# then
@@ -197,7 +197,7 @@ def test_get_valid_shipping_methods_for_order_no_channel_shipping_zones(
# when
valid_shipping_methods = get_valid_shipping_methods_for_order(
- order, order.channel.shipping_method_listings.all()
+ order, order.channel.shipping_method_listings.all(), get_plugins_manager()
)
# then
@@ -216,7 +216,7 @@ def test_get_valid_shipping_methods_for_order_no_shipping_address(
# when
valid_shipping_methods = get_valid_shipping_methods_for_order(
- order, order.channel.shipping_method_listings.all()
+ order, order.channel.shipping_method_listings.all(), get_plugins_manager()
)
# then
@@ -237,7 +237,7 @@ def test_get_valid_shipping_methods_for_order_shipping_not_required(
# when
valid_shipping_methods = get_valid_shipping_methods_for_order(
- order, order.channel.shipping_method_listings.all()
+ order, order.channel.shipping_method_listings.all(), get_plugins_manager()
)
# then
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 8a4642857d..b6a35263c3 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -27,7 +27,10 @@ from ..order.models import Order, OrderLine
from ..product.utils.digital_products import get_default_digital_content_settings
from ..shipping.interface import ShippingMethodData
from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
-from ..shipping.utils import convert_to_shipping_method_data
+from ..shipping.utils import (
+ convert_to_shipping_method_data,
+ initialize_shipping_method_active_status,
+)
from ..warehouse.management import (
decrease_allocations,
get_order_lines_with_track_inventory,
@@ -653,7 +656,9 @@ def sum_order_totals(qs, currency_code):
def get_valid_shipping_methods_for_order(
- order: Order, shipping_channel_listings: Iterable["ShippingMethodChannelListing"]
+ order: Order,
+ shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
+ manager: "PluginsManager",
) -> List[ShippingMethodData]:
"""Return a list of shipping methods according to Saleor's own business logic.
@@ -684,6 +689,9 @@ def get_valid_shipping_methods_for_order(
if shipping_method_data:
valid_methods.append(shipping_method_data)
+ excluded_methods = manager.excluded_shipping_methods_for_order(order, valid_methods)
+ initialize_shipping_method_active_status(valid_methods, excluded_methods)
+
return valid_methods
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index b7cd124aca..7a4fbbbb72 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -71,6 +71,12 @@ class ExternalAccessTokens:
user: Optional["User"] = None
+@dataclass
+class ExcludedShippingMethod:
+ id: str
+ reason: Optional[str]
+
+
class BasePlugin:
"""Abstract class for storing all methods available for any plugin.
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 3d190fc544..10d758b0bc 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -30,7 +30,7 @@ from ..core.prices import quantize_price
from ..core.taxes import TaxType, zero_taxed_money
from ..discount import DiscountInfo
from ..order.interface import OrderTaxedPricesData
-from .base_plugin import ExternalAccessTokens
+from .base_plugin import ExcludedShippingMethod, ExternalAccessTokens
from .models import PluginConfiguration
if TYPE_CHECKING:
@@ -57,7 +57,6 @@ if TYPE_CHECKING:
from ..warehouse.models import Stock
from .base_plugin import BasePlugin
-
NotifyEventTypeChoice = str
@@ -1174,6 +1173,30 @@ class PluginsManager(PaymentInterface):
plugin, "external_verify", default_value, data, request
)
+ def excluded_shipping_methods_for_order(
+ self,
+ order: "Order",
+ available_shipping_methods: List["ShippingMethodData"],
+ ) -> List[ExcludedShippingMethod]:
+ return self.__run_method_on_plugins(
+ "excluded_shipping_methods_for_order",
+ [],
+ order,
+ available_shipping_methods,
+ )
+
+ def excluded_shipping_methods_for_checkout(
+ self,
+ checkout: "Checkout",
+ available_shipping_methods: List["ShippingMethodData"],
+ ) -> List[ExcludedShippingMethod]:
+ return self.__run_method_on_plugins(
+ "excluded_shipping_methods_for_checkout",
+ [],
+ checkout,
+ available_shipping_methods,
+ )
+
def get_plugins_manager(
requestor_getter: Optional[Callable[[], "Requestor"]] = None
diff --git a/saleor/plugins/webhook/const.py b/saleor/plugins/webhook/const.py
new file mode 100644
index 0000000000..047e488379
--- /dev/null
+++ b/saleor/plugins/webhook/const.py
@@ -0,0 +1,3 @@
+CACHE_EXCLUDED_SHIPPING_KEY = "webhook_exclude_shipping_id_"
+CACHE_EXCLUDED_SHIPPING_TIME = 60 * 3
+EXCLUDED_SHIPPING_REQUEST_TIMEOUT = 2
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 660a4ad370..a7cf8a4bb1 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -13,6 +13,8 @@ from ...webhook.payloads import (
generate_checkout_payload,
generate_collection_payload,
generate_customer_payload,
+ generate_excluded_shipping_methods_for_checkout_payload,
+ generate_excluded_shipping_methods_for_order_payload,
generate_fulfillment_payload,
generate_invoice_payload,
generate_list_gateways_payload,
@@ -28,7 +30,9 @@ from ...webhook.payloads import (
generate_sale_payload,
generate_translation_payload,
)
-from ..base_plugin import BasePlugin
+from ..base_plugin import BasePlugin, ExcludedShippingMethod
+from .const import CACHE_EXCLUDED_SHIPPING_KEY
+from .shipping import get_excluded_shipping_data, parse_list_shipping_methods_response
from .tasks import (
_get_webhooks_for_event,
send_webhook_request_async,
@@ -39,7 +43,6 @@ from .utils import (
delivery_update,
from_payment_app_id,
parse_list_payment_gateways_response,
- parse_list_shipping_methods_response,
parse_payment_action_response,
)
@@ -57,7 +60,6 @@ if TYPE_CHECKING:
from ...translation.models import Translation
from ...warehouse.models import Stock
-
logger = logging.getLogger(__name__)
@@ -621,6 +623,44 @@ class WebhookPlugin(BasePlugin):
methods.extend(shipping_methods)
return methods
+ def excluded_shipping_methods_for_order(
+ self,
+ order: "Order",
+ available_shipping_methods: List["ShippingMethodData"],
+ previous_value: List[ExcludedShippingMethod],
+ ) -> List[ExcludedShippingMethod]:
+ generate_function = generate_excluded_shipping_methods_for_order_payload
+ payload_fun = lambda: generate_function( # noqa: E731
+ order,
+ available_shipping_methods,
+ )
+ cache_key = CACHE_EXCLUDED_SHIPPING_KEY + order.token
+ return get_excluded_shipping_data(
+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ previous_value=previous_value,
+ payload_fun=payload_fun,
+ cache_key=cache_key,
+ )
+
+ def excluded_shipping_methods_for_checkout(
+ self,
+ checkout: "Checkout",
+ available_shipping_methods: List["ShippingMethodData"],
+ previous_value: List[ExcludedShippingMethod],
+ ) -> List[ExcludedShippingMethod]:
+ generate_function = generate_excluded_shipping_methods_for_checkout_payload
+ payload_function = lambda: generate_function( # noqa: E731
+ checkout,
+ available_shipping_methods,
+ )
+ cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout.token)
+ return get_excluded_shipping_data(
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ previous_value=previous_value,
+ payload_fun=payload_function,
+ cache_key=cache_key,
+ )
+
def is_event_active(self, event: str, channel=Optional[str]):
map_event = {"invoice_request": WebhookEventAsyncType.INVOICE_REQUESTED}
webhooks = _get_webhooks_for_event(event_type=map_event[event])
diff --git a/saleor/plugins/webhook/shipping.py b/saleor/plugins/webhook/shipping.py
new file mode 100644
index 0000000000..9f8e4868e6
--- /dev/null
+++ b/saleor/plugins/webhook/shipping.py
@@ -0,0 +1,161 @@
+import base64
+import logging
+from collections import defaultdict
+from typing import TYPE_CHECKING, Any, Callable, Dict, List
+
+import graphene
+from django.core.cache import cache
+from django.db.models import QuerySet
+from prices import Money
+
+from ...shipping.interface import ShippingMethodData
+from ..base_plugin import ExcludedShippingMethod
+from .const import CACHE_EXCLUDED_SHIPPING_TIME, EXCLUDED_SHIPPING_REQUEST_TIMEOUT
+from .tasks import _get_webhooks_for_event, trigger_webhook_sync
+from .utils import APP_ID_PREFIX
+
+if TYPE_CHECKING:
+ from ...app.models import App
+
+
+logger = logging.getLogger(__name__)
+
+
+def to_shipping_app_id(app: "App", shipping_method_id: str) -> "str":
+ return base64.b64encode(
+ str.encode(f"{APP_ID_PREFIX}:{app.pk}:{shipping_method_id}")
+ ).decode("utf-8")
+
+
+def parse_list_shipping_methods_response(
+ response_data: Any, app: "App"
+) -> List["ShippingMethodData"]:
+ shipping_methods = []
+ for shipping_method_data in response_data:
+ method_id = shipping_method_data.get("id")
+ method_name = shipping_method_data.get("name")
+ method_amount = shipping_method_data.get("amount")
+ method_currency = shipping_method_data.get("currency")
+ method_maximum_delivery_days = shipping_method_data.get("maximum_delivery_days")
+
+ shipping_methods.append(
+ ShippingMethodData(
+ id=to_shipping_app_id(app, method_id),
+ name=method_name,
+ price=Money(method_amount, method_currency),
+ maximum_delivery_days=method_maximum_delivery_days,
+ )
+ )
+ return shipping_methods
+
+
+def get_excluded_shipping_methods_or_fetch(
+ webhooks: QuerySet, event_type: str, payload: str, cache_key: str
+) -> Dict[str, List[ExcludedShippingMethod]]:
+ """Return data of all excluded shipping methods.
+
+ The data will be fetched from the cache. If missing it will fetch it from all
+ defined webhooks by calling a request to each of them one by one.
+ """
+ cached_data = cache.get(cache_key)
+ if cached_data:
+ cached_payload, excluded_shipping_methods = cached_data
+ if payload == cached_payload:
+ return parse_excluded_shipping_methods(excluded_shipping_methods)
+
+ excluded_methods = []
+ # Gather responses from webhooks
+ for webhook in webhooks:
+ response_data = trigger_webhook_sync(
+ event_type,
+ payload,
+ webhook.app,
+ EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
+ )
+ if response_data:
+ excluded_methods.extend(
+ get_excluded_shipping_methods_from_response(response_data)
+ )
+ cache.set(cache_key, (payload, excluded_methods), CACHE_EXCLUDED_SHIPPING_TIME)
+ return parse_excluded_shipping_methods(excluded_methods)
+
+
+def get_excluded_shipping_data(
+ event_type: str,
+ previous_value: List[ExcludedShippingMethod],
+ payload_fun: Callable[[], str],
+ cache_key: str,
+) -> List[ExcludedShippingMethod]:
+ """Exclude not allowed shipping methods by sync webhook.
+
+ Fetch excluded shipping methods from sync webhooks and return them as a list of
+ excluded shipping methods.
+ The function uses a cache_key to reduce the number of
+ requests which we call to the external APIs. In case when we have the same payload
+ in a cache as we're going to send now, we will skip an additional request and use
+ the response fetched from cache.
+ The function will fetch the payload only in the case that we have any defined
+ webhook.
+ """
+
+ excluded_methods_map: Dict[str, List[ExcludedShippingMethod]] = defaultdict(list)
+ webhooks = _get_webhooks_for_event(event_type)
+ if webhooks:
+ payload = payload_fun()
+
+ excluded_methods_map = get_excluded_shipping_methods_or_fetch(
+ webhooks, event_type, payload, cache_key
+ )
+
+ # Gather responses for previous plugins
+ for method in previous_value:
+ excluded_methods_map[method.id].append(method)
+
+ # Return a list of excluded methods, unique by id
+ excluded_methods = []
+ for method_id, methods in excluded_methods_map.items():
+ reason = None
+ if reasons := [m.reason for m in methods if m.reason]:
+ reason = " ".join(reasons)
+ excluded_methods.append(ExcludedShippingMethod(id=method_id, reason=reason))
+ return excluded_methods
+
+
+def get_excluded_shipping_methods_from_response(
+ response_data: dict,
+) -> List[dict]:
+ excluded_methods = []
+ for method_data in response_data.get("excluded_methods", []):
+ try:
+ raw_id = method_data["id"]
+ typename, _id = graphene.Node.from_global_id(raw_id)
+ if typename == "app":
+ method_id = raw_id
+ elif typename == "ShippingMethod":
+ method_id = _id
+ else:
+ logger.warning(
+ "Invalid type received. Expected ShippingMethod, got %s", typename
+ )
+ continue
+ except (KeyError, ValueError, TypeError) as e:
+ logger.warning("Malformed ShippingMethod id was provided: %s", e)
+ continue
+ excluded_methods.append(
+ {"id": method_id, "reason": method_data.get("reason", "")}
+ )
+ return excluded_methods
+
+
+def parse_excluded_shipping_methods(
+ excluded_methods: List[dict],
+) -> Dict[str, List[ExcludedShippingMethod]]:
+ excluded_methods_map = defaultdict(list)
+ for excluded_method in excluded_methods:
+ method_id = excluded_method["id"]
+ excluded_methods_map[method_id].append(
+ ExcludedShippingMethod(
+ id=method_id, reason=excluded_method.get("reason", "")
+ )
+ )
+ return excluded_methods_map
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index 6f200278e0..b3163142c8 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -93,7 +93,7 @@ def trigger_webhooks_async(data, event_type, webhooks):
send_webhook_request_async.delay(delivery.id)
-def trigger_webhook_sync(event_type: str, data: str, app: "App"):
+def trigger_webhook_sync(event_type: str, data: str, app: "App", timeout=None):
"""Send a synchronous webhook request."""
webhooks = _get_webhooks_for_event(event_type, app.webhooks.all())
webhook = webhooks.first()
@@ -107,7 +107,10 @@ def trigger_webhook_sync(event_type: str, data: str, app: "App"):
if not webhooks:
raise PaymentError(f"No payment webhook found for event: {event_type}.")
- return send_webhook_request_sync(app.name, delivery)
+ kwargs = {}
+ if timeout:
+ kwargs = {"timeout": timeout}
+ return send_webhook_request_sync(app.name, delivery, **kwargs)
def send_webhook_using_http(
@@ -301,7 +304,7 @@ def send_webhook_request_async(self, event_delivery_id):
clear_successful_delivery(delivery)
-def send_webhook_request_sync(app_name, delivery):
+def send_webhook_request_sync(app_name, delivery, timeout=WEBHOOK_SYNC_TIMEOUT):
event_payload = delivery.payload
data = event_payload.payload
webhook = delivery.webhook
@@ -329,7 +332,7 @@ def send_webhook_request_sync(app_name, delivery):
domain,
signature,
delivery.event_type,
- timeout=WEBHOOK_SYNC_TIMEOUT,
+ timeout=timeout,
)
response_data = json.loads(response.content)
except RequestException as e:
diff --git a/saleor/plugins/webhook/tests/conftest.py b/saleor/plugins/webhook/tests/conftest.py
new file mode 100644
index 0000000000..5200b1302d
--- /dev/null
+++ b/saleor/plugins/webhook/tests/conftest.py
@@ -0,0 +1,75 @@
+import uuid
+from decimal import Decimal
+from typing import List
+
+import pytest
+from measurement.measures import Weight
+from prices import Money
+
+from ....app.models import App
+from ....plugins.manager import get_plugins_manager
+from ....plugins.webhook.plugin import WebhookPlugin
+from ....shipping.interface import ShippingMethodData
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook, WebhookEvent
+
+
+def webhook_plugin(settings):
+ def factory() -> WebhookPlugin:
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ return manager.global_plugins[0]
+
+ return factory
+
+
+def available_shipping_methods_factory():
+ def factory(num_methods=1) -> List[ShippingMethodData]:
+ methods = []
+ for i in range(num_methods):
+ methods.append(
+ ShippingMethodData(
+ id=str(i),
+ price=Money(Decimal("10"), "usd"),
+ name=uuid.uuid4().hex,
+ maximum_order_weight=Weight(kg=0),
+ minimum_order_weight=Weight(kg=0),
+ maximum_delivery_days=0,
+ minimum_delivery_days=5,
+ )
+ )
+ return methods
+
+ return factory
+
+
+def shipping_app_factory(db, permission_manage_orders, permission_manage_checkouts):
+ def create_app(app_name="Shipping App"):
+ app = App.objects.create(name=app_name, is_active=True)
+ app.tokens.create(name="Default")
+ app.permissions.add(permission_manage_orders)
+ app.permissions.add(permission_manage_checkouts)
+
+ webhook = Webhook.objects.create(
+ name="shipping-webhook-1",
+ app=app,
+ target_url="https://shipping-gateway.com/api/",
+ )
+ webhook.events.bulk_create(
+ [
+ WebhookEvent(
+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ webhook=webhook,
+ ),
+ WebhookEvent(
+ event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ webhook=webhook,
+ ),
+ ]
+ )
+ return app
+
+ return create_app
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index 9e10adab75..3c5390c640 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py
@@ -14,7 +14,6 @@ from ....payment import PaymentError, TransactionKind
from ....payment.utils import create_payment_information
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....webhook.models import Webhook, WebhookEvent
-from ...manager import get_plugins_manager
from ..tasks import send_webhook_request_sync, trigger_webhook_sync
from ..utils import (
parse_list_payment_gateways_response,
@@ -33,16 +32,6 @@ def payment_invalid_app(payment_dummy):
return payment_dummy
-def webhook_plugin(settings):
- def factory():
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- manager = get_plugins_manager()
- return manager.global_plugins[0]
-
- return factory
-
-
WebhookTestData = namedtuple("WebhookTestData", "secret, event_type, data, message")
diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.py
index 28bbce6d51..022b6a900b 100644
--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py
+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py
@@ -1,28 +1,403 @@
+import json
from unittest import mock
import graphene
import pytest
from ....core.models import EventDelivery
+from ....graphql.tests.utils import get_graphql_content
from ....webhook.event_types import WebhookEventSyncType
-from ...manager import get_plugins_manager
+from ....webhook.payloads import (
+ generate_excluded_shipping_methods_for_checkout_payload,
+ generate_excluded_shipping_methods_for_order_payload,
+)
+from ...base_plugin import ExcludedShippingMethod
+from ..const import (
+ CACHE_EXCLUDED_SHIPPING_KEY,
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
+)
+from ..shipping import get_excluded_shipping_methods_from_response, to_shipping_app_id
from ..tasks import trigger_webhook_sync
-from ..utils import parse_list_shipping_methods_response
+ORDER_QUERY_SHIPPING_METHOD = """
+ query OrdersQuery {
+ orders(first: 1) {
+ edges {
+ node {
+ shippingMethods {
+ id
+ name
+ active
+ message
+ }
+ availableShippingMethods {
+ id
+ name
+ active
+ message
+ }
+ }
+ }
+ }
+ }
+"""
+
+CHECKOUT_QUERY_SHIPPING_METHOD = """
+ query CheckoutsQuery {
+ checkouts(first: 1) {
+ edges {
+ node {
+ shippingMethods {
+ id
+ name
+ active
+ }
+ availableShippingMethods {
+ id
+ name
+ active
+ }
+ }
+ }
+ }
+ }
+"""
+
+
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
+ "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
+)
+def test_excluded_shipping_methods_for_order(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ webhook_plugin,
+ order_with_lines,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app = shipping_app_factory()
+ webhook_reason = "Order contains dangerous products."
+ other_reason = "Shipping is not applicable for this order."
+
+ mocked_webhook.return_value = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+ payload = mock.MagicMock()
+ mocked_payload.return_value = payload
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = [
+ ExcludedShippingMethod(id="1", reason=other_reason),
+ ExcludedShippingMethod(id="2", reason=other_reason),
+ ]
+
+ # when
+ excluded_methods = plugin.excluded_shipping_methods_for_order(
+ order=order_with_lines,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+ # then
+ assert len(excluded_methods) == 2
+ em = excluded_methods[0]
+ assert em.id == "1"
+ assert webhook_reason in em.reason
+ assert other_reason in em.reason
+ mocked_webhook.assert_called_once_with(
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ payload,
+ shipping_app,
+ EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
+ )
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + order_with_lines.token
+
+ expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
+
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ )
+
+
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
+ "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
+)
+def test_multiple_app_with_excluded_shipping_methods_for_order(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ webhook_plugin,
+ order_with_lines,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app = shipping_app_factory()
+ second_shipping_app = shipping_app_factory(app_name="shipping-app2")
+ webhook_reason = "Order contains dangerous products."
+ webhook_second_reason = "Shipping is not applicable for this order."
+
+ mocked_webhook.side_effect = [
+ {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ },
+ {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_second_reason,
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),
+ "reason": webhook_second_reason,
+ },
+ ]
+ },
+ ]
+
+ payload = mock.MagicMock()
+ mocked_payload.return_value = payload
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = []
+
+ # when
+ excluded_methods = plugin.excluded_shipping_methods_for_order(
+ order=order_with_lines,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+
+ # then
+ assert len(excluded_methods) == 2
+ em = excluded_methods[0]
+ assert em.id == "1"
+ assert webhook_reason in em.reason
+ assert webhook_second_reason in em.reason
+ mocked_webhook.assert_any_call(
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ payload,
+ shipping_app,
+ EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
+ )
+ mocked_webhook.assert_any_call(
+ WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
+ payload,
+ second_shipping_app,
+ EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
+ )
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + order_with_lines.token
+
+ expected_excluded_shipping_method = [
+ {"id": "1", "reason": webhook_reason},
+ {"id": "1", "reason": webhook_second_reason},
+ {"id": "2", "reason": webhook_second_reason},
+ ]
+
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ )
+
+
+def test_parse_excluded_shipping_methods_response(app):
+ # given
+ external_id = to_shipping_app_id(app, "test-1234")
+ response = {
+ "excluded_methods": [
+ {
+ "id": "",
+ },
+ {
+ "id": "not-an-id",
+ },
+ {
+ "id": graphene.Node.to_global_id("Car", "1"),
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),
+ },
+ {
+ "id": external_id,
+ },
+ ]
+ }
+ # when
+ excluded_methods = get_excluded_shipping_methods_from_response(response)
+ # then
+ assert len(excluded_methods) == 2
+ assert excluded_methods[0]["id"] == "2"
+ assert excluded_methods[1]["id"] == external_id
+
+
+ "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_order"
+)
+def test_order_shipping_methods(
+ mocked_webhook,
+ staff_api_client,
+ order_with_lines,
+ permission_manage_orders,
+ settings,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ webhook_reason = "spanish-inquisition"
+ excluded_shipping_method_id = order_with_lines.shipping_method.id
+ mocked_webhook.return_value = [
+ ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)
+ ]
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ # when
+ response = staff_api_client.post_graphql(ORDER_QUERY_SHIPPING_METHOD)
+ content = get_graphql_content(response)
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+
+ shipping_methods = order_data["shippingMethods"]
+ # then
+ assert len(shipping_methods) == 1
+ assert not shipping_methods[0]["active"]
+ assert shipping_methods[0]["message"] == webhook_reason
+
+
+ "webhook_response, expected_count",
+ [(lambda s: [ExcludedShippingMethod(s.id, "")], 0), (lambda s: [], 1)],
+)
+ "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_order"
+)
+def test_order_available_shipping_methods(
+ mocked_webhook,
+ staff_api_client,
+ order_with_lines,
+ permission_manage_orders,
+ settings,
+ webhook_response,
+ expected_count,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ mocked_webhook.side_effect = lambda *args, **kwargs: webhook_response(
+ order_with_lines.shipping_method
+ )
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ # when
+ response = staff_api_client.post_graphql(ORDER_QUERY_SHIPPING_METHOD)
+ content = get_graphql_content(response)
+ order_data = content["data"]["orders"]["edges"][0]["node"]
-def plugin_manager(settings, channel_USD):
+ # then
+ assert len(order_data["availableShippingMethods"]) == expected_count
+
+
+ "saleor.plugins.webhook.plugin.WebhookPlugin.excluded_shipping_methods_for_checkout"
+)
+def test_checkout_shipping_methods(
+ mocked_webhook,
+ staff_api_client,
+ checkout_ready_to_complete,
+ permission_manage_checkouts,
+ settings,
+):
+ # given
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- manager = get_plugins_manager()
- return manager
+ webhook_reason = "spanish-inquisition"
+ excluded_shipping_method_id = checkout_ready_to_complete.shipping_method.id
+ mocked_webhook.return_value = [
+ ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)
+ ]
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+ # when
+ response = staff_api_client.post_graphql(CHECKOUT_QUERY_SHIPPING_METHOD)
+ content = get_graphql_content(response)
+ checkout_data = content["data"]["checkouts"]["edges"][0]["node"]
+ shipping_methods = checkout_data["shippingMethods"]
+ # then
+ assert len(shipping_methods) == 2
+ inactive_method = list(
+ filter(
+ lambda s: s["id"]
+ == graphene.Node.to_global_id(
+ "ShippingMethod", excluded_shipping_method_id
+ ),
+ shipping_methods,
+ )
+ )
+ assert not inactive_method[0]["active"]
-def webhook_plugin(plugin_manager):
- def factory():
- return plugin_manager.global_plugins[0]
- return factory
+ "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"
+)
+def test_checkout_available_shipping_methods(
+ mocked_webhook,
+ staff_api_client,
+ checkout_ready_to_complete,
+ permission_manage_checkouts,
+ settings,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ webhook_reason = "spanish-inquisition"
+
+ excluded_shipping_method_id = checkout_ready_to_complete.shipping_method.id
+ mocked_webhook.return_value = [
+ ExcludedShippingMethod(excluded_shipping_method_id, webhook_reason)
+ ]
+
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+ # when
+ response = staff_api_client.post_graphql(CHECKOUT_QUERY_SHIPPING_METHOD)
+ content = get_graphql_content(response)
+ shipping_methods = content["data"]["checkouts"]["edges"][0]["node"][
+ "availableShippingMethods"
+ ]
+ # then
+ assert len(shipping_methods) == 1
+ assert shipping_methods[0]["active"]
+
+
+ "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"
+)
+def test_checkout_shipping_methods_webhook_called_once(
+ mocked_webhook,
+ staff_api_client,
+ checkout_ready_to_complete,
+ permission_manage_checkouts,
+):
+ # given
+ mocked_webhook.side_effect = [[], AssertionError("called twice.")]
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+ # when
+ response = staff_api_client.post_graphql(CHECKOUT_QUERY_SHIPPING_METHOD)
+ content = get_graphql_content(response)
+ checkout_data = content["data"]["checkouts"]["edges"][0]["node"]
+ # then
+ assert len(checkout_data["availableShippingMethods"]) == 2
+ assert len(checkout_data["shippingMethods"]) == 2
@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
@@ -35,69 +410,213 @@ def test_trigger_webhook_sync(mock_request, shipping_app):
mock_request.assert_called_once_with(shipping_app.name, event_delivery)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
-def test_get_shipping_methods_for_checkout(
- mock_send_request, shipping_app, webhook_plugin, checkout
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
+ "saleor.plugins.webhook.plugin."
+ "generate_excluded_shipping_methods_for_checkout_payload"
+)
+def test_excluded_shipping_methods_for_checkout(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ webhook_plugin,
+ checkout_with_items,
+ available_shipping_methods_factory,
+ shipping_app_factory,
):
+ # given
+ shipping_app = shipping_app_factory()
+ webhook_reason = "Checkout contains dangerous products."
+ other_reason = "Shipping is not applicable for this checkout."
+
+ mocked_webhook.return_value = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+ payload = mock.MagicMock()
+ mocked_payload.return_value = payload
plugin = webhook_plugin()
- mock_json_response = [
- {
- "id": "shipping_method_id",
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
- }
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = [
+ ExcludedShippingMethod(id="1", reason=other_reason),
+ ExcludedShippingMethod(id="2", reason=other_reason),
]
- mock_send_request.return_value = mock_json_response
- methods = plugin.get_shipping_methods_for_checkout(checkout, None)
- expected_methods = parse_list_shipping_methods_response(
- mock_json_response, shipping_app
+ # when
+ excluded_methods = plugin.excluded_shipping_methods_for_checkout(
+ checkout=checkout_with_items,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+ # then
+ assert len(excluded_methods) == 2
+ em = excluded_methods[0]
+ assert em.id == "1"
+ assert webhook_reason in em.reason
+ assert other_reason in em.reason
+ mocked_webhook.assert_called_once_with(
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ payload,
+ shipping_app,
+ EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
)
- assert len(methods) == 1
- assert methods[0] == expected_methods[0]
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
+ expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
-def test_get_shipping_method(mock_send_request, shipping_app, plugin_manager, checkout):
- response_method_id = "abcd"
- shipping_method_id = graphene.Node.to_global_id(
- "app", f"{shipping_app.id}:{response_method_id}"
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
)
- mock_json_response = [
+
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
+ "saleor.plugins.webhook.plugin."
+ "generate_excluded_shipping_methods_for_checkout_payload"
+)
+def test_multiple_app_with_excluded_shipping_methods_for_checkout(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ webhook_plugin,
+ checkout_with_items,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app = shipping_app_factory()
+ second_shipping_app = shipping_app_factory()
+ webhook_reason = "Checkout contains dangerous products."
+ webhook_second_reason = "Shipping is not applicable for this checkout."
+
+ mocked_webhook.side_effect = [
{
- "id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
- "maximum_delivery_days": "7",
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
},
{
- "id": "cdef",
- "name": "Provider - Priority",
- "amount": "15",
- "currency": "USD",
- "maximum_delivery_days": None,
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_second_reason,
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "2"),
+ "reason": webhook_second_reason,
+ },
+ ]
},
]
- mock_send_request.return_value = mock_json_response
- shipping_method = plugin_manager.get_shipping_method(
- shipping_method_id, checkout, None
+ payload = mock.MagicMock()
+ mocked_payload.return_value = payload
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = []
+
+ # when
+ excluded_methods = plugin.excluded_shipping_methods_for_checkout(
+ checkout=checkout_with_items,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
)
- assert shipping_method.id == shipping_method_id
+ # then
+ assert len(excluded_methods) == 2
+ em = excluded_methods[0]
+ assert em.id == "1"
+ assert webhook_reason in em.reason
+ assert webhook_second_reason in em.reason
+ mocked_webhook.assert_any_call(
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ payload,
+ shipping_app,
+ EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
+ )
+ mocked_webhook.assert_any_call(
+ WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,
+ payload,
+ second_shipping_app,
+ EXCLUDED_SHIPPING_REQUEST_TIMEOUT,
+ )
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
-def test_get_shipping_method_empty_response(
- mock_send_request, shipping_app, plugin_manager, checkout
+ expected_excluded_shipping_method = [
+ {"id": "1", "reason": webhook_reason},
+ {"id": "1", "reason": webhook_second_reason},
+ {"id": "2", "reason": webhook_second_reason},
+ ]
+
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ )
+
+
+def test_generate_excluded_shipping_methods_for_order_payload(
+ webhook_plugin,
+ order_with_lines,
+ available_shipping_methods_factory,
):
- shipping_method_id = graphene.Node.to_global_id("app", f"{shipping_app.id}:abcd")
- mock_send_request.return_value = []
- shipping_method = plugin_manager.get_shipping_method(
- shipping_method_id, checkout, None
+ # given
+ methods = available_shipping_methods_factory(num_methods=3)
+ # when
+ json_payload = json.loads(
+ generate_excluded_shipping_methods_for_order_payload(
+ order=order_with_lines, available_shipping_methods=methods
+ )
+ )
+ # then
+ assert len(json_payload["shipping_methods"]) == 3
+ assert json_payload["shipping_methods"][0]["id"] == graphene.Node.to_global_id(
+ "ShippingMethod", methods[0].id
)
+ assert json_payload["shipping_methods"][1]["id"] == graphene.Node.to_global_id(
+ "ShippingMethod", methods[1].id
+ )
+ assert json_payload["shipping_methods"][2]["id"] == graphene.Node.to_global_id(
+ "ShippingMethod", methods[2].id
+ )
+ graphql_order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
+ assert json_payload["order"]["id"] == graphql_order_id
+
- assert shipping_method is None
+def test_generate_excluded_shipping_methods_for_checkout_payload(
+ webhook_plugin,
+ checkout_with_items,
+ available_shipping_methods_factory,
+):
+ # given
+ methods = available_shipping_methods_factory(num_methods=3)
+ # when
+ json_payload = json.loads(
+ generate_excluded_shipping_methods_for_checkout_payload(
+ checkout=checkout_with_items, available_shipping_methods=methods
+ )
+ )
+ # then
+ assert len(json_payload["shipping_methods"]) == 3
+ assert json_payload["shipping_methods"][0]["id"] == graphene.Node.to_global_id(
+ "ShippingMethod", methods[0].id
+ )
+ assert json_payload["shipping_methods"][1]["id"] == graphene.Node.to_global_id(
+ "ShippingMethod", methods[1].id
+ )
+ assert json_payload["shipping_methods"][2]["id"] == graphene.Node.to_global_id(
+ "ShippingMethod", methods[2].id
+ )
+ assert "checkout" in json_payload
+ assert "channel" in json_payload["checkout"]
diff --git a/saleor/plugins/webhook/tests/test_shippping_exclude_cache.py b/saleor/plugins/webhook/tests/test_shippping_exclude_cache.py
new file mode 100644
index 0000000000..15e82ca6a1
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_shippping_exclude_cache.py
@@ -0,0 +1,366 @@
+import json
+from unittest import mock
+
+import graphene
+
+from ...base_plugin import ExcludedShippingMethod
+from ..const import CACHE_EXCLUDED_SHIPPING_KEY, CACHE_EXCLUDED_SHIPPING_TIME
+
+
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+ "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
+)
+def test_excluded_shipping_methods_for_order_use_cache(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ mocked_cache_get,
+ webhook_plugin,
+ order_with_lines,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app_factory()
+ webhook_reason = "Order contains dangerous products."
+ other_reason = "Shipping is not applicable for this order."
+
+ mocked_webhook.return_value = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+ payload = json.dumps({"order": {"id": 1, "some_field": "12"}})
+ mocked_payload.return_value = payload
+
+ mocked_cache_get.return_value = (payload, [{"id": "1", "reason": webhook_reason}])
+
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = [
+ ExcludedShippingMethod(id="1", reason=other_reason),
+ ExcludedShippingMethod(id="2", reason=other_reason),
+ ]
+
+ # when
+ plugin.excluded_shipping_methods_for_order(
+ order=order_with_lines,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+ # then
+ assert not mocked_webhook.called
+
+ assert not mocked_cache_set.called
+
+
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+ "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
+)
+def test_excluded_shipping_methods_for_order_stores_in_cache_when_empty(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ mocked_cache_get,
+ webhook_plugin,
+ order_with_lines,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app_factory()
+ webhook_reason = "Order contains dangerous products."
+ other_reason = "Shipping is not applicable for this order."
+
+ mocked_webhook.return_value = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+ payload = json.dumps({"order": {"id": 1, "some_field": "12"}})
+ mocked_payload.return_value = payload
+
+ mocked_cache_get.return_value = None
+
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = [
+ ExcludedShippingMethod(id="1", reason=other_reason),
+ ExcludedShippingMethod(id="2", reason=other_reason),
+ ]
+
+ # when
+ plugin.excluded_shipping_methods_for_order(
+ order=order_with_lines,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+ # then
+ assert mocked_webhook.called
+
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + order_with_lines.token
+
+ expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
+
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ )
+
+
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+ "saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
+)
+def test_excluded_shipping_methods_for_order_stores_in_cache_when_payload_is_different(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ mocked_cache_get,
+ webhook_plugin,
+ order_with_lines,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app_factory()
+ webhook_reason = "Order contains dangerous products."
+ other_reason = "Shipping is not applicable for this order."
+
+ mocked_webhook.return_value = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+ payload = json.dumps({"order": {"id": 1, "some_field": "12"}})
+ mocked_payload.return_value = payload
+
+ mocked_cache_get.return_value = (
+ {"order": "different-payload"},
+ [{"id": "1", "reason": webhook_reason}],
+ )
+
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = [
+ ExcludedShippingMethod(id="1", reason=other_reason),
+ ExcludedShippingMethod(id="2", reason=other_reason),
+ ]
+
+ # when
+ plugin.excluded_shipping_methods_for_order(
+ order=order_with_lines,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+ # then
+ assert mocked_webhook.called
+
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + order_with_lines.token
+
+ expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
+
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ )
+
+
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+ "saleor.plugins.webhook.plugin."
+ "generate_excluded_shipping_methods_for_checkout_payload"
+)
+def test_excluded_shipping_methods_for_checkout_use_cache(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ mocked_cache_get,
+ webhook_plugin,
+ checkout_with_items,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app_factory()
+ webhook_reason = "Order contains dangerous products."
+ other_reason = "Shipping is not applicable for this order."
+
+ mocked_webhook.return_value = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+
+ payload = json.dumps({"checkout": {"id": 1, "some_field": "12"}})
+ mocked_payload.return_value = payload
+
+ mocked_cache_get.return_value = (payload, [{"id": "1", "reason": webhook_reason}])
+
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = [
+ ExcludedShippingMethod(id="1", reason=other_reason),
+ ExcludedShippingMethod(id="2", reason=other_reason),
+ ]
+ # when
+ plugin.excluded_shipping_methods_for_checkout(
+ checkout=checkout_with_items,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+ # then
+ assert not mocked_webhook.called
+
+ assert not mocked_cache_set.called
+
+
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+ "saleor.plugins.webhook.plugin."
+ "generate_excluded_shipping_methods_for_checkout_payload"
+)
+def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ mocked_cache_get,
+ webhook_plugin,
+ checkout_with_items,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app_factory()
+ webhook_reason = "Order contains dangerous products."
+ other_reason = "Shipping is not applicable for this order."
+
+ mocked_webhook.return_value = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+
+ payload = json.dumps({"checkout": {"id": 1, "some_field": "12"}})
+ mocked_payload.return_value = payload
+
+ mocked_cache_get.return_value = None
+
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = [
+ ExcludedShippingMethod(id="1", reason=other_reason),
+ ExcludedShippingMethod(id="2", reason=other_reason),
+ ]
+ # when
+ plugin.excluded_shipping_methods_for_checkout(
+ checkout=checkout_with_items,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+ # then
+ assert mocked_webhook.called
+
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
+
+ expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
+
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ )
+
+
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+ "saleor.plugins.webhook.plugin."
+ "generate_excluded_shipping_methods_for_checkout_payload"
+)
+def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_payload_different(
+ mocked_payload,
+ mocked_webhook,
+ mocked_cache_set,
+ mocked_cache_get,
+ webhook_plugin,
+ checkout_with_items,
+ available_shipping_methods_factory,
+ shipping_app_factory,
+):
+ # given
+ shipping_app_factory()
+ webhook_reason = "Order contains dangerous products."
+ other_reason = "Shipping is not applicable for this order."
+
+ mocked_webhook.return_value = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "1"),
+ "reason": webhook_reason,
+ }
+ ]
+ }
+
+ payload = json.dumps({"checkout": {"id": 1, "some_field": "12"}})
+ mocked_payload.return_value = payload
+
+ mocked_cache_get.return_value = (
+ {"checkout": "different_payload"},
+ [{"id": "1", "reason": webhook_reason}],
+ )
+
+ plugin = webhook_plugin()
+ available_shipping_methods = available_shipping_methods_factory(num_methods=2)
+ previous_value = [
+ ExcludedShippingMethod(id="1", reason=other_reason),
+ ExcludedShippingMethod(id="2", reason=other_reason),
+ ]
+ # when
+ plugin.excluded_shipping_methods_for_checkout(
+ checkout=checkout_with_items,
+ available_shipping_methods=available_shipping_methods,
+ previous_value=previous_value,
+ )
+ # then
+ assert mocked_webhook.called
+
+ expected_cache_key = CACHE_EXCLUDED_SHIPPING_KEY + str(checkout_with_items.token)
+
+ expected_excluded_shipping_method = [{"id": "1", "reason": webhook_reason}]
+
+ mocked_cache_set.assert_called_once_with(
+ expected_cache_key,
+ (payload, expected_excluded_shipping_method),
+ CACHE_EXCLUDED_SHIPPING_TIME,
+ )
diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.py
index dc5f638aa0..89ee0c94e5 100644
--- a/saleor/plugins/webhook/utils.py
+++ b/saleor/plugins/webhook/utils.py
@@ -1,13 +1,12 @@
-import base64
import decimal
import json
+import logging
from contextlib import contextmanager
from dataclasses import dataclass
from time import time
from typing import TYPE_CHECKING, Any, List, Optional
from django.db.models import QuerySet
-from prices import Money
from ...core.models import (
EventDelivery,
@@ -16,7 +15,6 @@ from ...core.models import (
EventPayload,
)
from ...payment.interface import GatewayResponse, PaymentGateway, PaymentMethodInfo
-from ...shipping.interface import ShippingMethodData
if TYPE_CHECKING:
from ...app.models import App
@@ -26,6 +24,8 @@ if TYPE_CHECKING:
APP_ID_PREFIX = "app"
+logger = logging.getLogger(__name__)
+
@dataclass
class PaymentAppData:
@@ -43,12 +43,6 @@ def to_payment_app_id(app: "App", gateway_id: str) -> "str":
return f"{APP_ID_PREFIX}:{app.pk}:{gateway_id}"
-def to_shipping_app_id(app: "App", shipping_method_id: str) -> "str":
- return base64.b64encode(
- str.encode(f"{APP_ID_PREFIX}:{app.pk}:{shipping_method_id}")
- ).decode("utf-8")
-
-
def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
splitted_id = app_gateway_id.split(":")
if len(splitted_id) == 3 and splitted_id[0] == APP_ID_PREFIX and all(splitted_id):
@@ -129,28 +123,6 @@ def parse_payment_action_response(
)
-def parse_list_shipping_methods_response(
- response_data: Any, app: "App"
-) -> List["ShippingMethodData"]:
- shipping_methods = []
- for shipping_method_data in response_data:
- method_id = shipping_method_data.get("id")
- method_name = shipping_method_data.get("name")
- method_amount = shipping_method_data.get("amount")
- method_currency = shipping_method_data.get("currency")
- method_maximum_delivery_days = shipping_method_data.get("maximum_delivery_days")
-
- shipping_methods.append(
- ShippingMethodData(
- id=to_shipping_app_id(app, method_id),
- name=method_name,
- price=Money(method_amount, method_currency),
- maximum_delivery_days=method_maximum_delivery_days,
- )
- )
- return shipping_methods
-
-
@contextmanager
def catch_duration_time():
start = time()
diff --git a/saleor/shipping/interface.py b/saleor/shipping/interface.py
index 798cb67de4..7fada20ce7 100644
--- a/saleor/shipping/interface.py
+++ b/saleor/shipping/interface.py
@@ -1,6 +1,7 @@
from dataclasses import dataclass, field
from typing import Dict, Optional
+import graphene
import graphql
from measurement.measures import Weight
from prices import Money
@@ -39,3 +40,9 @@ class ShippingMethodData:
return str_type == "app"
return False
+
+ @property
+ def graphql_id(self):
+ if self.is_external:
+ return self.id
+ return graphene.Node.to_global_id("ShippingMethod", self.id)
diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.py
index dca6f46b4e..c9015904f9 100644
--- a/saleor/shipping/utils.py
+++ b/saleor/shipping/utils.py
@@ -1,8 +1,9 @@
import logging
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, List, Optional
from django_countries import countries
+from ..plugins.base_plugin import ExcludedShippingMethod
from .interface import ShippingMethodData
if TYPE_CHECKING:
@@ -53,3 +54,17 @@ def convert_to_shipping_method_data(
minimum_order_price=minimum_order_price,
maximum_order_price=maximum_order_price,
)
+
+
+def initialize_shipping_method_active_status(
+ shipping_methods: List["ShippingMethodData"],
+ excluded_methods: List["ExcludedShippingMethod"],
+):
+ reason_map = {str(method.id): method.reason for method in excluded_methods}
+ for instance in shipping_methods:
+ instance.active = True
+ instance.message = ""
+ reason = reason_map.get(str(instance.id))
+ if reason is not None:
+ instance.active = False
+ instance.message = reason
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 87191561f9..2a570cf8a8 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -475,6 +475,15 @@ def checkout_with_items(checkout, product_list, product):
return checkout
+def checkout_with_items_and_shipping(checkout_with_items, address, shipping_method):
+ checkout_with_items.shipping_address = address
+ checkout_with_items.shipping_method = shipping_method
+ checkout_with_items.billing_address = address
+ checkout_with_items.save()
+ return checkout_with_items
+
+
@pytest.fixture
def checkout_with_voucher(checkout, product, voucher):
variant = product.variants.get()
@@ -3999,10 +4008,11 @@ def fulfillment_awaiting_approval(fulfilled_order):
@pytest.fixture
-def draft_order(order_with_lines):
+def draft_order(order_with_lines, shipping_method):
Allocation.objects.filter(order_line__order=order_with_lines).delete()
order_with_lines.status = OrderStatus.DRAFT
order_with_lines.origin = OrderOrigin.DRAFT
+ order_with_lines.shipping_method = shipping_method
order_with_lines.save(update_fields=["status", "origin"])
return order_with_lines
diff --git a/saleor/webhook/deprecated_event_types.py b/saleor/webhook/deprecated_event_types.py
index 99c433b3e7..1235b5d320 100644
--- a/saleor/webhook/deprecated_event_types.py
+++ b/saleor/webhook/deprecated_event_types.py
@@ -1,16 +1,3 @@
-from ..core.permissions import (
- AccountPermissions,
- CheckoutPermissions,
- DiscountPermissions,
- OrderPermissions,
- PagePermissions,
- PaymentPermissions,
- ProductPermissions,
- ShippingPermissions,
- SitePermissions,
-)
-
-
class WebhookEventType:
ANY = "any_events"
ORDER_CREATED = "order_created"
@@ -67,6 +54,8 @@ class WebhookEventType:
PAYMENT_PROCESS = "payment_process"
SHIPPING_LIST_METHODS_FOR_CHECKOUT = "shipping_list_methods_for_checkout"
+ CHECKOUT_FILTER_SHIPPING_METHODS = "checkout_filter_shipping_methods"
+ ORDER_FILTER_SHIPPING_METHODS = "order_filter_shipping_methods"
TRANSLATION_CREATED = "translation_created"
TRANSLATION_UPDATED = "translation_updated"
@@ -114,6 +103,8 @@ class WebhookEventType:
PAYMENT_REFUND: "Refund payment",
PAYMENT_VOID: "Void payment",
SHIPPING_LIST_METHODS_FOR_CHECKOUT: "Shipping list methods for checkout",
+ ORDER_FILTER_SHIPPING_METHODS: "Filter order shipping methods",
+ CHECKOUT_FILTER_SHIPPING_METHODS: "Filter checkout shipping methods",
TRANSLATION_CREATED: "Create translation",
TRANSLATION_UPDATED: "Update translation",
}
@@ -164,64 +155,11 @@ class WebhookEventType:
SHIPPING_LIST_METHODS_FOR_CHECKOUT,
DISPLAY_LABELS[SHIPPING_LIST_METHODS_FOR_CHECKOUT],
),
+ (ORDER_FILTER_SHIPPING_METHODS, DISPLAY_LABELS[ORDER_FILTER_SHIPPING_METHODS]),
+ (
+ CHECKOUT_FILTER_SHIPPING_METHODS,
+ DISPLAY_LABELS[CHECKOUT_FILTER_SHIPPING_METHODS],
+ ),
(TRANSLATION_CREATED, DISPLAY_LABELS[TRANSLATION_CREATED]),
(TRANSLATION_UPDATED, DISPLAY_LABELS[TRANSLATION_UPDATED]),
]
-
- PAYMENT_EVENTS = [
- PAYMENT_AUTHORIZE,
- PAYMENT_CAPTURE,
- PAYMENT_CONFIRM,
- PAYMENT_LIST_GATEWAYS,
- PAYMENT_PROCESS,
- PAYMENT_REFUND,
- PAYMENT_VOID,
- ]
-
- SYNC_EVENTS = [SHIPPING_LIST_METHODS_FOR_CHECKOUT] + PAYMENT_EVENTS
-
- PERMISSIONS = {
- ORDER_CREATED: OrderPermissions.MANAGE_ORDERS,
- ORDER_CONFIRMED: OrderPermissions.MANAGE_ORDERS,
- ORDER_FULLY_PAID: OrderPermissions.MANAGE_ORDERS,
- ORDER_UPDATED: OrderPermissions.MANAGE_ORDERS,
- ORDER_CANCELLED: OrderPermissions.MANAGE_ORDERS,
- ORDER_FULFILLED: OrderPermissions.MANAGE_ORDERS,
- DRAFT_ORDER_CREATED: OrderPermissions.MANAGE_ORDERS,
- DRAFT_ORDER_DELETED: OrderPermissions.MANAGE_ORDERS,
- DRAFT_ORDER_UPDATED: OrderPermissions.MANAGE_ORDERS,
- SALE_CREATED: DiscountPermissions.MANAGE_DISCOUNTS,
- SALE_UPDATED: DiscountPermissions.MANAGE_DISCOUNTS,
- SALE_DELETED: DiscountPermissions.MANAGE_DISCOUNTS,
- INVOICE_REQUESTED: OrderPermissions.MANAGE_ORDERS,
- INVOICE_DELETED: OrderPermissions.MANAGE_ORDERS,
- INVOICE_SENT: OrderPermissions.MANAGE_ORDERS,
- CUSTOMER_CREATED: AccountPermissions.MANAGE_USERS,
- CUSTOMER_UPDATED: AccountPermissions.MANAGE_USERS,
- PRODUCT_CREATED: ProductPermissions.MANAGE_PRODUCTS,
- PRODUCT_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
- PRODUCT_DELETED: ProductPermissions.MANAGE_PRODUCTS,
- PRODUCT_VARIANT_CREATED: ProductPermissions.MANAGE_PRODUCTS,
- PRODUCT_VARIANT_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
- PRODUCT_VARIANT_DELETED: ProductPermissions.MANAGE_PRODUCTS,
- PRODUCT_VARIANT_BACK_IN_STOCK: ProductPermissions.MANAGE_PRODUCTS,
- PRODUCT_VARIANT_OUT_OF_STOCK: ProductPermissions.MANAGE_PRODUCTS,
- CHECKOUT_CREATED: CheckoutPermissions.MANAGE_CHECKOUTS,
- CHECKOUT_UPDATED: CheckoutPermissions.MANAGE_CHECKOUTS,
- FULFILLMENT_CREATED: OrderPermissions.MANAGE_ORDERS,
- FULFILLMENT_CANCELED: OrderPermissions.MANAGE_ORDERS,
- NOTIFY_USER: AccountPermissions.MANAGE_USERS,
- PAGE_CREATED: PagePermissions.MANAGE_PAGES,
- PAGE_UPDATED: PagePermissions.MANAGE_PAGES,
- PAGE_DELETED: PagePermissions.MANAGE_PAGES,
- PAYMENT_AUTHORIZE: PaymentPermissions.HANDLE_PAYMENTS,
- PAYMENT_CAPTURE: PaymentPermissions.HANDLE_PAYMENTS,
- PAYMENT_CONFIRM: PaymentPermissions.HANDLE_PAYMENTS,
- PAYMENT_LIST_GATEWAYS: PaymentPermissions.HANDLE_PAYMENTS,
- PAYMENT_PROCESS: PaymentPermissions.HANDLE_PAYMENTS,
- PAYMENT_REFUND: PaymentPermissions.HANDLE_PAYMENTS,
- PAYMENT_VOID: PaymentPermissions.HANDLE_PAYMENTS,
- SHIPPING_LIST_METHODS_FOR_CHECKOUT: ShippingPermissions.MANAGE_SHIPPING,
- TRANSLATION_CREATED: SitePermissions.MANAGE_TRANSLATIONS,
- TRANSLATION_UPDATED: SitePermissions.MANAGE_TRANSLATIONS,
- }
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 49fd665c3b..7912167841 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -203,6 +203,8 @@ class WebhookEventSyncType:
PAYMENT_PROCESS = "payment_process"
SHIPPING_LIST_METHODS_FOR_CHECKOUT = "shipping_list_methods_for_checkout"
+ CHECKOUT_FILTER_SHIPPING_METHODS = "checkout_filter_shipping_methods"
+ ORDER_FILTER_SHIPPING_METHODS = "order_filter_shipping_methods"
DISPLAY_LABELS = {
PAYMENT_AUTHORIZE: "Authorize payment",
@@ -213,6 +215,8 @@ class WebhookEventSyncType:
PAYMENT_REFUND: "Refund payment",
PAYMENT_VOID: "Void payment",
SHIPPING_LIST_METHODS_FOR_CHECKOUT: "Shipping list methods for checkout",
+ ORDER_FILTER_SHIPPING_METHODS: "Filter order shipping methods",
+ CHECKOUT_FILTER_SHIPPING_METHODS: "Filter checkout shipping methods",
}
CHOICES = [
@@ -227,6 +231,11 @@ class WebhookEventSyncType:
SHIPPING_LIST_METHODS_FOR_CHECKOUT,
DISPLAY_LABELS[SHIPPING_LIST_METHODS_FOR_CHECKOUT],
),
+ (ORDER_FILTER_SHIPPING_METHODS, DISPLAY_LABELS[ORDER_FILTER_SHIPPING_METHODS]),
+ (
+ CHECKOUT_FILTER_SHIPPING_METHODS,
+ DISPLAY_LABELS[CHECKOUT_FILTER_SHIPPING_METHODS],
+ ),
]
ALL = [event[0] for event in CHOICES]
@@ -250,4 +259,6 @@ class WebhookEventSyncType:
PAYMENT_REFUND: PaymentPermissions.HANDLE_PAYMENTS,
PAYMENT_VOID: PaymentPermissions.HANDLE_PAYMENTS,
SHIPPING_LIST_METHODS_FOR_CHECKOUT: ShippingPermissions.MANAGE_SHIPPING,
+ ORDER_FILTER_SHIPPING_METHODS: OrderPermissions.MANAGE_ORDERS,
+ CHECKOUT_FILTER_SHIPPING_METHODS: CheckoutPermissions.MANAGE_CHECKOUTS,
}
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index a3410d9a5c..163976f9f4 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -29,6 +29,7 @@ from ..payment import ChargeStatus
from ..plugins.webhook.utils import from_payment_app_id
from ..product import ProductMediaTypes
from ..product.models import Collection, Product
+from ..shipping.interface import ShippingMethodData
from ..warehouse.models import Stock, Warehouse
from . import traced_payload_generator
from .event_types import WebhookEventAsyncType
@@ -413,6 +414,7 @@ def generate_checkout_payload(
checkout_price_fields = ("discount_amount",)
quantize_price_fields(checkout, checkout_price_fields, checkout.currency)
user_fields = ("email", "first_name", "last_name")
+ channel_fields = ("slug", "currency_code")
shipping_method_fields = ("name", "type", "currency", "price_amount")
lines_dict_data = serialize_checkout_lines(checkout)
@@ -428,6 +430,7 @@ def generate_checkout_payload(
fields=checkout_fields,
obj_id_name="token",
additional_fields={
+ "channel": (lambda o: o.channel, channel_fields),
"user": (lambda c: c.user, user_fields),
"billing_address": (lambda c: c.billing_address, ADDRESS_FIELDS),
"shipping_address": (lambda c: c.shipping_address, ADDRESS_FIELDS),
@@ -997,3 +1000,49 @@ def generate_translation_payload(
translation_data.update(context)
return json.dumps(translation_data)
+
+
+def _generate_payload_for_shipping_method(method: ShippingMethodData):
+ payload = {
+ "id": method.graphql_id,
+ "price": method.price.amount,
+ "currency": method.price.currency,
+ "name": method.name,
+ "maximum_order_weight": method.maximum_order_weight,
+ "minimum_order_weight": method.minimum_order_weight,
+ "maximum_delivery_days": method.maximum_delivery_days,
+ "minimum_delivery_days": method.minimum_delivery_days,
+ }
+ return payload
+
+
+@traced_payload_generator
+def generate_excluded_shipping_methods_for_order_payload(
+ order: "Order",
+ available_shipping_methods: List[ShippingMethodData],
+):
+ order_data = json.loads(generate_order_payload(order))[0]
+ payload = {
+ "order": order_data,
+ "shipping_methods": [
+ _generate_payload_for_shipping_method(shipping_method)
+ for shipping_method in available_shipping_methods
+ ],
+ }
+ return json.dumps(payload, cls=CustomJsonEncoder)
+
+
+@traced_payload_generator
+def generate_excluded_shipping_methods_for_checkout_payload(
+ checkout: "Checkout",
+ available_shipping_methods: List[ShippingMethodData],
+):
+ checkout_data = json.loads(generate_checkout_payload(checkout))[0]
+ payload = {
+ "checkout": checkout_data,
+ "shipping_methods": [
+ _generate_payload_for_shipping_method(shipping_method)
+ for shipping_method in available_shipping_methods
+ ],
+ }
+ return json.dumps(payload, cls=CustomJsonEncoder)
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 57c0beb445..bc1c22ede2 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -9,6 +9,8 @@ from unittest.mock import ANY
import graphene
from django.utils import timezone
from freezegun import freeze_time
+from measurement.measures import Weight
+from prices import Money
from ... import __version__
from ...core.utils.json_serializer import CustomJsonEncoder
@@ -21,6 +23,7 @@ from ...order.models import Order
from ...plugins.manager import get_plugins_manager
from ...plugins.webhook.utils import from_payment_app_id
from ...product.models import ProductVariant
+from ...shipping.interface import ShippingMethodData
from ...warehouse import WarehouseClickAndCollectOption
from ..payloads import (
ORDER_FIELDS,
@@ -28,6 +31,8 @@ from ..payloads import (
generate_checkout_payload,
generate_collection_payload,
generate_customer_payload,
+ generate_excluded_shipping_methods_for_checkout_payload,
+ generate_excluded_shipping_methods_for_order_payload,
generate_fulfillment_lines_payload,
generate_invoice_payload,
generate_list_gateways_payload,
@@ -910,6 +915,66 @@ def test_genereate_sale_payload_calculates_set_differences(sale):
assert set(payload["variants_removed"]) == {"ccc"}
+def test_generate_excluded_shipping_methods_for_order(order):
+ shipping_method = ShippingMethodData(
+ id="123",
+ price=Money(Decimal("10.59"), "USD"),
+ name="shipping",
+ maximum_order_weight=Weight(kg=10),
+ minimum_order_weight=Weight(g=1),
+ maximum_delivery_days=10,
+ minimum_delivery_days=2,
+ )
+ response = json.loads(
+ generate_excluded_shipping_methods_for_order_payload(order, [shipping_method])
+ )
+
+ assert "order" in response
+ assert response["shipping_methods"] == [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "123"),
+ "price": "10.59",
+ "currency": "USD",
+ "name": "shipping",
+ "maximum_order_weight": "10.0:kg",
+ "minimum_order_weight": "1.0:g",
+ "maximum_delivery_days": 10,
+ "minimum_delivery_days": 2,
+ }
+ ]
+
+
+def test_generate_excluded_shipping_methods_for_checkout(checkout):
+ shipping_method = ShippingMethodData(
+ id="123",
+ price=Money(Decimal("10.59"), "USD"),
+ name="shipping",
+ maximum_order_weight=Weight(kg=10),
+ minimum_order_weight=Weight(g=1),
+ maximum_delivery_days=10,
+ minimum_delivery_days=2,
+ )
+ response = json.loads(
+ generate_excluded_shipping_methods_for_checkout_payload(
+ checkout, [shipping_method]
+ )
+ )
+
+ assert "checkout" in response
+ assert response["shipping_methods"] == [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "123"),
+ "price": "10.59",
+ "currency": "USD",
+ "name": "shipping",
+ "maximum_order_weight": "10.0:kg",
+ "minimum_order_weight": "1.0:g",
+ "maximum_delivery_days": 10,
+ "minimum_delivery_days": 2,
+ }
+ ]
+
+
def test_generate_requestor_returns_dict_with_user_id_and_user_type(staff_user, rf):
request = rf.request()
request.user = staff_user