Skip to content

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

Denormalize assigned shipping method to checkout (#17381)

Maciej Korycinski2a94bed90c43
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index e952ba3ac0..3399f3aaf9 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -32,7 +32,7 @@ from ..tax.utils import (
normalize_tax_rate_for_db,
validate_tax_data,
)
-from .fetch import find_checkout_line_info
+from .fetch import ShippingMethodInfo, find_checkout_line_info
from .models import Checkout
from .payment_utils import update_checkout_payment_statuses
@@ -302,7 +302,22 @@ def checkout_line_undiscounted_total_price(
return quantize_price(total_price, total_price.currency)
-def update_undiscounted_unit_price_for_lines(lines: Iterable["CheckoutLineInfo"]):
+def update_undiscounted_prices(
+ checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]
+):
+ delivery_method_info = checkout_info.delivery_method_info
+ if isinstance(delivery_method_info, ShippingMethodInfo):
+ shipping_method_data = delivery_method_info.delivery_method
+ checkout_info.checkout.undiscounted_base_shipping_price_amount = (
+ shipping_method_data.price.amount
+ )
+ else:
+ checkout_info.checkout.undiscounted_base_shipping_price_amount = Decimal(0)
+
+ _update_undiscounted_unit_price_for_lines(lines)
+
+
+def _update_undiscounted_unit_price_for_lines(lines: Iterable["CheckoutLineInfo"]):
"""Update line undiscounted unit price amount.
Undiscounted unit price stores the denormalized price of the variant.
@@ -380,7 +395,7 @@ def _fetch_checkout_prices_if_expired(
)
lines = cast(list, lines)
- update_undiscounted_unit_price_for_lines(lines)
+ update_undiscounted_prices(checkout_info, lines)
update_prior_unit_price_for_lines(lines)
create_or_update_discount_objects_from_promotion_for_checkout(
@@ -454,6 +469,7 @@ def _fetch_checkout_prices_if_expired(
"subtotal_gross_amount",
"shipping_price_net_amount",
"shipping_price_gross_amount",
+ "undiscounted_base_shipping_price_amount",
"shipping_tax_rate",
"translated_discount_name",
"discount_amount",
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 4736888896..f4b871e18a 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -81,6 +81,7 @@ from .fetch import (
)
from .models import Checkout
from .utils import (
+ PRIVATE_META_APP_SHIPPING_ID,
calculate_checkout_weight,
delete_checkouts,
get_checkout_metadata,
@@ -730,6 +731,15 @@ def _create_order(
{data.key: data.value for data in private_metadata_list}
)
+ if checkout_info.checkout.external_shipping_method_id:
+ # Add external shipping method to metadata, as order still uses private
+ # metadata for external shipping id.
+ order.store_value_in_private_metadata(
+ {
+ PRIVATE_META_APP_SHIPPING_ID: checkout_info.checkout.external_shipping_method_id
+ }
+ )
+
update_order_charge_data(order, with_save=False)
update_order_authorize_data(order, with_save=False)
order.search_vector = FlatConcatSearchVector(
@@ -1300,6 +1310,16 @@ def _create_order_from_checkout(
{data.key: data.value for data in private_metadata_list}
)
+ if checkout_info.checkout.external_shipping_method_id:
+ # Add external shipping method to metadata, as order still uses private
+ # metadata for external shipping id. The metadata will be transfered to the
+ # order.
+ checkout_metadata.store_value_in_private_metadata(
+ {
+ PRIVATE_META_APP_SHIPPING_ID: checkout_info.checkout.external_shipping_method_id
+ }
+ )
+
# order
order = Order.objects.create( # type: ignore[misc] # see below:
status=status,
diff --git a/saleor/checkout/migrations/0073_checkout_external_shipping_method_id_and_more.py b/saleor/checkout/migrations/0073_checkout_external_shipping_method_id_and_more.py
new file mode 100644
index 0000000000..54f2320655
--- /dev/null
+++ b/saleor/checkout/migrations/0073_checkout_external_shipping_method_id_and_more.py
@@ -0,0 +1,43 @@
+# Generated by Django 4.2.15 on 2025-02-10 09:57
+
+from decimal import Decimal
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0072_propagate_line_undiscounted_unit_price"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="external_shipping_method_id",
+ field=models.CharField(
+ blank=True, default=None, editable=False, max_length=255, null=True
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="shipping_method_name",
+ field=models.CharField(
+ blank=True, default=None, editable=False, max_length=255, null=True
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="undiscounted_base_shipping_price_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE checkout_checkout
+ ALTER COLUMN undiscounted_base_shipping_price_amount
+ SET DEFAULT 0;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0075_merge_20250210_1203.py b/saleor/checkout/migrations/0075_merge_20250210_1203.py
new file mode 100644
index 0000000000..7d1ffced81
--- /dev/null
+++ b/saleor/checkout/migrations/0075_merge_20250210_1203.py
@@ -0,0 +1,12 @@
+# Generated by Django 4.2.15 on 2025-02-10 12:03
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0073_checkout_external_shipping_method_id_and_more"),
+ ("checkout", "0074_checkoutline_prior_unit_price_amount"),
+ ]
+
+ operations = []
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index c99820f0fe..a4a8d2b931 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -79,6 +79,14 @@ class Checkout(models.Model):
related_name="checkouts",
on_delete=models.SET_NULL,
)
+
+ shipping_method_name = models.CharField(
+ max_length=255, null=True, default=None, blank=True, editable=False
+ )
+ external_shipping_method_id = models.CharField(
+ max_length=255, null=True, default=None, blank=True, editable=False
+ )
+
collection_point = models.ForeignKey(
"warehouse.Warehouse",
blank=True,
@@ -157,6 +165,17 @@ class Checkout(models.Model):
max_digits=5, decimal_places=4, default=Decimal("0.0")
)
+ undiscounted_base_shipping_price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ # Shipping price before applying any discounts
+ undiscounted_base_shipping_price = MoneyField(
+ amount_field="undiscounted_base_shipping_price_amount",
+ currency_field="currency",
+ )
+
authorize_status = models.CharField(
max_length=32,
default=CheckoutAuthorizeStatus.NONE,
diff --git a/saleor/checkout/tests/fixtures/checkout.py b/saleor/checkout/tests/fixtures/checkout.py
index e631951a25..2885bd945c 100644
--- a/saleor/checkout/tests/fixtures/checkout.py
+++ b/saleor/checkout/tests/fixtures/checkout.py
@@ -177,6 +177,7 @@ def checkout_with_shipping_method(checkout_with_shipping_address, shipping_metho
checkout = checkout_with_shipping_address
checkout.shipping_method = shipping_method
+ checkout.shipping_method_name = shipping_method.name
checkout.save()
return checkout
@@ -351,6 +352,15 @@ def checkout_with_delivery_method_for_cc(
return checkout
+def checkout_with_delivery_method_for_external_shipping(checkout_with_item, address):
+ checkout_with_item.shipping_address = address.get_copy()
+ checkout_with_item.external_shipping_method_id = "YXBwOlFYQndPakU9OmFiY2Q="
+ checkout_with_item.shipping_method_name = "Provider - Economy"
+ checkout_with_item.save()
+ return checkout_with_item
+
+
@pytest.fixture
def checkout_with_items(checkout, product_list, product):
variant = product.variants.get()
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index 919adcfe2f..ebe1ee308a 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -9,7 +9,10 @@ from freezegun import freeze_time
from graphene import Node
from prices import Money, TaxedMoney
-from ...checkout.utils import add_promo_code_to_checkout, set_external_shipping_id
+from ...checkout.utils import (
+ add_promo_code_to_checkout,
+ assign_external_shipping_to_checkout,
+)
from ...core.prices import quantize_price
from ...core.taxes import TaxData, TaxDataErrorMessage, TaxLineData, zero_taxed_money
from ...graphql.core.utils import to_global_id_or_none
@@ -19,6 +22,7 @@ from ...plugins.avatax.tests.conftest import plugin_configuration # noqa: F401
from ...plugins.manager import get_plugins_manager
from ...plugins.tests.sample_plugins import PluginSample
from ...product.models import ProductVariantChannelListing
+from ...shipping.interface import ShippingMethodData
from ...tax import TaxCalculationStrategy
from ...tax.calculations.checkout import update_checkout_prices_with_flat_rates
from ..base_calculations import (
@@ -778,13 +782,16 @@ def test_external_shipping_method_called_only_once_during_tax_calculations(
):
# given
external_method_id = "method-1-from-shipping-app"
+ shipping_name = "Shipping app method 1"
+ shipping_price = Decimal(10)
+ currency = "USD"
mock_send_webhook_request_sync.side_effect = (
[
{
- "amount": "1337.0",
- "currency": "USD",
+ "amount": shipping_price,
+ "currency": currency,
"id": external_method_id,
- "name": "Shipping app method 1",
+ "name": shipping_name,
}
],
{
@@ -799,12 +806,19 @@ def test_external_shipping_method_called_only_once_during_tax_calculations(
external_shipping_method_id = Node.to_global_id(
"app", f"{shipping_app_with_subscription.id}:{external_method_id}"
)
+ external_shipping_method = ShippingMethodData(
+ id=external_shipping_method_id,
+ name=shipping_name,
+ price=Money(shipping_price, currency),
+ )
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
manager = get_plugins_manager(allow_replica=False)
checkout_with_single_item.shipping_address = address
- set_external_shipping_id(checkout_with_single_item, external_shipping_method_id)
+ assign_external_shipping_to_checkout(
+ checkout_with_single_item, external_shipping_method
+ )
checkout_with_single_item.save()
checkout_with_single_item.metadata_storage.save()
checkout_lines, _ = fetch_checkout_lines(checkout_with_single_item)
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 192918cf2e..0297b6e195 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -48,16 +48,13 @@ from ..utils import (
change_billing_address_in_checkout,
change_shipping_address_in_checkout,
clear_delivery_method,
- delete_external_shipping_id_if_present,
get_checkout_metadata,
- get_external_shipping_id,
get_voucher_discount_for_checkout,
get_voucher_for_checkout,
get_voucher_for_checkout_info,
is_fully_paid,
recalculate_checkout_discount,
remove_voucher_from_checkout,
- set_external_shipping_id,
)
@@ -1290,6 +1287,8 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
shipping_method = None
shipping_channel_listings = []
+ meta_storage_mock = Mock()
+ meta_storage_mock.get_value_from_private_metadata.return_value = None
checkout = Mock(
is_shipping_required=Mock(return_value=is_shipping_required),
shipping_method=shipping_method,
@@ -1297,7 +1296,8 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
quantity=total_quantity,
spec=Checkout,
channel=channel_USD,
- metadata_storage=Mock(get_value_from_private_metadata=Mock(return_value=None)),
+ metadata_storage=meta_storage_mock,
+ external_shipping_method_id=None,
)
voucher = Voucher.objects.create(
@@ -2233,63 +2233,6 @@ def test_checkout_without_delivery_method_creates_empty_delivery_method(
assert not delivery_method_info.is_method_in_valid_methods(checkout_info)
-def test_set_external_shipping_id(checkout):
- # given
- app_shipping_id = "abcd"
- initial_private_metadata = {"test": 123}
- checkout.metadata_storage.private_metadata = initial_private_metadata
- checkout.metadata_storage.save()
-
- # when
- set_external_shipping_id(checkout, app_shipping_id)
-
- # then
- assert PRIVATE_META_APP_SHIPPING_ID in checkout.metadata_storage.private_metadata
-
-
-def test_get_external_shipping_id(checkout):
- # given
- app_shipping_id = "abcd"
- initial_private_metadata = {"test": 123}
- checkout.metadata_storage.private_metadata = initial_private_metadata
- checkout.metadata_storage.save()
- set_external_shipping_id(checkout, app_shipping_id)
-
- # when
- shipping_id = get_external_shipping_id(checkout)
-
- # then
- assert shipping_id == app_shipping_id
-
-
-def test_delete_external_shipping_id(checkout):
- # given
- app_shipping_id = "abcd"
- initial_private_metadata = {"test": 123}
- checkout.metadata_storage.private_metadata = initial_private_metadata
- checkout.metadata_storage.save()
- set_external_shipping_id(checkout, app_shipping_id)
-
- # when
- delete_external_shipping_id_if_present(checkout)
-
- # then
- assert checkout.metadata_storage.private_metadata == initial_private_metadata
-
-
-def test_delete_external_shipping_id_when_external_shipping_missing(checkout):
- # given
- initial_private_metadata = {"test": 123}
- checkout.metadata_storage.private_metadata = initial_private_metadata
- checkout.metadata_storage.save()
-
- # when
- delete_external_shipping_id_if_present(checkout)
-
- # then
- assert checkout.metadata_storage.private_metadata == initial_private_metadata
-
-
def test_checkout_total_setter():
# given
currency = "USD"
diff --git a/saleor/checkout/tests/test_delivery_assignent_to_checkout.py b/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
new file mode 100644
index 0000000000..02c61b0d78
--- /dev/null
+++ b/saleor/checkout/tests/test_delivery_assignent_to_checkout.py
@@ -0,0 +1,546 @@
+from decimal import Decimal
+
+from prices import Money
+
+from ...shipping.interface import ShippingMethodData
+from ..utils import (
+ PRIVATE_META_APP_SHIPPING_ID,
+ assign_built_in_shipping_to_checkout,
+ assign_collection_point_to_checkout,
+ assign_external_shipping_to_checkout,
+ get_external_shipping_id,
+ remove_delivery_method_from_checkout,
+ remove_external_shipping_from_checkout,
+)
+
+
+def test_remove_delivery_method_from_checkout_with_cc(
+ checkout_with_delivery_method_for_cc,
+):
+ # given
+ expected_updated_fields = {"collection_point_id", "shipping_address_id"}
+ # when
+ updated_fields = remove_delivery_method_from_checkout(
+ checkout_with_delivery_method_for_cc
+ )
+
+ # then
+ assert expected_updated_fields == set(updated_fields)
+ assert checkout_with_delivery_method_for_cc.collection_point_id is None
+ assert checkout_with_delivery_method_for_cc.shipping_address_id is None
+
+
+def test_remove_delivery_method_from_checkout_with_external_shipping(
+ checkout_with_item,
+):
+ # given
+ checkout_with_item.external_shipping_method_id = "abd"
+ checkout_with_item.shipping_method_name = "Ext shipping"
+
+ expected_updated_fields = {"shipping_method_name", "external_shipping_method_id"}
+ # when
+ updated_fields = remove_delivery_method_from_checkout(checkout_with_item)
+
+ # then
+ assert expected_updated_fields == set(updated_fields)
+ assert checkout_with_item.external_shipping_method_id is None
+ assert checkout_with_item.shipping_method_name is None
+
+
+def test_remove_delivery_method_from_checkout_with_built_in_shipping(
+ checkout_with_item, shipping_method
+):
+ # given
+ checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.shipping_method_name = shipping_method.name
+
+ expected_updated_fields = {"shipping_method_id", "shipping_method_name"}
+ # when
+ updated_fields = remove_delivery_method_from_checkout(checkout_with_item)
+
+ # then
+ assert expected_updated_fields == set(updated_fields)
+ assert checkout_with_item.shipping_method is None
+ assert checkout_with_item.shipping_method_name is None
+
+
+def test_remove_delivery_method_from_checkout_without_method(checkout_with_item):
+ # given
+ expected_updated_fields = []
+
+ # when
+ updated_fields = remove_delivery_method_from_checkout(checkout_with_item)
+
+ # then
+ assert expected_updated_fields == updated_fields
+
+
+def test_assign_external_shipping_to_checkout_with_cc(
+ checkout_with_delivery_method_for_cc,
+):
+ # given
+ app_shipping_id = "abcd"
+ app_shipping_name = "Shipping"
+ external_shipping_data = ShippingMethodData(
+ name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
+ )
+ checkout = checkout_with_delivery_method_for_cc
+
+ expected_updated_fields = {
+ "external_shipping_method_id",
+ "shipping_method_name",
+ "collection_point_id",
+ "shipping_address_id",
+ }
+
+ # when
+ fields_to_updated = assign_external_shipping_to_checkout(
+ checkout, external_shipping_data
+ )
+
+ # then
+ assert expected_updated_fields == set(fields_to_updated)
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+ assert checkout.external_shipping_method_id == app_shipping_id
+ assert checkout.shipping_method_name == app_shipping_name
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_address_id is None
+
+
+def test_assign_external_shipping_to_checkout_without_delivery_method(checkout):
+ # given
+ app_shipping_id = "abcd"
+ app_shipping_name = "Shipping"
+ external_shipping_data = ShippingMethodData(
+ name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
+ )
+
+ expected_updated_fields = {
+ "external_shipping_method_id",
+ "shipping_method_name",
+ }
+
+ # when
+ fields_to_updated = assign_external_shipping_to_checkout(
+ checkout, external_shipping_data
+ )
+
+ # then
+ assert expected_updated_fields == set(fields_to_updated)
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+ assert checkout.external_shipping_method_id == app_shipping_id
+ assert checkout.shipping_method_name == app_shipping_name
+
+
+def test_assign_external_shipping_to_checkout_with_built_in_shipping(
+ checkout_with_item, shipping_method
+):
+ # given
+ app_shipping_id = "abcd"
+ app_shipping_name = "Shipping"
+ external_shipping_data = ShippingMethodData(
+ name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
+ )
+ checkout_with_item.shipping_method = shipping_method
+ checkout = checkout_with_item
+
+ expected_updated_fields = {
+ "external_shipping_method_id",
+ "shipping_method_name",
+ "shipping_method_id",
+ }
+
+ # when
+ fields_to_updated = assign_external_shipping_to_checkout(
+ checkout, external_shipping_data
+ )
+
+ # then
+ assert expected_updated_fields == set(fields_to_updated)
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+ assert checkout.external_shipping_method_id == app_shipping_id
+ assert checkout.shipping_method_name == app_shipping_name
+ assert checkout.shipping_method_id is None
+
+
+def test_assign_external_shipping_to_checkout_with_different_external_shipping(
+ checkout_with_item,
+):
+ # given
+ app_shipping_id = "abcd"
+ app_shipping_name = "Shipping"
+ external_shipping_data = ShippingMethodData(
+ name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
+ )
+ checkout = checkout_with_item
+ checkout.external_shipping_method_id = "different-shipp"
+ checkout.shipping_method_name = "Ext shipping"
+
+ expected_updated_fields = {
+ "external_shipping_method_id",
+ "shipping_method_name",
+ }
+
+ # when
+ fields_to_updated = assign_external_shipping_to_checkout(
+ checkout, external_shipping_data
+ )
+
+ # then
+ assert expected_updated_fields == set(fields_to_updated)
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+ assert checkout.external_shipping_method_id == app_shipping_id
+ assert checkout.shipping_method_name == app_shipping_name
+
+
+def test_assign_external_shipping_to_checkout_with_the_same_shipping_method(
+ checkout_with_item, shipping_method
+):
+ # given
+ app_shipping_id = "abcd"
+ app_shipping_name = "Shipping"
+ external_shipping_data = ShippingMethodData(
+ name=app_shipping_name, id=app_shipping_id, price=Money(0, "USD")
+ )
+ checkout = checkout_with_item
+ checkout.external_shipping_method_id = app_shipping_id
+ checkout.shipping_method_name = app_shipping_name
+
+ # when
+ fields_to_updated = assign_external_shipping_to_checkout(
+ checkout, external_shipping_data
+ )
+
+ # then
+ assert not fields_to_updated
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+ assert checkout.external_shipping_method_id == app_shipping_id
+ assert checkout.shipping_method_name == app_shipping_name
+
+
+def test_assign_built_in_shipping_to_checkout_without_delivery_method(
+ checkout, shipping_method
+):
+ # given
+ expected_updated_fields = {"shipping_method_id", "shipping_method_name"}
+ shipping_method_data = ShippingMethodData(
+ id=str(shipping_method.id),
+ name=shipping_method.name,
+ price=Money(10, checkout.currency),
+ )
+ # when
+ fields_to_update = assign_built_in_shipping_to_checkout(
+ checkout, shipping_method_data
+ )
+
+ # then
+ assert expected_updated_fields == set(fields_to_update)
+ assert checkout.shipping_method == shipping_method
+ assert checkout.shipping_method_name == shipping_method.name
+
+
+def test_assign_built_in_shipping_to_checkout_with_cc(
+ checkout_with_delivery_method_for_cc, shipping_method
+):
+ # given
+ checkout = checkout_with_delivery_method_for_cc
+ expected_updated_fields = {
+ "shipping_method_id",
+ "shipping_method_name",
+ "collection_point_id",
+ "shipping_address_id",
+ }
+ shipping_method_data = ShippingMethodData(
+ id=str(shipping_method.id),
+ name=shipping_method.name,
+ price=Money(10, checkout.currency),
+ )
+
+ # when
+ fields_to_update = assign_built_in_shipping_to_checkout(
+ checkout, shipping_method_data
+ )
+ assert expected_updated_fields == set(fields_to_update)
+ assert checkout.shipping_method == shipping_method
+ assert checkout.shipping_method_name == shipping_method.name
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_address_id is None
+
+
+def test_assign_built_in_shipping_to_checkout_with_external_shipping_method(
+ checkout, shipping_method
+):
+ # given
+ checkout.external_shipping_method_id = "ext-id"
+ checkout.shipping_method_name = "Ext default"
+ expected_updated_fields = {
+ "shipping_method_id",
+ "shipping_method_name",
+ "external_shipping_method_id",
+ }
+ shipping_method_data = ShippingMethodData(
+ id=str(shipping_method.id),
+ name=shipping_method.name,
+ price=Money(10, checkout.currency),
+ )
+
+ # when
+ fields_to_update = assign_built_in_shipping_to_checkout(
+ checkout, shipping_method_data
+ )
+ assert expected_updated_fields == set(fields_to_update)
+ assert checkout.shipping_method == shipping_method
+ assert checkout.shipping_method_name == shipping_method.name
+ assert checkout.external_shipping_method_id is None
+
+
+def test_assign_built_in_shipping_to_checkout_with_different_shipping_method(
+ checkout, shipping_method, shipping_method_weight_based
+):
+ # given
+ checkout.shipping_method = shipping_method_weight_based
+ checkout.shipping_method_name = shipping_method_weight_based.name
+
+ shipping_method_data = ShippingMethodData(
+ id=str(shipping_method.id),
+ name=shipping_method.name,
+ price=Money(10, checkout.currency),
+ )
+
+ expected_updated_fields = {
+ "shipping_method_id",
+ "shipping_method_name",
+ }
+
+ # when
+ fields_to_update = assign_built_in_shipping_to_checkout(
+ checkout, shipping_method_data
+ )
+
+ # then
+ assert expected_updated_fields == set(fields_to_update)
+ assert checkout.shipping_method == shipping_method
+ assert checkout.shipping_method_name == shipping_method.name
+
+
+def test_assign_built_in_shipping_to_checkout_with_the_same_shipping_method(
+ checkout, shipping_method
+):
+ # given
+ checkout.shipping_method = shipping_method
+ checkout.shipping_method_name = shipping_method.name
+
+ shipping_method_data = ShippingMethodData(
+ id=str(shipping_method.id),
+ name=shipping_method.name,
+ price=Money(10, checkout.currency),
+ )
+
+ # when
+ fields_to_update = assign_built_in_shipping_to_checkout(
+ checkout, shipping_method_data
+ )
+
+ # then
+ assert not fields_to_update
+ assert checkout.shipping_method == shipping_method
+ assert checkout.shipping_method_name == shipping_method.name
+
+
+def test_assign_collection_point_to_checkout_without_delivery_method(
+ checkout, warehouses_for_cc
+):
+ # given
+ collection_point = warehouses_for_cc[0]
+ expected_updated_fields = {"collection_point_id", "shipping_address_id"}
+
+ # when
+ fields_to_update = assign_collection_point_to_checkout(checkout, collection_point)
+
+ # then
+ assert expected_updated_fields == set(fields_to_update)
+
+ assert checkout.collection_point == collection_point
+ assert checkout.shipping_address == collection_point.address
+ assert int(checkout.shipping_address_id) != int(collection_point.address.id)
+
+
+def test_assign_collection_point_to_checkout_with_external_shipping_method(
+ checkout, warehouses_for_cc
+):
+ # given
+ checkout.external_shipping_method_id = "ext-id"
+ checkout.shipping_method_name = "Ext default"
+
+ collection_point = warehouses_for_cc[0]
+ expected_updated_fields = {
+ "collection_point_id",
+ "shipping_address_id",
+ "external_shipping_method_id",
+ "shipping_method_name",
+ }
+
+ # when
+ fields_to_update = assign_collection_point_to_checkout(checkout, collection_point)
+
+ # then
+ assert expected_updated_fields == set(fields_to_update)
+ assert checkout.collection_point == collection_point
+ assert checkout.shipping_address == collection_point.address
+ assert int(checkout.shipping_address_id) != int(collection_point.address.id)
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+
+def test_assign_collection_point_to_checkout_with_shipping_method(
+ checkout, shipping_method_weight_based, warehouses_for_cc
+):
+ # given
+ checkout.shipping_method = shipping_method_weight_based
+ checkout.shipping_method_name = shipping_method_weight_based.name
+
+ collection_point = warehouses_for_cc[0]
+ expected_updated_fields = {
+ "collection_point_id",
+ "shipping_address_id",
+ "shipping_method_id",
+ "shipping_method_name",
+ }
+
+ # when
+ fields_to_update = assign_collection_point_to_checkout(checkout, collection_point)
+
+ # then
+ assert expected_updated_fields == set(fields_to_update)
+ assert checkout.collection_point == collection_point
+ assert checkout.shipping_address == collection_point.address
+ assert int(checkout.shipping_address_id) != int(collection_point.address.id)
+ assert checkout.shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+
+def test_assign_collection_point_to_checkout_with_different_cc(
+ checkout, warehouses_for_cc, address_other_country
+):
+ # given
+ previous_collection_point = warehouses_for_cc[1]
+ previous_collection_point.address = address_other_country
+
+ new_collection_point = warehouses_for_cc[0]
+
+ checkout.collection_point = previous_collection_point
+ checkout.shipping_address = previous_collection_point.address
+
+ expected_updated_fields = {
+ "collection_point_id",
+ "shipping_address_id",
+ }
+
+ # when
+ fields_to_update = assign_collection_point_to_checkout(
+ checkout, new_collection_point
+ )
+
+ # then
+ assert expected_updated_fields == set(fields_to_update)
+ assert checkout.collection_point == new_collection_point
+ assert checkout.shipping_address == new_collection_point.address
+ assert int(checkout.shipping_address_id) != int(new_collection_point.address.id)
+
+
+def test_assign_collection_point_to_checkout_with_the_same_cc(
+ checkout, warehouses_for_cc, address_other_country
+):
+ # given
+ collection_point = warehouses_for_cc[0]
+
+ checkout.collection_point = collection_point
+ checkout.shipping_address = collection_point.address.get_copy()
+
+ # when
+ fields_to_update = assign_collection_point_to_checkout(checkout, collection_point)
+
+ # then
+ assert not fields_to_update
+ assert checkout.collection_point == collection_point
+ assert checkout.shipping_address == collection_point.address
+ assert int(checkout.shipping_address_id) != int(collection_point.address.id)
+
+
+def test_get_external_shipping_id_from_metadata(checkout):
+ # given
+ app_shipping_id = "abcd"
+ initial_private_metadata = {PRIVATE_META_APP_SHIPPING_ID: app_shipping_id}
+ checkout.metadata_storage.private_metadata = initial_private_metadata
+ checkout.metadata_storage.save()
+
+ # when
+ shipping_id = get_external_shipping_id(checkout)
+
+ # then
+ assert shipping_id == app_shipping_id
+
+
+def test_get_external_shipping_id(checkout):
+ # given
+ app_shipping_id = "abcd"
+ checkout.external_shipping_method_id = app_shipping_id
+
+ # when
+ shipping_id = get_external_shipping_id(checkout)
+
+ # then
+ assert shipping_id == app_shipping_id
+
+
+def test_remove_external_shipping_from_checkout(checkout):
+ # given
+ app_shipping_id = "abcd"
+ expected_private_metadata = {"test": "123"}
+ initial_private_metadata = {PRIVATE_META_APP_SHIPPING_ID: app_shipping_id}
+ checkout.external_shipping_method_id = app_shipping_id
+
+ initial_private_metadata.update(expected_private_metadata)
+ checkout.metadata_storage.private_metadata = initial_private_metadata
+ checkout.metadata_storage.save()
+
+ # when
+ remove_external_shipping_from_checkout(checkout)
+
+ # then
+ assert checkout.metadata_storage.private_metadata == expected_private_metadata
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_name is None
+ assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
+
+
+def test_remove_external_shipping_from_checkout_with_save(checkout):
+ # given
+ app_shipping_id = "abcd"
+ expected_private_metadata = {"test": "123"}
+ initial_private_metadata = {PRIVATE_META_APP_SHIPPING_ID: app_shipping_id}
+ checkout.external_shipping_method_id = app_shipping_id
+
+ initial_private_metadata.update(expected_private_metadata)
+ checkout.metadata_storage.private_metadata = initial_private_metadata
+ checkout.metadata_storage.save()
+
+ # when
+ remove_external_shipping_from_checkout(checkout, save=True)
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.metadata_storage.private_metadata == expected_private_metadata
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_name is None
+ assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 8c5ab37d1f..27a95bcb5c 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1005,9 +1005,10 @@ def get_valid_collection_points_for_checkout(
def clear_delivery_method(checkout_info: "CheckoutInfo"):
checkout = checkout_info.checkout
- checkout.collection_point = None
- checkout.shipping_method = None
- checkout_info.shipping_method = None
+ updated_fields = remove_delivery_method_from_checkout(checkout_info.checkout)
+
+ if "collection_point_id" in updated_fields:
+ checkout_info.shipping_address = checkout_info.checkout.shipping_address
update_delivery_method_lists_for_checkout_info(
checkout_info=checkout_info,
@@ -1017,15 +1018,13 @@ def clear_delivery_method(checkout_info: "CheckoutInfo"):
lines=checkout_info.lines,
shipping_channel_listings=checkout_info.shipping_channel_listings,
)
-
- checkout.save(
- update_fields=[
- "shipping_method",
- "collection_point",
- "last_change",
- ]
- )
- delete_external_shipping_id_if_present(checkout=checkout)
+ if updated_fields:
+ checkout.save(
+ update_fields=updated_fields
+ + [
+ "last_change",
+ ]
+ )
def is_fully_paid(
@@ -1096,15 +1095,129 @@ def validate_variants_in_checkout_lines(lines: list["CheckoutLineInfo"]):
)
-def set_external_shipping_id(checkout: Checkout, app_shipping_id: str):
- metadata = get_or_create_checkout_metadata(checkout)
- metadata.store_value_in_private_metadata(
- {PRIVATE_META_APP_SHIPPING_ID: app_shipping_id}
+def _remove_external_shipping_from_metadata(checkout: Checkout):
+ metadata = get_checkout_metadata(checkout)
+ if not metadata:
+ return
+
+ field_deleted = metadata.delete_value_from_private_metadata(
+ PRIVATE_META_APP_SHIPPING_ID
)
- metadata.save()
+ if field_deleted:
+ metadata.save(update_fields=["private_metadata"])
+
+
+def remove_external_shipping_from_checkout(
+ checkout: Checkout, save: bool = False
+) -> list[str]:
+ fields_to_update = []
+ if checkout.external_shipping_method_id:
+ checkout.external_shipping_method_id = None
+ fields_to_update.append("external_shipping_method_id")
+ if checkout.shipping_method_name is not None:
+ checkout.shipping_method_name = None
+ fields_to_update.append("shipping_method_name")
+
+ if save:
+ fields_to_update.append("last_change")
+ checkout.save(update_fields=fields_to_update)
+
+ _remove_external_shipping_from_metadata(checkout)
+ return fields_to_update
+
+
+def remove_built_in_shipping_from_checkout(checkout: Checkout) -> list[str]:
+ fields_to_update = []
+ if checkout.shipping_method_id:
+ checkout.shipping_method_id = None
+ fields_to_update.append("shipping_method_id")
+ if checkout.shipping_method_name is not None:
+ checkout.shipping_method_name = None
+ fields_to_update.append("shipping_method_name")
+ return fields_to_update
+
+
+def remove_click_and_collect_from_checkout(checkout: Checkout) -> list[str]:
+ fields_to_update = []
+ if checkout.collection_point_id:
+ checkout.collection_point_id = None
+ fields_to_update.append("collection_point_id")
+ if checkout.shipping_address_id:
+ checkout.shipping_address = None
+ fields_to_update.append("shipping_address_id")
+ return fields_to_update
+
+
+def remove_delivery_method_from_checkout(checkout: Checkout) -> list[str]:
+ fields_to_update = []
+ fields_to_update += remove_built_in_shipping_from_checkout(checkout)
+ fields_to_update += remove_click_and_collect_from_checkout(checkout)
+ fields_to_update += remove_external_shipping_from_checkout(checkout)
+ return fields_to_update
+
+
+def assign_external_shipping_to_checkout(
+ checkout: Checkout, external_shipping_method_data: ShippingMethodData
+) -> list[str]:
+ fields_to_update = []
+ fields_to_update += remove_built_in_shipping_from_checkout(checkout)
+ fields_to_update += remove_click_and_collect_from_checkout(checkout)
+
+ # make sure that we don't have obsolete data for shipping methods stored in
+ # private metadata
+ _remove_external_shipping_from_metadata(checkout=checkout)
+
+ if checkout.external_shipping_method_id != external_shipping_method_data.id:
+ checkout.external_shipping_method_id = external_shipping_method_data.id
+ fields_to_update.append("external_shipping_method_id")
+ if checkout.shipping_method_name != external_shipping_method_data.name:
+ checkout.shipping_method_name = external_shipping_method_data.name
+ fields_to_update.append("shipping_method_name")
+
+ return fields_to_update
+
+
+def assign_built_in_shipping_to_checkout(
+ checkout: Checkout, shipping_method_data: ShippingMethodData
+) -> list[str]:
+ fields_to_update = []
+ fields_to_update += remove_external_shipping_from_checkout(checkout)
+ fields_to_update += remove_click_and_collect_from_checkout(checkout)
+
+ if checkout.shipping_method_id != int(shipping_method_data.id):
+ checkout.shipping_method_id = shipping_method_data.id
+ fields_to_update.append("shipping_method_id")
+ if checkout.shipping_method_name != shipping_method_data.name:
+ checkout.shipping_method_name = shipping_method_data.name
+ fields_to_update.append("shipping_method_name")
+ return fields_to_update
+
+
+def assign_collection_point_to_checkout(
+ checkout, collection_point: Warehouse
+) -> list[str]:
+ fields_to_update = []
+ fields_to_update += remove_external_shipping_from_checkout(checkout)
+ fields_to_update += remove_built_in_shipping_from_checkout(checkout)
+ if checkout.collection_point_id != collection_point.id:
+ checkout.collection_point_id = collection_point.id
+ fields_to_update.append("collection_point_id")
+ if checkout.shipping_address != collection_point.address:
+ checkout.shipping_address = collection_point.address.get_copy()
+ fields_to_update.append("shipping_address_id")
+
+ return fields_to_update
def get_external_shipping_id(container: Union["Checkout", "Order"]):
+ if isinstance(container, Checkout):
+ if container.external_shipping_method_id:
+ return container.external_shipping_method_id
+ # For order & fallback to previous checkout storage method
+ return _get_external_shipping_id_from_meta(container)
+
+
+def _get_external_shipping_id_from_meta(container: Union["Checkout", "Order"]):
metadata_object: ModelWithMetadata | None
if isinstance(container, Checkout):
metadata_object = get_checkout_metadata(container)
@@ -1115,19 +1228,6 @@ def get_external_shipping_id(container: Union["Checkout", "Order"]):
return metadata_object.get_value_from_private_metadata(PRIVATE_META_APP_SHIPPING_ID)
-def delete_external_shipping_id_if_present(checkout: Checkout):
- """Delete external shipping key if present in metadata."""
- metadata = get_checkout_metadata(checkout)
- if not metadata:
- return
-
- field_deleted = metadata.delete_value_from_private_metadata(
- PRIVATE_META_APP_SHIPPING_ID
- )
- if field_deleted:
- metadata.save(update_fields=["private_metadata"])
-
-
@allow_writer()
def create_checkout_metadata(checkout: "Checkout"):
return CheckoutMetadata.objects.create(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
index f553ab754d..de9e9c2c72 100644
--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
@@ -1,7 +1,8 @@
+from typing import TYPE_CHECKING
+
import graphene
from django.core.exceptions import ValidationError
-from ....checkout.actions import call_checkout_info_event
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import (
CheckoutInfo,
@@ -9,14 +10,10 @@ from ....checkout.fetch import (
fetch_checkout_info,
fetch_checkout_lines,
)
-from ....checkout.utils import (
- delete_external_shipping_id_if_present,
- invalidate_checkout,
- is_shipping_required,
- set_external_shipping_id,
-)
+from ....checkout.utils import is_shipping_required
from ....shipping import interface as shipping_interface
from ....shipping import models as shipping_models
+from ....shipping.interface import ShippingMethodData
from ....shipping.utils import convert_to_shipping_method_data
from ....warehouse import models as warehouse_models
from ....webhook.const import APP_ID_PREFIX
@@ -33,7 +30,15 @@ from ...plugins.dataloaders import get_plugin_manager_promise
from ...shipping.types import ShippingMethod
from ...warehouse.types import Warehouse
from ..types import Checkout
-from .utils import ERROR_DOES_NOT_SHIP, clean_delivery_method, get_checkout
+from .utils import (
+ ERROR_DOES_NOT_SHIP,
+ assign_delivery_method_to_checkout,
+ clean_delivery_method,
+ get_checkout,
+)
+
+if TYPE_CHECKING:
+ from ....plugins.manager import PluginsManager
class CheckoutDeliveryMethodUpdate(BaseMutation):
@@ -78,16 +83,29 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
]
@classmethod
- def perform_on_shipping_method(
+ def get_collection_point_as_delivery_method_data(
cls,
+ checkout_info: CheckoutInfo,
+ delivery_method_id: str,
info: ResolveInfo,
- shipping_method_id,
- checkout_info,
- lines,
- checkout,
- manager,
- ):
- shipping_method = cls.get_node_or_error(
+ ) -> warehouse_models.Warehouse:
+ collection_point = cls.get_node_or_error(
+ info,
+ delivery_method_id,
+ only_type=Warehouse,
+ field="delivery_method_id",
+ qs=warehouse_models.Warehouse.objects.select_related("address"),
+ )
+ return collection_point
+
+ @classmethod
+ def get_built_in_shipping_method_as_delivery_method_data(
+ cls,
+ checkout_info: CheckoutInfo,
+ shipping_method_id: str,
+ info: ResolveInfo,
+ ) -> ShippingMethodData:
+ shipping_method: shipping_models.ShippingMethod = cls.get_node_or_error(
info,
shipping_method_id,
only_type=ShippingMethod,
@@ -111,40 +129,22 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
}
)
delivery_method = convert_to_shipping_method_data(shipping_method, listing)
-
- cls._check_delivery_method(
- checkout_info, lines, shipping_method=delivery_method, collection_point=None
- )
-
- cls._update_delivery_method(
- manager,
- checkout_info,
- lines,
- shipping_method=shipping_method,
- external_shipping_method=None,
- collection_point=None,
- )
- return CheckoutDeliveryMethodUpdate(
- checkout=SyncWebhookControlContext(node=checkout)
- )
+ return delivery_method
@classmethod
- def perform_on_external_shipping_method(
+ def get_external_shipping_method_as_delivery_method_data(
cls,
- info: ResolveInfo,
- shipping_method_id,
- checkout_info,
- lines,
- checkout,
- manager,
- ):
+ checkout_info: CheckoutInfo,
+ shipping_method_id: str,
+ manager: "PluginsManager",
+ ) -> ShippingMethodData:
delivery_method = manager.get_shipping_method(
- checkout=checkout,
- channel_slug=checkout.channel.slug,
+ checkout=checkout_info.checkout,
+ channel_slug=checkout_info.channel.slug,
shipping_method_id=shipping_method_id,
)
- if delivery_method is None and shipping_method_id:
+ if delivery_method is None:
raise ValidationError(
{
"delivery_method_id": ValidationError(
@@ -153,64 +153,19 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
)
}
)
-
- cls._check_delivery_method(
- checkout_info, lines, shipping_method=delivery_method, collection_point=None
- )
-
- cls._update_delivery_method(
- manager,
- checkout_info,
- lines,
- shipping_method=None,
- external_shipping_method=delivery_method,
- collection_point=None,
- )
- return CheckoutDeliveryMethodUpdate(
- checkout=SyncWebhookControlContext(node=checkout)
- )
-
- @classmethod
- def perform_on_collection_point(
- cls,
- collection_point,
- checkout_info,
- lines,
- checkout,
- manager,
- ):
- cls._check_delivery_method(
- checkout_info,
- lines,
- shipping_method=None,
- collection_point=collection_point,
- )
- cls._update_delivery_method(
- manager,
- checkout_info,
- lines,
- shipping_method=None,
- external_shipping_method=None,
- collection_point=collection_point,
- )
- return CheckoutDeliveryMethodUpdate(
- checkout=SyncWebhookControlContext(node=checkout)
- )
+ return delivery_method
@staticmethod
def _check_delivery_method(
checkout_info,
lines,
- *,
- shipping_method: shipping_interface.ShippingMethodData | None,
- collection_point: Warehouse | None,
+ delivery_method_data: ShippingMethodData | warehouse_models.Warehouse,
) -> None:
- delivery_method = shipping_method
- error_msg = "This shipping method is not applicable."
-
- if collection_point is not None:
- delivery_method = collection_point
+ delivery_method = delivery_method_data
+ if isinstance(delivery_method, warehouse_models.Warehouse):
error_msg = "This pick up point is not applicable."
+ else:
+ error_msg = "This shipping method is not applicable."
delivery_method_is_valid = clean_delivery_method(
checkout_info=checkout_info, method=delivery_method
@@ -225,50 +180,6 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
}
)
- @classmethod
- def _update_delivery_method(
- cls,
- manager,
- checkout_info: "CheckoutInfo",
- lines: list["CheckoutLineInfo"],
- *,
- shipping_method: ShippingMethod | None,
- external_shipping_method: shipping_interface.ShippingMethodData | None,
- collection_point: Warehouse | None,
- ) -> None:
- checkout_fields_to_update = ["shipping_method", "collection_point"]
- checkout = checkout_info.checkout
- if external_shipping_method:
- set_external_shipping_id(
- checkout=checkout, app_shipping_id=external_shipping_method.id
- )
- else:
- delete_external_shipping_id_if_present(checkout=checkout)
-
- # Clear checkout shipping address if it was switched from C&C.
- if checkout.collection_point_id and not collection_point:
- checkout.shipping_address = None
- checkout_fields_to_update += ["shipping_address"]
-
- checkout.shipping_method = shipping_method
- checkout.collection_point = collection_point
- if collection_point is not None:
- checkout.shipping_address = collection_point.address.get_copy()
- checkout_info.shipping_address = checkout.shipping_address
- checkout_fields_to_update += ["shipping_address"]
- invalidate_prices_updated_fields = invalidate_checkout(
- checkout_info, lines, manager, save=False
- )
- checkout.save(
- update_fields=checkout_fields_to_update + invalidate_prices_updated_fields
- )
- call_checkout_info_event(
- manager,
- event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
- checkout_info=checkout_info,
- lines=lines,
- )
-
@staticmethod
def _resolve_delivery_method_type(id_) -> str | None:
if id_ is None:
@@ -290,17 +201,43 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
return str_type
- @staticmethod
- def validate_collection_point(checkout_info, collection_point):
- if collection_point not in checkout_info.valid_pick_up_points:
- raise ValidationError(
- {
- "delivery_method_id": ValidationError(
- "This pick up point is not applicable.",
- code=CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.value,
- )
- }
+ @classmethod
+ def get_delivery_method_data(
+ cls,
+ checkout_info: CheckoutInfo,
+ lines_info: list[CheckoutLineInfo],
+ delivery_method_id: str,
+ manager: "PluginsManager",
+ info: ResolveInfo,
+ ) -> shipping_interface.ShippingMethodData | warehouse_models.Warehouse | None:
+ if delivery_method_id is None:
+ return None
+
+ delivery_method_data: ShippingMethodData | warehouse_models.Warehouse | None = (
+ None
+ )
+ type_name = cls._resolve_delivery_method_type(delivery_method_id)
+ if type_name == "Warehouse":
+ delivery_method_data = cls.get_collection_point_as_delivery_method_data(
+ checkout_info, delivery_method_id, info
+ )
+ elif type_name == "ShippingMethod":
+ delivery_method_data = (
+ cls.get_built_in_shipping_method_as_delivery_method_data(
+ checkout_info, delivery_method_id, info
+ )
)
+ elif type_name == APP_ID_PREFIX:
+ delivery_method_data = (
+ cls.get_external_shipping_method_as_delivery_method_data(
+ checkout_info, delivery_method_id, manager
+ )
+ )
+
+ if delivery_method_data:
+ cls._check_delivery_method(checkout_info, lines_info, delivery_method_data)
+
+ return delivery_method_data
@classmethod
def perform_mutation(
@@ -344,24 +281,17 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
)
}
)
- type_name = cls._resolve_delivery_method_type(delivery_method_id)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- if type_name == "Warehouse":
- collection_point = cls.get_node_or_error(
- info,
- delivery_method_id,
- only_type=Warehouse,
- field="delivery_method_id",
- qs=warehouse_models.Warehouse.objects.select_related("address"),
- )
- cls.validate_collection_point(checkout_info, collection_point)
- return cls.perform_on_collection_point(
- collection_point, checkout_info, lines, checkout, manager
- )
- if type_name == "ShippingMethod":
- return cls.perform_on_shipping_method(
- info, delivery_method_id, checkout_info, lines, checkout, manager
- )
- return cls.perform_on_external_shipping_method(
- info, delivery_method_id, checkout_info, lines, checkout, manager
+
+ delivery_method_data = cls.get_delivery_method_data(
+ checkout_info, lines, delivery_method_id, manager, info
+ )
+ assign_delivery_method_to_checkout(
+ checkout_info,
+ lines,
+ manager,
+ delivery_method_data,
+ )
+ return CheckoutDeliveryMethodUpdate(
+ checkout=SyncWebhookControlContext(checkout_info.checkout)
)
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
index 775f06a9e6..33cf0a7ad6 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
@@ -1,14 +1,17 @@
+from typing import TYPE_CHECKING
+
import graphene
from django.core.exceptions import ValidationError
-from ....checkout.actions import call_checkout_info_event
from ....checkout.error_codes import CheckoutErrorCode
-from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....checkout.fetch import (
+ CheckoutInfo,
+ CheckoutLineInfo,
+ fetch_checkout_info,
+ fetch_checkout_lines,
+)
from ....checkout.utils import (
- delete_external_shipping_id_if_present,
- invalidate_checkout,
is_shipping_required,
- set_external_shipping_id,
)
from ....shipping import interface as shipping_interface
from ....shipping import models as shipping_models
@@ -26,7 +29,15 @@ from ...core.utils import WebhookEventInfo, from_global_id_or_error
from ...plugins.dataloaders import get_plugin_manager_promise
from ...shipping.types import ShippingMethod
from ..types import Checkout
-from .utils import ERROR_DOES_NOT_SHIP, clean_delivery_method, get_checkout
+from .utils import (
+ ERROR_DOES_NOT_SHIP,
+ assign_delivery_method_to_checkout,
+ clean_delivery_method,
+ get_checkout,
+)
+
+if TYPE_CHECKING:
+ from ....plugins.manager import PluginsManager
class CheckoutShippingMethodUpdate(BaseMutation):
@@ -91,76 +102,15 @@ class CheckoutShippingMethodUpdate(BaseMutation):
return str_type
- @classmethod
- def perform_mutation(
- cls,
- _root,
- info: ResolveInfo,
- /,
- *,
- checkout_id=None,
- id=None,
- shipping_method_id=None,
- token=None,
- ):
- checkout = get_checkout(cls, info, checkout_id=checkout_id, token=token, id=id)
-
- use_legacy_error_flow_for_checkout = (
- checkout.channel.use_legacy_error_flow_for_checkout
- )
-
- manager = get_plugin_manager_promise(info.context).get()
-
- lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
- if use_legacy_error_flow_for_checkout and unavailable_variant_pks:
- not_available_variants_ids = {
- graphene.Node.to_global_id("ProductVariant", pk)
- for pk in unavailable_variant_pks
- }
- raise ValidationError(
- {
- "lines": ValidationError(
- "Some of the checkout lines variants are unavailable.",
- code=CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.value,
- params={"variants": not_available_variants_ids},
- )
- }
- )
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- if use_legacy_error_flow_for_checkout and not is_shipping_required(lines):
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- ERROR_DOES_NOT_SHIP,
- code=CheckoutErrorCode.SHIPPING_NOT_REQUIRED.value,
- )
- }
- )
- if shipping_method_id is None:
- return cls.remove_shipping_method(checkout, checkout_info, lines, manager)
-
- type_name = cls._resolve_delivery_method_type(shipping_method_id)
-
- if type_name == "ShippingMethod":
- return cls.perform_on_shipping_method(
- info, shipping_method_id, checkout_info, lines, checkout, manager
- )
- return cls.perform_on_external_shipping_method(
- info, shipping_method_id, checkout_info, lines, checkout, manager
- )
-
@staticmethod
def _check_delivery_method(
- checkout_info,
- lines,
- *,
- delivery_method: shipping_interface.ShippingMethodData | None,
+ checkout_info, lines, delivery_method: shipping_interface.ShippingMethodData
) -> None:
delivery_method_is_valid = clean_delivery_method(
checkout_info=checkout_info,
method=delivery_method,
)
- if not delivery_method_is_valid or not delivery_method:
+ if not delivery_method_is_valid:
raise ValidationError(
{
"shipping_method": ValidationError(
@@ -171,16 +121,13 @@ class CheckoutShippingMethodUpdate(BaseMutation):
)
@classmethod
- def perform_on_shipping_method(
+ def get_built_in_shipping_method_as_delivery_method_data(
cls,
- info: ResolveInfo,
- shipping_method_id,
checkout_info,
- lines,
- checkout,
- manager,
- ):
- shipping_method = cls.get_node_or_error(
+ shipping_method_id,
+ info: ResolveInfo,
+ ) -> shipping_interface.ShippingMethodData:
+ shipping_method: shipping_models.ShippingMethod = cls.get_node_or_error(
info,
shipping_method_id,
only_type=ShippingMethod,
@@ -202,96 +149,116 @@ class CheckoutShippingMethodUpdate(BaseMutation):
)
}
)
- delivery_method = convert_to_shipping_method_data(shipping_method, listing)
-
- cls._check_delivery_method(
- checkout_info, lines, delivery_method=delivery_method
- )
-
- checkout.shipping_method = shipping_method
- invalidate_prices_updated_fields = invalidate_checkout(
- checkout_info, lines, manager, save=False
- )
- checkout.save(
- update_fields=[
- "shipping_method",
- ]
- + invalidate_prices_updated_fields
- )
- delete_external_shipping_id_if_present(checkout=checkout)
-
- call_checkout_info_event(
- manager,
- event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
- checkout_info=checkout_info,
- lines=lines,
- )
- return CheckoutShippingMethodUpdate(
- checkout=SyncWebhookControlContext(node=checkout)
- )
+ return convert_to_shipping_method_data(shipping_method, listing)
@classmethod
- def perform_on_external_shipping_method(
+ def get_external_shipping_method_as_delivery_method_data(
cls,
- info: ResolveInfo,
- shipping_method_id,
- checkout_info,
- lines,
- checkout,
- manager,
+ checkout_info: CheckoutInfo,
+ shipping_method_id: str,
+ manager: "PluginsManager",
):
delivery_method = manager.get_shipping_method(
- checkout=checkout,
- channel_slug=checkout.channel.slug,
+ checkout=checkout_info.checkout,
+ channel_slug=checkout_info.channel.slug,
shipping_method_id=shipping_method_id,
)
+ if delivery_method is None:
+ raise ValidationError(
+ {
+ "shipping_method": ValidationError(
+ "This shipping method is not applicable.",
+ code=CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
+ )
+ }
+ )
+ return delivery_method
- cls._check_delivery_method(
- checkout_info, lines, delivery_method=delivery_method
- )
+ @classmethod
+ def get_delivery_method_data(
+ cls,
+ checkout_info: CheckoutInfo,
+ lines_info: list[CheckoutLineInfo],
+ shipping_method_id: str,
+ manager: "PluginsManager",
+ info: ResolveInfo,
+ ) -> shipping_interface.ShippingMethodData | None:
+ if shipping_method_id is None:
+ return None
- set_external_shipping_id(checkout=checkout, app_shipping_id=delivery_method.id)
- checkout.shipping_method = None
- invalidate_prices_updated_fields = invalidate_checkout(
- checkout_info, lines, manager, save=False
- )
- checkout.save(
- update_fields=[
- "shipping_method",
- ]
- + invalidate_prices_updated_fields
- )
- call_checkout_info_event(
- manager,
- event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
- checkout_info=checkout_info,
- lines=lines,
- )
+ type_name = cls._resolve_delivery_method_type(shipping_method_id)
+ if type_name == "ShippingMethod":
+ delivery_method_data = (
+ cls.get_built_in_shipping_method_as_delivery_method_data(
+ checkout_info, shipping_method_id, info
+ )
+ )
+ else:
+ delivery_method_data = (
+ cls.get_external_shipping_method_as_delivery_method_data(
+ checkout_info, shipping_method_id, manager
+ )
+ )
- return CheckoutShippingMethodUpdate(
- checkout=SyncWebhookControlContext(node=checkout)
- )
+ if delivery_method_data:
+ cls._check_delivery_method(checkout_info, lines_info, delivery_method_data)
+
+ return delivery_method_data
@classmethod
- def remove_shipping_method(cls, checkout, checkout_info, lines, manager):
- checkout.shipping_method = None
- invalidate_prices_updated_fields = invalidate_checkout(
- checkout_info, lines, manager, save=False
- )
- checkout.save(
- update_fields=[
- "shipping_method",
- ]
- + invalidate_prices_updated_fields
+ def perform_mutation(
+ cls,
+ _root,
+ info: ResolveInfo,
+ /,
+ *,
+ checkout_id=None,
+ id=None,
+ shipping_method_id=None,
+ token=None,
+ ):
+ checkout = get_checkout(cls, info, checkout_id=checkout_id, token=token, id=id)
+
+ use_legacy_error_flow_for_checkout = (
+ checkout.channel.use_legacy_error_flow_for_checkout
)
- delete_external_shipping_id_if_present(checkout=checkout)
- call_checkout_info_event(
+ manager = get_plugin_manager_promise(info.context).get()
+
+ lines, unavailable_variant_pks = fetch_checkout_lines(checkout)
+ if use_legacy_error_flow_for_checkout and unavailable_variant_pks:
+ not_available_variants_ids = {
+ graphene.Node.to_global_id("ProductVariant", pk)
+ for pk in unavailable_variant_pks
+ }
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ "Some of the checkout lines variants are unavailable.",
+ code=CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.value,
+ params={"variants": not_available_variants_ids},
+ )
+ }
+ )
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ if use_legacy_error_flow_for_checkout and not is_shipping_required(lines):
+ raise ValidationError(
+ {
+ "shipping_method": ValidationError(
+ ERROR_DOES_NOT_SHIP,
+ code=CheckoutErrorCode.SHIPPING_NOT_REQUIRED.value,
+ )
+ }
+ )
+ delivery_method_data = cls.get_delivery_method_data(
+ checkout_info, lines, shipping_method_id, manager, info
+ )
+ assign_delivery_method_to_checkout(
+ checkout_info,
+ lines,
manager,
- event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
- checkout_info=checkout_info,
- lines=lines,
+ delivery_method_data,
)
return CheckoutShippingMethodUpdate(
- checkout=SyncWebhookControlContext(node=checkout)
+ checkout=SyncWebhookControlContext(checkout_info.checkout)
)
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index ab6a2b57b3..cd70dd5aa7 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -14,14 +14,20 @@ from django.db.models import Exists, OuterRef, Q, QuerySet
from prices import Money
from ....checkout import models
+from ....checkout.actions import call_checkout_info_event
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ....checkout.utils import (
+ assign_built_in_shipping_to_checkout,
+ assign_collection_point_to_checkout,
+ assign_external_shipping_to_checkout,
calculate_checkout_quantity,
clear_delivery_method,
- delete_external_shipping_id_if_present,
get_external_shipping_id,
+ invalidate_checkout,
is_shipping_required,
+ remove_delivery_method_from_checkout,
+ remove_external_shipping_from_checkout,
)
from ....core.exceptions import InsufficientStock, PermissionDenied
from ....discount import DiscountType, DiscountValueType
@@ -37,11 +43,13 @@ from ....product.models import ProductChannelListing, ProductVariant
from ....shipping import interface as shipping_interface
from ....warehouse import models as warehouse_models
from ....warehouse.availability import check_stock_and_preorder_quantity_bulk
+from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
from ...core.validators import validate_one_of_args_is_in_mutation
from ..types import Checkout
if TYPE_CHECKING:
+ from ....plugins.manager import PluginsManager
from ...core.mutations import BaseMutation
@@ -81,8 +89,10 @@ def clean_delivery_method(
code=CheckoutErrorCode.SHIPPING_ADDRESS_NOT_SET.value,
)
- valid_methods = checkout_info.valid_delivery_methods
- return method in valid_methods
+ if isinstance(method, shipping_interface.ShippingMethodData):
+ return method in checkout_info.valid_shipping_methods
+
+ return method in checkout_info.valid_pick_up_points
def _is_external_shipping_valid(checkout_info: "CheckoutInfo") -> bool:
@@ -97,7 +107,7 @@ def update_checkout_external_shipping_method_if_invalid(
checkout_info: "CheckoutInfo", lines: list[CheckoutLineInfo]
):
if not _is_external_shipping_valid(checkout_info):
- delete_external_shipping_id_if_present(checkout_info.checkout)
+ remove_external_shipping_from_checkout(checkout_info.checkout, save=True)
def update_checkout_shipping_method_if_invalid(
@@ -587,3 +597,56 @@ def _set_checkout_base_subtotal_and_total_on_checkout_creation(
# delivery method during checkout creation
checkout.base_total = checkout.base_subtotal
checkout.save(update_fields=["base_subtotal_amount", "base_total_amount"])
+
+
+def assign_delivery_method_to_checkout(
+ checkout_info: CheckoutInfo,
+ lines_info: list[CheckoutLineInfo],
+ manager: "PluginsManager",
+ delivery_method_data: (
+ shipping_interface.ShippingMethodData | warehouse_models.Warehouse | None
+ ),
+):
+ fields_to_update = []
+ checkout = checkout_info.checkout
+ with transaction.atomic():
+ if delivery_method_data is None:
+ fields_to_update = remove_delivery_method_from_checkout(
+ checkout=checkout_info.checkout
+ )
+ checkout_info.shipping_method = None
+ checkout_info.collection_point = None
+
+ elif isinstance(delivery_method_data, shipping_interface.ShippingMethodData):
+ if delivery_method_data.is_external:
+ fields_to_update = assign_external_shipping_to_checkout(
+ checkout, delivery_method_data
+ )
+ checkout_info.shipping_method = None
+ checkout_info.collection_point = None
+ else:
+ fields_to_update = assign_built_in_shipping_to_checkout(
+ checkout, delivery_method_data
+ )
+ checkout_info.shipping_method = checkout.shipping_method
+ checkout_info.collection_point = None
+ elif isinstance(delivery_method_data, warehouse_models.Warehouse):
+ fields_to_update = assign_collection_point_to_checkout(
+ checkout, delivery_method_data
+ )
+ checkout_info.shipping_address = checkout.shipping_address
+ checkout_info.shipping_method = None
+
+ if not fields_to_update:
+ return
+
+ invalidate_prices_updated_fields = invalidate_checkout(
+ checkout_info, lines_info, manager, save=False
+ )
+ checkout.save(update_fields=fields_to_update + invalidate_prices_updated_fields)
+ call_checkout_info_event(
+ manager,
+ event_name=WebhookEventAsyncType.CHECKOUT_UPDATED,
+ checkout_info=checkout_info,
+ lines=lines_info,
+ )
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 3d976ec112..8d4accd9b8 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -4,17 +4,22 @@ from unittest.mock import patch
import graphene
import pytest
from graphene import Node
+from prices import Money
from .....checkout import calculations
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
-from .....checkout.utils import add_variants_to_checkout, set_external_shipping_id
+from .....checkout.utils import (
+ add_variants_to_checkout,
+ assign_external_shipping_to_checkout,
+)
from .....discount import RewardValueType
from .....discount.models import CheckoutLineDiscount, PromotionRule
from .....plugins.manager import get_plugins_manager
from .....product.models import Product, ProductVariant, ProductVariantChannelListing
from .....product.utils.variant_prices import update_discounted_prices_for_promotion
from .....product.utils.variants import fetch_variants_for_promotion_rules
+from .....shipping.interface import ShippingMethodData
from .....warehouse.models import Stock
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -965,14 +970,18 @@ def test_add_checkout_lines_with_external_shipping(
shipping_app,
settings,
):
+ # given
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
response_method_id = "abcd"
+ shipping_name = "Provider - Economy"
+ shipping_price = Decimal(10)
+ currency = "USD"
mock_json_response = [
{
"id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
+ "name": shipping_name,
+ "amount": shipping_price,
+ "currency": currency,
"maximum_delivery_days": "7",
}
]
@@ -981,9 +990,16 @@ def test_add_checkout_lines_with_external_shipping(
external_shipping_method_id = Node.to_global_id(
"app", f"{shipping_app.id}:{response_method_id}"
)
+ external_shipping_method = ShippingMethodData(
+ id=external_shipping_method_id,
+ name=shipping_name,
+ price=Money(shipping_price, currency),
+ )
checkout_with_single_item.shipping_address = address
- set_external_shipping_id(checkout_with_single_item, external_shipping_method_id)
+ assign_external_shipping_to_checkout(
+ checkout_with_single_item, external_shipping_method
+ )
checkout_with_single_item.save()
checkout_with_single_item.metadata_storage.save()
@@ -1026,9 +1042,13 @@ def test_add_checkout_lines_with_external_shipping(
},
],
}
+
+ # when
response = get_graphql_content(
api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
)
+
+ # then
assert not response["data"]["checkoutLinesAdd"]["errors"]
# Two api calls :
# - post-mutate() logic used to validate currently selected method
diff --git a/saleor/graphql/checkout/tests/benchmark/test_homepage.py b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
index 15c7dd6639..53af85b858 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_homepage.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
@@ -1,9 +1,12 @@
+from decimal import Decimal
from unittest.mock import patch
import pytest
from django.utils import timezone
+from prices import Money
-from .....checkout.utils import set_external_shipping_id
+from .....checkout.utils import assign_external_shipping_to_checkout
+from .....shipping.interface import ShippingMethodData
from .....webhook.transport.shipping import to_shipping_app_id
from ....tests.utils import get_graphql_content
@@ -158,18 +161,26 @@ def test_user_checkout_details_with_external_shipping_method(
# given
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
external_id = to_shipping_app_id(app, "abcd")
+ shipping_name = "Provider - Economy"
+ shipping_price = Decimal(10)
+ currency = "USD"
mock_json_response = [
{
"id": external_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
+ "name": shipping_name,
+ "amount": shipping_price,
+ "currency": currency,
"maximum_delivery_days": "7",
}
]
+
+ external_shipping_method = ShippingMethodData(
+ id=external_id, name=shipping_name, price=Money(shipping_price, currency)
+ )
+
checkout = customer_checkout
checkout.shipping_method = None
- set_external_shipping_id(checkout, external_id)
+ assign_external_shipping_to_checkout(checkout, external_shipping_method)
checkout.save()
mock_send_request.return_value = mock_json_response
query = """
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index a56538f193..91682d4921 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -13,7 +13,10 @@ from .....checkout import base_calculations, calculations
from .....checkout.actions import call_checkout_info_event
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.utils import add_variant_to_checkout, set_external_shipping_id
+from .....checkout.utils import (
+ add_variant_to_checkout,
+ assign_external_shipping_to_checkout,
+)
from .....core.models import EventDelivery
from .....discount import VoucherType
from .....plugins.manager import get_plugins_manager
@@ -22,6 +25,7 @@ from .....product.models import (
ProductChannelListing,
ProductVariantChannelListing,
)
+from .....shipping.interface import ShippingMethodData
from .....tests import race_condition
from .....warehouse.models import Stock
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
@@ -173,14 +177,18 @@ def test_checkout_add_voucher_code_by_token_with_external_shipment(
address,
settings,
):
+ # given
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
response_method_id = "abcd"
+ shipping_name = "Provider - Economy"
+ shipping_price = Decimal(10)
+ currency = "USD"
mock_json_response = [
{
"id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
- "currency": "USD",
+ "name": shipping_name,
+ "amount": shipping_price,
+ "currency": currency,
"maximum_delivery_days": "7",
}
]
@@ -190,18 +198,33 @@ def test_checkout_add_voucher_code_by_token_with_external_shipment(
"app", f"{shipping_app.id}:{response_method_id}"
)
+ external_shipping_method = ShippingMethodData(
+ id=external_shipping_method_id,
+ name=shipping_name,
+ price=Money(shipping_price, currency),
+ )
+
checkout = checkout_with_item
checkout.shipping_address = address
- set_external_shipping_id(checkout, external_shipping_method_id)
- checkout.save(update_fields=["shipping_address"])
+ assign_external_shipping_to_checkout(checkout, external_shipping_method)
+ checkout.save(
+ update_fields=[
+ "shipping_address",
+ "external_shipping_method_id",
+ "shipping_method_name",
+ ]
+ )
checkout.metadata_storage.save(update_fields=["private_metadata"])
variables = {
"id": to_global_id_or_none(checkout_with_item),
"promoCode": voucher.code,
}
+
+ # when
data = _mutate_checkout_add_promo_code(api_client, variables)
+ # then
assert not data["errors"]
assert data["checkout"]["token"] == str(checkout_with_item.token)
assert data["checkout"]["voucherCode"] == voucher.code
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index bcc869c7b2..1ec6ebcc7f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -7,6 +7,7 @@ import pytest
from django.conf import settings
from django.contrib.sites.models import Site
from django.db.models.aggregates import Sum
+from django.test import override_settings
from django.utils import timezone
from .....account.models import Address
@@ -14,6 +15,7 @@ from .....checkout import calculations
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
+from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID
from .....core.exceptions import InsufficientStock, InsufficientStockData
from .....core.taxes import TaxError, zero_money, zero_taxed_money
from .....discount import DiscountType, DiscountValueType, RewardValueType
@@ -5238,3 +5240,81 @@ def test_checkout_complete_empty_product_translation(
recalculate_with_plugins_mock.assert_not_called()
assert not len(Reservation.objects.all())
+
+
+@override_settings(
+ PLUGINS=[
+ "saleor.plugins.webhook.plugin.WebhookPlugin",
+ "saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin",
+ ]
+)
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_checkout_complete_with_external_shipping(
+ mocked_sync_webhook,
+ user_api_client,
+ checkout_with_item,
+ payment_dummy,
+ address,
+ shipping_app,
+):
+ # given
+ external_shipping_method_id = "ABC"
+ external_shipping_name = "Provider - Economy"
+ graphql_externa_method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{external_shipping_method_id}"
+ )
+ mock_json_response = [
+ {
+ "id": external_shipping_method_id,
+ "name": external_shipping_name,
+ "amount": "10",
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mocked_sync_webhook.return_value = mock_json_response
+
+ checkout = checkout_with_item
+ checkout.external_shipping_method_id = graphql_externa_method_id
+ checkout.shipping_method_name = external_shipping_name
+ checkout.shipping_address = address
+ checkout.billing_address = address
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.tax_exemption = True
+ checkout.save()
+ checkout.metadata_storage.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ payment.refresh_from_db()
+ order = payment.order
+ assert (
+ order.private_metadata[PRIVATE_META_APP_SHIPPING_ID]
+ == graphql_externa_method_id
+ )
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index 7aeb1d0d73..840a820f6c 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -6,6 +6,7 @@ import graphene
import pytest
from django.db import transaction
from django.db.models.aggregates import Sum
+from django.test import override_settings
from django.utils import timezone
from prices import TaxedMoney
@@ -16,7 +17,7 @@ from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
from .....checkout.payment_utils import update_checkout_payment_statuses
-from .....checkout.utils import add_voucher_to_checkout
+from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, add_voucher_to_checkout
from .....core.taxes import TaxError, zero_money, zero_taxed_money
from .....discount import DiscountType, DiscountValueType, RewardValueType
from .....discount.models import CheckoutLineDiscount, PromotionRule, Voucher
@@ -4787,3 +4788,77 @@ def test_complete_checkout_order_status_changed_after_creation(
order = data["order"]
assert order
assert order["status"] == OrderStatus.UNFULFILLED.upper()
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
+def test_checkout_complete_with_external_shipping_method(
+ mocked_sync_webhook,
+ user_api_client,
+ checkout_with_item,
+ transaction_item_generator,
+ address,
+ shipping_app,
+):
+ # given
+ external_shipping_method_id = "ABC"
+ external_shipping_name = "Provider - Economy"
+ graphql_externa_method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{external_shipping_method_id}"
+ )
+ mock_json_response = [
+ {
+ "id": external_shipping_method_id,
+ "name": external_shipping_name,
+ "amount": "10",
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mocked_sync_webhook.return_value = mock_json_response
+
+ checkout = checkout_with_item
+ checkout.external_shipping_method_id = graphql_externa_method_id
+ checkout.shipping_method_name = external_shipping_name
+ checkout.shipping_address = address
+ checkout.billing_address = address
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.tax_exemption = True
+ checkout.save()
+ checkout.metadata_storage.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+
+ transaction_item_generator(
+ checkout_id=checkout.pk, authorized_value=total.gross.amount
+ )
+
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=total.gross,
+ checkout_has_lines=bool(lines),
+ )
+
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ order = Order.objects.get()
+ assert (
+ order.private_metadata[PRIVATE_META_APP_SHIPPING_ID]
+ == graphql_externa_method_id
+ )
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
index 02299e165f..20c10e4943 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from unittest import mock
from unittest.mock import patch
@@ -14,12 +15,14 @@ from .....core.models import EventDelivery
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing, ProductVariantChannelListing
from .....shipping import models as shipping_models
+from .....shipping.models import ShippingZone
from .....shipping.utils import convert_to_shipping_method_data
from .....warehouse import WarehouseClickAndCollectOption
-from .....warehouse.models import Stock
+from .....warehouse.models import Stock, Warehouse
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
+from ...mutations.utils import clean_delivery_method
MUTATION_UPDATE_DELIVERY_METHOD = """
mutation checkoutDeliveryMethodUpdate($id: ID, $deliveryMethodId: ID) {
@@ -64,7 +67,6 @@ MUTATION_UPDATE_DELIVERY_METHOD = """
"""
[email protected]("is_valid_delivery_method", [True, False])
@pytest.mark.parametrize(
("delivery_method", "node_name", "attribute_name"),
[
@@ -75,64 +77,99 @@ MUTATION_UPDATE_DELIVERY_METHOD = """
)
@patch(
"saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
+ "clean_delivery_method",
+ wraps=clean_delivery_method,
)
@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "invalidate_checkout",
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
-def test_checkout_delivery_method_update(
- mock_invalidate_checkout,
- mock_clean_delivery,
+def test_checkout_delivery_method_update_not_applicable_delivery_method(
+ mocked_invalidate_checkout,
+ mocked_clean_delivery_method,
api_client,
delivery_method,
node_name,
attribute_name,
checkout_with_item_for_cc,
- is_valid_delivery_method,
):
# given
- mock_clean_delivery.return_value = is_valid_delivery_method
-
checkout = checkout_with_item_for_cc
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- shipping_method_data = delivery_method
- if attribute_name == "shipping_method":
- shipping_method_data = convert_to_shipping_method_data(
- delivery_method,
- delivery_method.channel_listings.get(),
- )
- query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = is_valid_delivery_method
+ Warehouse.objects.update(
+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,
+ )
+ ShippingZone.objects.update(countries=[])
method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
+ # when
response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
)
+
+ # then
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
checkout.refresh_from_db()
- mock_clean_delivery.assert_called_once_with(
- checkout_info=checkout_info, method=shipping_method_data
+ errors = data["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["field"] == "deliveryMethodId"
+ assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
+ assert checkout.shipping_method is None
+ assert checkout.collection_point is None
+ mocked_invalidate_checkout.assert_not_called()
+ mocked_clean_delivery_method.assert_called_once()
+
+
+ ("delivery_method", "node_name", "attribute_name"),
+ [
+ ("warehouse", "Warehouse", "collection_point"),
+ ("shipping_method", "ShippingMethod", "shipping_method"),
+ ],
+ indirect=("delivery_method",),
+)
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
+ "clean_delivery_method",
+ wraps=clean_delivery_method,
+)
+@patch(
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update(
+ mocked_invalidate_checkout,
+ mocked_clean_delivery_method,
+ api_client,
+ delivery_method,
+ node_name,
+ attribute_name,
+ checkout_with_item_for_cc,
+):
+ # given
+ checkout = checkout_with_item_for_cc
+
+ method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
)
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ checkout.refresh_from_db()
+
errors = data["errors"]
- if is_valid_delivery_method:
- assert not errors
- assert getattr(checkout, attribute_name) == delivery_method
- assert mock_invalidate_checkout.call_count == 1
- else:
- assert len(errors) == 1
- assert errors[0]["field"] == "deliveryMethodId"
- assert (
- errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
- )
- assert checkout.shipping_method is None
- assert checkout.collection_point is None
+ assert not errors
+ assert getattr(checkout, attribute_name) == delivery_method
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_clean_delivery_method.assert_called_once()
@pytest.mark.parametrize(
@@ -185,7 +222,6 @@ def test_checkout_delivery_method_update_when_line_without_channel_listing(
assert checkout.shipping_method is None
[email protected]("is_valid_delivery_method", [True, False])
@pytest.mark.parametrize(
("delivery_method", "node_name", "attribute_name"),
[
@@ -196,71 +232,102 @@ def test_checkout_delivery_method_update_when_line_without_channel_listing(
)
@patch(
"saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
+ "clean_delivery_method",
+ wraps=clean_delivery_method,
)
@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "invalidate_checkout",
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
-def test_checkout_delivery_method_update_no_checkout_metadata(
- mock_invalidate_checkout,
- mock_clean_delivery,
+def test_checkout_delivery_method_update_missing_checkout_metadata_when_not_applicable_method(
+ mocked_invalidate_checkout,
+ mocked_clean_delivery_method,
api_client,
delivery_method,
node_name,
attribute_name,
checkout_with_item_for_cc,
- is_valid_delivery_method,
):
# given
- mock_clean_delivery.return_value = is_valid_delivery_method
-
checkout = checkout_with_item_for_cc
checkout.metadata_storage.delete()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- shipping_method_data = delivery_method
- if attribute_name == "shipping_method":
- shipping_method_data = convert_to_shipping_method_data(
- delivery_method,
- delivery_method.channel_listings.get(),
- )
- query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = is_valid_delivery_method
+ Warehouse.objects.update(
+ click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,
+ )
+ ShippingZone.objects.update(countries=[])
method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
# when
response = api_client.post_graphql(
- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
)
# then
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
checkout.refresh_from_db()
- mock_clean_delivery.assert_called_once_with(
- checkout_info=checkout_info, method=shipping_method_data
+ errors = data["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["field"] == "deliveryMethodId"
+ assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
+ assert checkout.shipping_method is None
+ assert checkout.collection_point is None
+ mocked_invalidate_checkout.assert_not_called()
+ mocked_clean_delivery_method.assert_called_once()
+
+
+ ("delivery_method", "node_name", "attribute_name"),
+ [
+ ("warehouse", "Warehouse", "collection_point"),
+ ("shipping_method", "ShippingMethod", "shipping_method"),
+ ],
+ indirect=("delivery_method",),
+)
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
+ "clean_delivery_method",
+ wraps=clean_delivery_method,
+)
+@patch(
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_checkout_without_metadata(
+ mocked_invalidate_checkout,
+ mocked_clean_delivery_method,
+ api_client,
+ delivery_method,
+ node_name,
+ attribute_name,
+ checkout_with_item_for_cc,
+):
+ # given
+ checkout = checkout_with_item_for_cc
+ checkout.metadata_storage.delete()
+ method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
)
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ checkout.refresh_from_db()
+
errors = data["errors"]
- if is_valid_delivery_method:
- assert not errors
- assert getattr(checkout, attribute_name) == delivery_method
- assert mock_invalidate_checkout.call_count == 1
- else:
- assert len(errors) == 1
- assert errors[0]["field"] == "deliveryMethodId"
- assert (
- errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
- )
- assert checkout.shipping_method is None
- assert checkout.collection_point is None
+ assert not errors
+ assert getattr(checkout, attribute_name) == delivery_method
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_clean_delivery_method.assert_called_once()
[email protected]("is_valid_delivery_method", [True, False])
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@patch(
"saleor.graphql.checkout.mutations.checkout_delivery_method_update."
@@ -271,22 +338,23 @@ def test_checkout_delivery_method_update_external_shipping(
mock_send_request,
api_client,
checkout_with_item_for_cc,
- is_valid_delivery_method,
settings,
shipping_app,
channel_USD,
):
checkout = checkout_with_item_for_cc
query = MUTATION_UPDATE_DELIVERY_METHOD
- mock_clean_delivery.return_value = is_valid_delivery_method
+ mock_clean_delivery.return_value = True
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
response_method_id = "abcd"
+ response_shipping_name = "Provider - Economy"
+ response_shipping_price = "10"
mock_json_response = [
{
"id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
+ "name": response_shipping_name,
+ "amount": response_shipping_price,
"currency": "USD",
"maximum_delivery_days": "7",
}
@@ -304,22 +372,76 @@ def test_checkout_delivery_method_update_external_shipping(
checkout.refresh_from_db()
errors = data["errors"]
- if is_valid_delivery_method:
- assert not errors
- assert (
- PRIVATE_META_APP_SHIPPING_ID in checkout.metadata_storage.private_metadata
- )
- assert data["checkout"]["deliveryMethod"]["id"] == method_id
- else:
- assert len(errors) == 1
- assert errors[0]["field"] == "deliveryMethodId"
- assert (
- errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
- )
- assert (
- PRIVATE_META_APP_SHIPPING_ID
- not in checkout.metadata_storage.private_metadata
- )
+
+ assert not errors
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+ assert checkout.external_shipping_method_id
+ assert checkout.shipping_method_name == response_shipping_name
+ assert checkout.undiscounted_base_shipping_price_amount == Decimal(
+ response_shipping_price
+ )
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+
+
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
+ "clean_delivery_method"
+)
+def test_checkout_delivery_method_update_external_shipping_when_invalid(
+ mock_clean_delivery,
+ mock_send_request,
+ api_client,
+ checkout_with_item_for_cc,
+ settings,
+ shipping_app,
+ channel_USD,
+):
+ # given
+ checkout = checkout_with_item_for_cc
+ query = MUTATION_UPDATE_DELIVERY_METHOD
+ mock_clean_delivery.return_value = False
+
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "abcd"
+ response_shipping_name = "Provider - Economy"
+ response_shipping_price = "10"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": response_shipping_name,
+ "amount": response_shipping_price,
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mock_send_request.return_value = mock_json_response
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+
+ # when
+ response = api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ checkout.refresh_from_db()
+
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "deliveryMethodId"
+ assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_name is None
+ assert checkout.undiscounted_base_shipping_price_amount == Decimal(0)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -357,6 +479,11 @@ def test_checkout_delivery_method_update_deletes_external_shipping_when_not_vali
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ checkout.external_shipping_method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+ checkout.save(update_fields=["external_shipping_method_id"])
+
checkout.metadata_storage.private_metadata = {
PRIVATE_META_APP_SHIPPING_ID: graphene.Node.to_global_id(
"app", f"{shipping_app.id}:{response_method_id}"
@@ -379,6 +506,7 @@ def test_checkout_delivery_method_update_deletes_external_shipping_when_not_vali
assert (
PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
)
+ assert checkout.external_shipping_method_id is None
assert data["checkout"]["deliveryMethod"]["id"] == method_id
@@ -624,7 +752,8 @@ def test_checkout_delivery_method_update_shipping_zone_with_channel(
)
@patch(
"saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
+ "clean_delivery_method",
+ wraps=clean_delivery_method,
)
def test_checkout_delivery_method_update_valid_method_not_all_shipping_data(
mock_clean_delivery,
@@ -640,13 +769,7 @@ def test_checkout_delivery_method_update_valid_method_not_all_shipping_data(
checkout = checkout_with_item_for_cc
checkout.shipping_address = Address.objects.create(country="US")
checkout.save()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- shipping_method_data = convert_to_shipping_method_data(
- delivery_method,
- delivery_method.channel_listings.get(),
- )
+
query = MUTATION_UPDATE_DELIVERY_METHOD
mock_clean_delivery.return_value = True
@@ -659,15 +782,13 @@ def test_checkout_delivery_method_update_valid_method_not_all_shipping_data(
# then
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+
checkout.refresh_from_db()
- mock_clean_delivery.assert_called_once_with(
- checkout_info=checkout_info, method=shipping_method_data
- )
errors = data["errors"]
-
assert not errors
assert getattr(checkout, attribute_name) == delivery_method
+ mock_clean_delivery.assert_called_once()
@pytest.mark.parametrize(
@@ -865,7 +986,8 @@ def test_checkout_delivery_method_update_invalid_with_not_valid_address_data(
)
@patch(
"saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "clean_delivery_method"
+ "clean_delivery_method",
+ wraps=clean_delivery_method,
)
def test_checkout_delivery_method_update_valid_with_not_valid_address_data(
mock_clean_delivery,
@@ -887,14 +1009,7 @@ def test_checkout_delivery_method_update_valid_with_not_valid_address_data(
postal_code="53-601",
)
checkout.save()
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- shipping_method_data = convert_to_shipping_method_data(
- delivery_method,
- delivery_method.channel_listings.get(),
- )
query = MUTATION_UPDATE_DELIVERY_METHOD
mock_clean_delivery.return_value = True
@@ -908,14 +1023,10 @@ def test_checkout_delivery_method_update_valid_with_not_valid_address_data(
# then
data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
checkout.refresh_from_db()
-
- mock_clean_delivery.assert_called_once_with(
- checkout_info=checkout_info, method=shipping_method_data
- )
errors = data["errors"]
-
assert not errors
assert getattr(checkout, attribute_name) == delivery_method
+ mock_clean_delivery.assert_called_once()
@pytest.mark.parametrize(
@@ -1115,7 +1226,7 @@ def test_checkout_delivery_method_update_from_cc_to_all_warehouses_disabled_cc(
@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update.call_checkout_info_event",
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -1202,7 +1313,7 @@ def test_checkout_delivery_method_update_triggers_webhooks(
@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update.call_checkout_info_event",
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -1269,7 +1380,7 @@ def test_checkout_delivery_method_update_cc_triggers_webhooks(
# Shipping sync webhooks are called twice - first call before saving the changes in
# the checkout instance, second when generating the payload. In the second call
# checkout instance has different data and cache cannot be used.
- assert mocked_send_webhook_request_sync.call_count == 5
+ assert mocked_send_webhook_request_sync.call_count == 3
# confirm each sync webhook was called without saving event delivery
assert not EventDelivery.objects.exclude(
@@ -1299,7 +1410,7 @@ def test_checkout_delivery_method_update_cc_triggers_webhooks(
@patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update.call_checkout_info_event",
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -1403,3 +1514,772 @@ def test_checkout_delivery_method_update_external_shipping_triggers_webhooks(
tax_delivery = tax_delivery_call.args[0]
assert tax_delivery.webhook_id == tax_webhook.id
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_checkout_delivery_method_update_from_cc_to_external_shipping(
+ mocked_send_webhook_request_sync,
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ settings,
+ checkout_with_delivery_method_for_cc,
+ shipping_app,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_cc
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "abcd"
+ response_shipping_name = "Provider - Economy"
+ response_shipping_price = "10"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": response_shipping_name,
+ "amount": response_shipping_price,
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mocked_send_webhook_request_sync.return_value = mock_json_response
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+ assert data["checkout"]["deliveryMethod"]["name"] == response_shipping_name
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_address_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id == method_id
+ assert checkout.shipping_method_name == response_shipping_name
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_cc_to_none(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_delivery_method_for_cc,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_cc
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": None},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"] is None
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_address_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_name is None
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_cc_to_built_in_shipping(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_delivery_method_for_cc,
+ shipping_method,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_cc
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "deliveryMethodId": to_global_id_or_none(shipping_method),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == shipping_method.name
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_address_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id == shipping_method.id
+ assert checkout.shipping_method_name == shipping_method.name
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_cc_to_the_same_cc(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_delivery_method_for_cc,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_cc
+ collection_point = checkout.collection_point
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "deliveryMethodId": to_global_id_or_none(collection_point),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ collection_point
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == collection_point.name
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id == collection_point.id
+ assert checkout.shipping_address_id != collection_point.address.id
+ assert checkout.shipping_address == collection_point.address
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+ mocked_invalidate_checkout.assert_not_called()
+ mocked_call_checkout_info_event.assert_not_called()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_cc_to_different_cc(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_items,
+ warehouses_for_cc,
+ api_client,
+):
+ # given
+ checkout = checkout_with_items
+ checkout.collection_point = warehouses_for_cc[0]
+ checkout.shipping_address = warehouses_for_cc[0].address.get_copy()
+ checkout.save()
+
+ collection_point = warehouses_for_cc[1]
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "deliveryMethodId": to_global_id_or_none(collection_point),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ collection_point
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == collection_point.name
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id == collection_point.id
+ assert checkout.shipping_address_id != collection_point.address.id
+ assert checkout.shipping_address == collection_point.address
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_external_shipping_to_cc(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_delivery_method_for_external_shipping,
+ warehouses_for_cc,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_external_shipping
+
+ collection_point = warehouses_for_cc[1]
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "deliveryMethodId": to_global_id_or_none(collection_point),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ collection_point
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == collection_point.name
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id == collection_point.id
+ assert checkout.shipping_address_id != collection_point.address.id
+ assert checkout.shipping_address == collection_point.address
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_external_shipping_to_built_in_shipping(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_delivery_method_for_external_shipping,
+ shipping_method,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_external_shipping
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "deliveryMethodId": to_global_id_or_none(shipping_method),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == shipping_method.name
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id == shipping_method.id
+ assert checkout.shipping_method_name == shipping_method.name
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_external_shipping_to_different_external(
+ mocked_invalidate_checkout,
+ mocked_send_webhook_request_sync,
+ mocked_call_checkout_info_event,
+ settings,
+ shipping_app,
+ checkout_with_delivery_method_for_external_shipping,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_external_shipping
+
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "new-abcd"
+ response_shipping_name = "New Provider - Economy"
+ response_shipping_price = "10"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": response_shipping_name,
+ "amount": response_shipping_price,
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mocked_send_webhook_request_sync.return_value = mock_json_response
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+ assert data["checkout"]["deliveryMethod"]["name"] == response_shipping_name
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id == method_id
+ assert checkout.shipping_method_name == response_shipping_name
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_external_shipping_to_none(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_delivery_method_for_external_shipping,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_external_shipping
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": None},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"] is None
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_external_shipping_to_the_same_external(
+ mocked_invalidate_checkout,
+ mocked_send_webhook_request_sync,
+ mocked_call_checkout_info_event,
+ address,
+ settings,
+ shipping_app,
+ checkout_with_item,
+ api_client,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "new-abcd"
+ response_shipping_name = "New Provider - Economy"
+ response_shipping_price = "10"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": response_shipping_name,
+ "amount": response_shipping_price,
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+
+ mocked_send_webhook_request_sync.return_value = mock_json_response
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.external_shipping_method_id = method_id
+ checkout.shipping_method_name = response_shipping_name
+ checkout.save()
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+ assert data["checkout"]["deliveryMethod"]["name"] == response_shipping_name
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id == method_id
+ assert checkout.shipping_method_name == response_shipping_name
+
+ mocked_invalidate_checkout.assert_not_called()
+ mocked_call_checkout_info_event.assert_not_called()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_built_in_shipping_to_cc(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_shipping_method,
+ warehouses_for_cc,
+ api_client,
+):
+ # given
+ checkout = checkout_with_shipping_method
+
+ collection_point = warehouses_for_cc[1]
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "deliveryMethodId": to_global_id_or_none(collection_point),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ collection_point
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == collection_point.name
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id == collection_point.id
+ assert checkout.shipping_address_id != collection_point.address.id
+ assert checkout.shipping_address == collection_point.address
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_built_in_shipping_to_external_shipping(
+ mocked_invalidate_checkout,
+ mocked_send_webhook_request_sync,
+ mocked_call_checkout_info_event,
+ settings,
+ checkout_with_shipping_method,
+ shipping_app,
+ api_client,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "new-abcd"
+ response_shipping_name = "New Provider - Economy"
+ response_shipping_price = "10"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": response_shipping_name,
+ "amount": response_shipping_price,
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+
+ mocked_send_webhook_request_sync.return_value = mock_json_response
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+
+ checkout = checkout_with_shipping_method
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+ assert data["checkout"]["deliveryMethod"]["name"] == response_shipping_name
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id == method_id
+ assert checkout.shipping_method_name == response_shipping_name
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_built_in_shipping_to_differnt_built_in(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_shipping_method,
+ other_shipping_method,
+ api_client,
+):
+ # given
+ checkout = checkout_with_shipping_method
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "deliveryMethodId": to_global_id_or_none(other_shipping_method),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ other_shipping_method
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == other_shipping_method.name
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id == other_shipping_method.id
+ assert checkout.shipping_method_name == other_shipping_method.name
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_built_in_shipping_to_the_same_shipping(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_shipping_method,
+ api_client,
+):
+ # given
+ checkout = checkout_with_shipping_method
+
+ shipping_method = checkout.shipping_method
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "deliveryMethodId": to_global_id_or_none(shipping_method),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == shipping_method.name
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id == shipping_method.id
+ assert checkout.shipping_method_name == shipping_method.name
+
+ mocked_invalidate_checkout.assert_not_called()
+ mocked_call_checkout_info_event.assert_not_called()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_delivery_method_update_from_built_in_shipping_to_none(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_shipping_method,
+ api_client,
+):
+ # given
+ checkout = checkout_with_shipping_method
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_DELIVERY_METHOD,
+ {"id": to_global_id_or_none(checkout), "deliveryMethodId": None},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"] is None
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
index 81b516ce51..19f56af23f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from unittest import mock
from unittest.mock import patch
@@ -7,6 +8,7 @@ from django.test import override_settings
from .....account.models import Address
from .....checkout.actions import call_checkout_info_event
+from .....checkout.calculations import fetch_checkout_data
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkout
@@ -22,19 +24,31 @@ from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
MUTATION_UPDATE_SHIPPING_METHOD = """
- mutation checkoutShippingMethodUpdate(
- $id: ID, $shippingMethodId: ID){
- checkoutShippingMethodUpdate(
- id: $id, shippingMethodId: $shippingMethodId) {
- errors {
- field
- message
- code
+ mutation checkoutShippingMethodUpdate($id: ID, $shippingMethodId: ID) {
+ checkoutShippingMethodUpdate(id: $id, shippingMethodId: $shippingMethodId) {
+ errors {
+ field
+ message
+ code
+ }
+ checkout {
+ token
+ deliveryMethod {
+ __typename
+ ... on ShippingMethod {
+ name
+ id
+ translation(languageCode: EN_US) {
+ name
+ }
}
- checkout {
- token
+ ... on Warehouse {
+ name
+ id
}
+ }
}
+ }
}
"""
@@ -46,8 +60,7 @@ MUTATION_UPDATE_SHIPPING_METHOD = """
"clean_delivery_method"
)
@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "invalidate_checkout",
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update(
@@ -110,11 +123,13 @@ def test_checkout_shipping_method_update_external_shipping_method(
):
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
response_method_id = "abcd"
+ method_price = Decimal("10")
+ method_name = "Provider - Economy"
mock_json_response = [
{
"id": response_method_id,
- "name": "Provider - Economy",
- "amount": "10",
+ "name": method_name,
+ "amount": method_price,
"currency": "USD",
"maximum_delivery_days": "7",
}
@@ -136,10 +151,68 @@ def test_checkout_shipping_method_update_external_shipping_method(
data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
checkout.refresh_from_db()
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ fetch_checkout_data(
+ checkout_info,
+ manager,
+ lines,
+ )
errors = data["errors"]
assert not errors
assert data["checkout"]["token"] == str(checkout_with_item.token)
- assert PRIVATE_META_APP_SHIPPING_ID in checkout.metadata_storage.private_metadata
+
+ assert checkout.external_shipping_method_id == method_id
+ assert checkout.undiscounted_base_shipping_price_amount == method_price
+ assert checkout.shipping_method_name == method_name
+ assert (
+ PRIVATE_META_APP_SHIPPING_ID not in checkout.metadata_storage.private_metadata
+ )
+
+
+def test_checkout_shipping_method_update_overwrites_external_shipping(
+ staff_api_client, shipping_method, checkout_with_item_and_shipping_method, address
+):
+ # given
+ checkout = checkout_with_item_and_shipping_method
+ checkout.external_shipping_method_id = "ext-ship"
+ checkout.undiscounted_base_shipping_price_amount = Decimal("110")
+ checkout.shipping_method_name = "Ext shipping"
+ checkout.shipping_address = address
+ checkout.save()
+
+ query = MUTATION_UPDATE_SHIPPING_METHOD
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id}
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ checkout.refresh_from_db()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ fetch_checkout_data(
+ checkout_info,
+ manager,
+ lines,
+ )
+
+ errors = data["errors"]
+ assert not errors
+ assert checkout.shipping_method == shipping_method
+ assert checkout.external_shipping_method_id is None
+ assert (
+ checkout.undiscounted_base_shipping_price_amount
+ == shipping_method.channel_listings.get().price_amount
+ )
+ assert checkout.shipping_method_name == shipping_method.name
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -287,6 +360,9 @@ def test_checkout_shipping_method_update_excluded_webhook(
assert errors[0]["field"] == "shippingMethod"
assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
assert checkout.shipping_method is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.undiscounted_base_shipping_price_amount == Decimal("0")
+ assert checkout.shipping_method_name is None
# Deprecated
@@ -319,6 +395,9 @@ def test_checkout_shipping_method_update_excluded_postal_code(
assert errors[0]["field"] == "shippingMethod"
assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
assert checkout.shipping_method is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.undiscounted_base_shipping_price_amount == Decimal("0")
+ assert checkout.shipping_method_name is None
assert (
mock_is_shipping_method_available.call_count
== shipping_models.ShippingMethod.objects.count()
@@ -350,8 +429,23 @@ def test_checkout_shipping_method_update_with_not_all_required_shipping_address_
checkout.refresh_from_db()
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ fetch_checkout_data(
+ checkout_info,
+ manager,
+ lines,
+ )
+
assert not data["errors"]
assert checkout.shipping_method == shipping_method
+ assert checkout.external_shipping_method_id is None
+ assert (
+ checkout.undiscounted_base_shipping_price_amount
+ == shipping_method.channel_listings.get().price_amount
+ )
+ assert checkout.shipping_method_name == shipping_method.name
def test_checkout_shipping_method_update_with_not_valid_shipping_address_data(
@@ -385,8 +479,23 @@ def test_checkout_shipping_method_update_with_not_valid_shipping_address_data(
checkout.refresh_from_db()
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ fetch_checkout_data(
+ checkout_info,
+ manager,
+ lines,
+ )
+
assert not data["errors"]
assert checkout.shipping_method == shipping_method
+ assert checkout.external_shipping_method_id is None
+ assert (
+ checkout.undiscounted_base_shipping_price_amount
+ == shipping_method.channel_listings.get().price_amount
+ )
+ assert checkout.shipping_method_name == shipping_method.name
def test_checkout_delivery_method_update_unavailable_variant(
@@ -442,11 +551,23 @@ def test_checkout_shipping_method_update_shipping_zone_without_channel(
checkout.refresh_from_db()
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ fetch_checkout_data(
+ checkout_info,
+ manager,
+ lines,
+ )
+
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
+ assert checkout.external_shipping_method_id is None
+ assert checkout.undiscounted_base_shipping_price_amount == Decimal("0")
+ assert checkout.shipping_method_name is None
# Deprecated
@@ -471,12 +592,26 @@ def test_checkout_shipping_method_update_shipping_zone_with_channel(
checkout.refresh_from_db()
- checkout.refresh_from_db()
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ fetch_checkout_data(
+ checkout_info,
+ manager,
+ lines,
+ )
+
errors = data["errors"]
assert not errors
assert data["checkout"]["token"] == str(checkout_with_item.token)
assert checkout.shipping_method == shipping_method
+ assert checkout.external_shipping_method_id is None
+ assert (
+ checkout.undiscounted_base_shipping_price_amount
+ == shipping_method.channel_listings.get().price_amount
+ )
+ assert checkout.shipping_method_name == shipping_method.name
def test_checkout_update_shipping_method_with_digital(
@@ -507,6 +642,9 @@ def test_checkout_update_shipping_method_with_digital(
# Ensure the shipping method was unchanged
checkout.refresh_from_db(fields=["shipping_method"])
assert checkout.shipping_method is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.undiscounted_base_shipping_price_amount == Decimal("0")
+ assert checkout.shipping_method_name is None
def test_with_active_problems_flow(
@@ -536,7 +674,7 @@ def test_with_active_problems_flow(
@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update.call_checkout_info_event",
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -613,7 +751,7 @@ def test_checkout_shipping_method_update_triggers_webhooks(
@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update.call_checkout_info_event",
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -683,7 +821,7 @@ def test_checkout_shipping_method_update_external_shipping_triggers_webhooks(
assert mocked_send_webhook_request_async.call_count == 1
# confirm each sync webhook was called without saving event delivery
- assert mocked_send_webhook_request_sync.call_count == 5
+ assert mocked_send_webhook_request_sync.call_count == 3
assert not EventDelivery.objects.exclude(
webhook_id=checkout_updated_webhook.id
).exists()
@@ -711,7 +849,7 @@ def test_checkout_shipping_method_update_external_shipping_triggers_webhooks(
@patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update.call_checkout_info_event",
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
wraps=call_checkout_info_event,
)
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -740,7 +878,8 @@ def test_checkout_shipping_method_update_to_none_triggers_webhooks(
) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_UPDATED)
checkout_with_items.shipping_address = address
- checkout_with_items.save(update_fields=["shipping_address"])
+ checkout_with_items.shipping_method = shipping_method
+ checkout_with_items.save(update_fields=["shipping_address", "shipping_method"])
# when
response = api_client.post_graphql(
@@ -796,3 +935,420 @@ def test_checkout_shipping_method_update_to_none_triggers_webhooks(
tax_delivery = tax_delivery_call.args[0]
assert tax_delivery.webhook_id == tax_webhook.id
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_method_update_from_external_shipping_to_different_external(
+ mocked_invalidate_checkout,
+ mocked_send_webhook_request_sync,
+ mocked_call_checkout_info_event,
+ settings,
+ shipping_app,
+ checkout_with_delivery_method_for_external_shipping,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_external_shipping
+
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "new-abcd"
+ response_shipping_name = "New Provider - Economy"
+ response_shipping_price = "10"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": response_shipping_name,
+ "amount": response_shipping_price,
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+ mocked_send_webhook_request_sync.return_value = mock_json_response
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+ assert data["checkout"]["deliveryMethod"]["name"] == response_shipping_name
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id == method_id
+ assert checkout.shipping_method_name == response_shipping_name
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_method_update_from_external_shipping_to_the_same_external(
+ mocked_invalidate_checkout,
+ mocked_send_webhook_request_sync,
+ mocked_call_checkout_info_event,
+ address,
+ settings,
+ shipping_app,
+ checkout_with_item,
+ api_client,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "new-abcd"
+ response_shipping_name = "New Provider - Economy"
+ response_shipping_price = "10"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": response_shipping_name,
+ "amount": response_shipping_price,
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+
+ mocked_send_webhook_request_sync.return_value = mock_json_response
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.external_shipping_method_id = method_id
+ checkout.shipping_method_name = response_shipping_name
+ checkout.save()
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+ assert data["checkout"]["deliveryMethod"]["name"] == response_shipping_name
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id == method_id
+ assert checkout.shipping_method_name == response_shipping_name
+
+ mocked_invalidate_checkout.assert_not_called()
+ mocked_call_checkout_info_event.assert_not_called()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_method_update_from_external_shipping_to_built_in_method(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_delivery_method_for_external_shipping,
+ shipping_method,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_external_shipping
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "shippingMethodId": to_global_id_or_none(shipping_method),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == shipping_method.name
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id == shipping_method.id
+ assert checkout.shipping_method_name == shipping_method.name
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_method_update_from_external_shipping_to_none(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_delivery_method_for_external_shipping,
+ api_client,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_external_shipping
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {"id": to_global_id_or_none(checkout), "shippingMethodId": None},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"] is None
+
+ checkout.refresh_from_db()
+
+ assert checkout.collection_point_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_method_update_from_built_in_shipping_to_different_built_in(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_shipping_method,
+ other_shipping_method,
+ api_client,
+):
+ # given
+ checkout = checkout_with_shipping_method
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "shippingMethodId": to_global_id_or_none(other_shipping_method),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ other_shipping_method
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == other_shipping_method.name
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id == other_shipping_method.id
+ assert checkout.shipping_method_name == other_shipping_method.name
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_method_update_from_built_in_shipping_to_external(
+ mocked_invalidate_checkout,
+ mocked_send_webhook_request_sync,
+ mocked_call_checkout_info_event,
+ settings,
+ checkout_with_shipping_method,
+ shipping_app,
+ api_client,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ response_method_id = "new-abcd"
+ response_shipping_name = "New Provider - Economy"
+ response_shipping_price = "10"
+ mock_json_response = [
+ {
+ "id": response_method_id,
+ "name": response_shipping_name,
+ "amount": response_shipping_price,
+ "currency": "USD",
+ "maximum_delivery_days": "7",
+ }
+ ]
+
+ mocked_send_webhook_request_sync.return_value = mock_json_response
+
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{response_method_id}"
+ )
+
+ checkout = checkout_with_shipping_method
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == method_id
+ assert data["checkout"]["deliveryMethod"]["name"] == response_shipping_name
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id == method_id
+ assert checkout.shipping_method_name == response_shipping_name
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_method_update_from_built_in_shipping_to_the_same_built_in(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_shipping_method,
+ api_client,
+):
+ # given
+ checkout = checkout_with_shipping_method
+
+ shipping_method = checkout.shipping_method
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {
+ "id": to_global_id_or_none(checkout),
+ "shippingMethodId": to_global_id_or_none(shipping_method),
+ },
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"]["id"] == to_global_id_or_none(
+ shipping_method
+ )
+ assert data["checkout"]["deliveryMethod"]["name"] == shipping_method.name
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_id == shipping_method.id
+ assert checkout.shipping_method_name == shipping_method.name
+
+ mocked_invalidate_checkout.assert_not_called()
+ mocked_call_checkout_info_event.assert_not_called()
+
+
+ "saleor.graphql.checkout.mutations.utils.call_checkout_info_event",
+ wraps=call_checkout_info_event,
+)
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_method_update_from_built_in_shipping_to_none(
+ mocked_invalidate_checkout,
+ mocked_call_checkout_info_event,
+ checkout_with_shipping_method,
+ api_client,
+):
+ # given
+ checkout = checkout_with_shipping_method
+
+ # when
+ response = api_client.post_graphql(
+ MUTATION_UPDATE_SHIPPING_METHOD,
+ {"id": to_global_id_or_none(checkout), "shippingMethodId": None},
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]
+ errors = data["errors"]
+ assert not errors
+ assert data["checkout"]["deliveryMethod"] is None
+
+ checkout.refresh_from_db()
+ assert checkout.collection_point_id is None
+ assert checkout.shipping_method_id is None
+ assert checkout.external_shipping_method_id is None
+ assert checkout.shipping_method_name is None
+
+ mocked_invalidate_checkout.assert_called_once()
+ mocked_call_checkout_info_event.assert_called_once()
diff --git a/saleor/graphql/checkout/tests/mutations/test_utils.py b/saleor/graphql/checkout/tests/mutations/test_utils.py
index 3ca44f1354..4a44981a01 100644
--- a/saleor/graphql/checkout/tests/mutations/test_utils.py
+++ b/saleor/graphql/checkout/tests/mutations/test_utils.py
@@ -1,10 +1,12 @@
import graphene
+from prices import Money
-from .....checkout.fetch import (
- fetch_checkout_lines,
-)
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....plugins.manager import get_plugins_manager
+from .....shipping.interface import ShippingMethodData
from ...mutations.utils import (
CheckoutLineData,
+ assign_delivery_method_to_checkout,
group_lines_input_data_on_update,
group_lines_input_on_add,
)
@@ -181,3 +183,88 @@ def test_group_on_update_when_one_line_and_mixed_parameters_provided(
assert expected == group_lines_input_data_on_update(
lines_data, existing_checkout_lines
)
+
+
+def test_assign_delivery_method_to_checkout_delivery_method_to_none(
+ checkout_with_delivery_method_for_cc,
+):
+ # given
+ checkout = checkout_with_delivery_method_for_cc
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ assign_delivery_method_to_checkout(checkout_info, lines_info, manager, None)
+
+ # then
+ assert checkout_with_delivery_method_for_cc.collection_point_id is None
+ assert checkout_with_delivery_method_for_cc.shipping_address_id is None
+ assert checkout_info.shipping_method is None
+ assert checkout_info.collection_point is None
+
+
+def test_assign_delivery_method_to_checkout_delivery_method_to_external(
+ checkout_with_shipping_method, shipping_app
+):
+ # given
+ checkout = checkout_with_shipping_method
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ app_shipping_id = "abcd"
+ app_shipping_name = "Shipping"
+ method_id = graphene.Node.to_global_id(
+ "app", f"{shipping_app.id}:{app_shipping_id}"
+ )
+ external_shipping_data = ShippingMethodData(
+ name=app_shipping_name, id=method_id, price=Money(0, checkout.currency)
+ )
+
+ # when
+ assign_delivery_method_to_checkout(
+ checkout_info, lines_info, manager, external_shipping_data
+ )
+
+ # then
+ assert checkout.external_shipping_method_id == method_id
+ assert checkout.shipping_method_name == app_shipping_name
+ assert checkout.shipping_method_id is None
+ assert checkout_info.shipping_method is None
+ assert checkout_info.collection_point is None
+
+
+def test_assign_delivery_method_to_checkout_delivery_method_to_cc(
+ checkout, shipping_method_weight_based, warehouses_for_cc
+):
+ # given
+ checkout.shipping_method = shipping_method_weight_based
+ checkout.shipping_method_name = shipping_method_weight_based.name
+
+ lines_info, _ = fetch_checkout_lines(checkout)
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ collection_point = warehouses_for_cc[0]
+
+ # when
+ assign_delivery_method_to_checkout(
+ checkout_info, lines_info, manager, collection_point
+ )
+
+ # then
+ assert checkout.collection_point == collection_point
+ assert checkout.shipping_address == collection_point.address
+ assert int(checkout.shipping_address_id) != int(collection_point.address.id)
+ assert checkout.shipping_method_id is None
+ assert checkout.shipping_method_name is None
+ assert checkout_info.shipping_method is None
diff --git a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
index 501f57300f..43335c4ea2 100644
--- a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
+++ b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
@@ -275,8 +275,7 @@ mutation updateCheckoutShippingOptions($token: UUID!, $shippingMethodId: ID) {
@mock.patch(
- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
- "invalidate_checkout",
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_shipping_method_update_invalidate_prices(
@@ -319,8 +318,7 @@ mutation updateCheckoutDeliveryOptions($token: UUID!, $deliveryMethodId: ID!) {
@mock.patch(
- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
- "invalidate_checkout",
+ "saleor.graphql.checkout.mutations.utils.invalidate_checkout",
wraps=invalidate_checkout,
)
def test_checkout_delivery_method_update_invalidate_prices(