Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Apply `InstanceTracker` to `DraftOrderUpdate` mutation (#17656)
Piotr Zabieglikc6e61956d6a9
diff --git a/saleor/core/utils/tests/test_update_mutation_manager.py b/saleor/core/utils/tests/test_update_mutation_manager.pynew file mode 100644index 0000000000..fbd3eb6136--- /dev/null+++ b/saleor/core/utils/tests/test_update_mutation_manager.py@@ -0,0 +1,102 @@+from ....order import OrderStatus+from ..update_mutation_manager import InstanceTracker+++def test_instance_tracker(product):+ # given+ fields_to_track = ["name", "slug"]+ tracker = InstanceTracker(product, fields_to_track)++ # when+ product.name = product.name + "_updated"+ modified_field = tracker.get_modified_fields()++ # then+ assert modified_field == ["name"]+++def test_instance_tracker_no_instance_on_init(product):+ # given+ fields_to_track = ["name", "slug"]+ tracker = InstanceTracker(None, fields_to_track)++ # when+ tracker.instance = product+ modified_fields = tracker.get_modified_fields()++ # then+ assert modified_fields == fields_to_track+++def test_instance_tracker_no_instance_on_init_and_on_get_modified_fields():+ # given+ fields_to_track = ["name", "slug"]+ tracker = InstanceTracker(None, fields_to_track)++ # when+ modified_fields = tracker.get_modified_fields()++ # then+ assert modified_fields == []+++def test_instance_tracker_remove_instance(product):+ # given+ fields_to_track = ["name", "slug"]+ tracker = InstanceTracker(product, fields_to_track)++ # when+ tracker.instance = None+ modified_fields = tracker.get_modified_fields()++ # then+ assert modified_fields == fields_to_track+++def test_instance_tracker_foreign_relation(order_with_lines):+ # given+ order = order_with_lines+ fields_to_track = ["status", "shipping_address", "billing_address"]+ foreign_fields_to_track = ["last_name", "first_name"]+ tracker = InstanceTracker(+ order,+ fields_to_track,+ foreign_fields_to_track={"shipping_address": foreign_fields_to_track},+ )++ order.status = OrderStatus.FULFILLED+ shipping_address = order.shipping_address+ shipping_address.last_name = "new_last_name"++ # when+ modified_fields = tracker.get_modified_fields()+ foreign_modified_fields = tracker.get_foreign_modified_fields()++ # then+ assert modified_fields == ["status", "shipping_address"]+ assert foreign_modified_fields["shipping_address"] == ["last_name"]+++def test_instance_tracker_foreign_relation_new_instance(order_with_lines):+ # given+ order = order_with_lines+ order.shipping_address = None++ fields_to_track = ["status", "shipping_address", "billing_address"]+ foreign_fields_to_track = ["last_name", "first_name"]+ tracker = InstanceTracker(+ order,+ fields_to_track,+ foreign_fields_to_track={"shipping_address": foreign_fields_to_track},+ )++ order.status = OrderStatus.FULFILLED+ order.shipping_address = order.billing_address++ # when+ modified_fields = tracker.get_modified_fields()+ foreign_modified_fields = tracker.get_foreign_modified_fields()++ # then+ assert modified_fields == ["status", "shipping_address"]+ assert foreign_modified_fields["shipping_address"] == foreign_fields_to_trackdiff --git a/saleor/core/utils/update_mutation_manager.py b/saleor/core/utils/update_mutation_manager.pynew file mode 100644index 0000000000..ce5e639b8f--- /dev/null+++ b/saleor/core/utils/update_mutation_manager.py@@ -0,0 +1,70 @@+from copy import deepcopy+from typing import Any, TypeVar++from django.db.models import Model++T = TypeVar("T", bound=Model)+++class InstanceTracker:+ """Instance with modifications tracker.++ It is used to determine modified fields of the instance.+ """++ def __init__(+ self,+ instance: T | None,+ fields_to_track: list[str],+ foreign_fields_to_track: dict[str, list[str]] | None = None,+ ):+ self.instance = instance+ self.fields_to_track = fields_to_track+ self.initial_instance_values: dict[str, Any] = (+ deepcopy(self.get_field_values()) if instance else {}+ )+ self.foreign_instance_relation: dict[str, InstanceTracker] = {}+ self.create = instance is None++ if foreign_fields_to_track:+ for lookup, fields in foreign_fields_to_track.items():+ foreign_instance = getattr(instance, lookup, None)+ self.foreign_instance_relation[lookup] = InstanceTracker(+ foreign_instance,+ fields,+ None,+ )++ def get_field_values(self) -> dict[str, Any]:+ """Create a dict of tracked fields with related instance values."""+ if not self.instance:+ return {}++ return {field: getattr(self.instance, field) for field in self.fields_to_track}++ def get_modified_fields(self) -> list[str]:+ """Compare updated instance values with initial ones.++ Raise exception when instance is None.+ """+ if not self.initial_instance_values:+ if self.instance:+ return self.fields_to_track+ return []++ modified_instance_values: dict[str, Any] = self.get_field_values()+ return [+ field+ for field in self.initial_instance_values+ if self.initial_instance_values.get(field)+ != modified_instance_values.get(field)+ ]++ def get_foreign_modified_fields(self) -> dict[str, list[str]]:+ modified_fields = {}+ for lookup, tracker in self.foreign_instance_relation.items():+ tracker.instance = getattr(self.instance, lookup, None)+ foreign_modified = tracker.get_modified_fields()+ if foreign_modified:+ modified_fields[lookup] = foreign_modified+ return modified_fieldsdiff --git a/saleor/graphql/account/mutations/account/utils.py b/saleor/graphql/account/mutations/account/utils.pynew file mode 100644index 0000000000..b067162609--- /dev/null+++ b/saleor/graphql/account/mutations/account/utils.py@@ -0,0 +1,16 @@+ADDRESS_UPDATE_FIELDS = {+ "city",+ "city_area",+ "company_name",+ "country",+ "country_area",+ "first_name",+ "last_name",+ "metadata",+ "phone",+ "postal_code",+ "private_metadata",+ "street_address_1",+ "street_address_2",+ "validation_skipped",+}diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.pyindex b79f6272e6..b2fef42b3e 100644--- a/saleor/graphql/order/mutations/draft_order_update.py+++ b/saleor/graphql/order/mutations/draft_order_update.py@@ -1,9 +1,12 @@+from typing import cast+import graphenefrom django.core.exceptions import ValidationErrorfrom ....account.models import Userfrom ....checkout import AddressTypefrom ....core.tracing import traced_atomic_transaction+from ....core.utils.update_mutation_manager import InstanceTrackerfrom ....discount.models import VoucherCodefrom ....discount.utils.voucher import (create_or_update_voucher_discount_objects_for_order,@@ -14,14 +17,12 @@ from ....order import OrderStatus, modelsfrom ....order.actions import call_order_eventfrom ....order.error_codes import OrderErrorCodefrom ....order.search import update_order_search_vector-from ....order.utils import (- invalidate_order_prices,- update_order_display_gross_prices,-)+from ....order.utils import invalidate_order_pricesfrom ....permission.enums import OrderPermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...account.i18n import I18nMixinfrom ...account.mixins import AddressMetadataMixin+from ...account.mutations.account.utils import ADDRESS_UPDATE_FIELDSfrom ...core import ResolveInfofrom ...core.context import SyncWebhookControlContextfrom ...core.mutations import (@@ -36,9 +37,9 @@ from ..types import Orderfrom . import draft_order_cleanerfrom .draft_order_create import DraftOrderInputfrom .utils import (+ DRAFT_ORDER_UPDATE_FIELDS,SHIPPING_METHOD_UPDATE_FIELDS,ShippingMethodUpdateMixin,- save_addresses,)@@ -68,6 +69,8 @@ class DraftOrderUpdate(support_meta_field = Truesupport_private_meta_field = True+ FIELDS_TO_TRACK = list(DRAFT_ORDER_UPDATE_FIELDS | SHIPPING_METHOD_UPDATE_FIELDS)+@classmethoddef get_instance(cls, info: ResolveInfo, **data):instance = super().get_instance(@@ -94,6 +97,7 @@ class DraftOrderUpdate("billing_address","shipping_method","voucher",+ "voucher_code",])@@ -153,6 +157,30 @@ class DraftOrderUpdate()shipping_method_input["shipping_method"] = shipping_method+ # Do not process shipping method if it is already associated with the order+ # and shipping price is properly set. Shipping price can be not set together+ # with shipping method when it is added to the order without lines or with+ # lines that do not require shipping.+ if shipping_method is not None:+ method_channel_listing = shipping_method.channel_listings.filter(+ channel=instance.channel+ ).first()+ shipping_price = (+ method_channel_listing.price if method_channel_listing else 0+ )+ shipping_price_update_required = (+ shipping_method.id == instance.shipping_method_id+ and instance.undiscounted_base_shipping_price != shipping_price+ )+ shipping_method_update_required = (+ shipping_method.id != instance.shipping_method_id+ )+ shipping_update_required = (+ shipping_method_update_required or shipping_price_update_required+ )+ if not shipping_update_required:+ shipping_method_input = {}+return shipping_method_input@classmethod@@ -174,6 +202,7 @@ class DraftOrderUpdate(info=info,)cleaned_input["shipping_address"] = shipping_address+ instance.shipping_address = shipping_addresscleaned_input["draft_save_shipping_address"] = (save_shipping_address or False)@@ -195,6 +224,7 @@ class DraftOrderUpdate(info=info,)cleaned_input["billing_address"] = billing_address+ instance.billing_address = billing_addresscleaned_input["draft_save_billing_address"] = save_billing_address or Falseelif save_billing_address is not None:raise ValidationError(@@ -210,40 +240,38 @@ class DraftOrderUpdate(@classmethoddef _save(cls,- info: ResolveInfo,- instance,- cleaned_input,- changed_fields,- ):- updated_fields = changed_fields+ instance_tracker: InstanceTracker,+ cleaned_input: dict,+ ) -> bool:+ instance = cast(models.Order, instance_tracker.instance)with traced_atomic_transaction():- # Process addresses- address_fields = save_addresses(instance, cleaned_input)- updated_fields.extend(address_fields)+ modified_foreign_fields = instance_tracker.get_foreign_modified_fields()+ if "shipping_address" in modified_foreign_fields:+ cls._save_address(+ instance.shipping_address,+ modified_foreign_fields["shipping_address"],+ )- if "shipping_method" in cleaned_input:- updated_fields.extend(SHIPPING_METHOD_UPDATE_FIELDS)+ if "billing_address" in modified_foreign_fields:+ cls._save_address(+ instance.billing_address,+ modified_foreign_fields["billing_address"],+ )- # In case nothing change, do not update perform post-process actions;- # do not call the `DRAFT_ORDER_UPDATED` event.- if not updated_fields:+ modified_instance_fields = instance_tracker.get_modified_fields()+ modified_instance_fields.extend(modified_foreign_fields)+ if not modified_instance_fields:return False- if (- "shipping_address" in updated_fields- or "billing_address" in updated_fields- ):- update_order_display_gross_prices(instance)- updated_fields.append("display_gross_prices")-+ # Post-process the resultsupdate_order_search_vector(instance, save=False)- updated_fields.append("search_vector")-- if cls.should_invalidate_prices(cleaned_input):+ modified_instance_fields.extend(["search_vector"])+ if cls.should_invalidate_prices(modified_instance_fields):invalidate_order_prices(instance)- updated_fields.append("should_refresh_prices")+ modified_instance_fields.extend(["should_refresh_prices"])- cls._save_order_instance(instance, updated_fields)+ # Save instance+ cls._save_order_instance(instance, modified_instance_fields)return True@@ -252,6 +280,13 @@ class DraftOrderUpdate(update_fields = ["updated_at"] + modified_instance_fieldsinstance.save(update_fields=update_fields)+ @classmethod+ def _save_address(cls, address_instance, modified_fields):+ if address_instance._state.adding:+ address_instance.save()+ else:+ address_instance.save(update_fields=modified_fields)+@classmethoddef _post_save_action(cls, instance, manager):call_order_event(@@ -333,11 +368,19 @@ class DraftOrderUpdate(@classmethoddef perform_mutation(cls, _root, info: ResolveInfo, /, **data):instance = cls.get_instance(info, **data)- channel_id = cls.get_instance_channel_id(instance, **data)-+ channel_id = instance.channel_idcls.check_channel_permissions(info, [channel_id])- old_instance_data = instance.serialize_for_comparison()+ instance = cast(models.Order, instance)+ instance_tracker = InstanceTracker(+ instance,+ cls.FIELDS_TO_TRACK,+ foreign_fields_to_track={+ "shipping_address": list(ADDRESS_UPDATE_FIELDS),+ "billing_address": list(ADDRESS_UPDATE_FIELDS),+ },+ )+old_voucher = instance.voucherold_voucher_code = instance.voucher_codedata = data["input"]@@ -345,6 +388,7 @@ class DraftOrderUpdate(cls.handle_metadata(instance, cleaned_input)+ # update instance with data from inputinstance = cls.construct_instance(instance, cleaned_input)cls.clean_instance(info, instance)@@ -353,21 +397,8 @@ class DraftOrderUpdate(cls.handle_shipping(cleaned_input, instance, manager)cls.handle_order_voucher(cleaned_input, instance, old_voucher, old_voucher_code)- new_instance_data = instance.serialize_for_comparison()- changed_fields = cls.diff_instance_data_fields(- instance.comparison_fields,- old_instance_data,- new_instance_data,- )-- order_modified = cls._save(info, instance, cleaned_input, changed_fields)+ order_modified = cls._save(instance_tracker, cleaned_input)if order_modified:cls._post_save_action(instance, manager)return DraftOrderUpdate(order=SyncWebhookControlContext(node=instance))-- @classmethod- def get_instance_channel_id(cls, instance, **data):- if channel_id := instance.channel_id:- return channel_id- return Nonediff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.pyindex 02aeb3afea..c83962e05b 100644--- a/saleor/graphql/order/mutations/utils.py+++ b/saleor/graphql/order/mutations/utils.py@@ -23,7 +23,31 @@ from ....shipping.utils import convert_to_shipping_method_datafrom ....webhook.event_types import WebhookEventAsyncTypefrom ..utils import get_shipping_method_availability_error-SHIPPING_METHOD_UPDATE_FIELDS = [+DRAFT_ORDER_UPDATE_FIELDS = {+ "base_shipping_price_amount",+ "billing_address",+ "channel",+ "collection_point",+ "collection_point_name",+ "customer_note",+ "display_gross_prices",+ "draft_save_billing_address",+ "draft_save_shipping_address",+ "external_reference",+ "language_code",+ "metadata",+ "private_metadata",+ "redirect_url",+ "search_vector",+ "shipping_address",+ "user",+ "user_email",+ "voucher",+ "voucher_code",+ "weight",+}++SHIPPING_METHOD_UPDATE_FIELDS = {"currency","shipping_method","shipping_price_net_amount",@@ -38,7 +62,7 @@ SHIPPING_METHOD_UPDATE_FIELDS = ["shipping_tax_rate","should_refresh_prices","updated_at",-]+}class EditableOrderValidationMixin:diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.pyindex 214701b268..91cf89ef34 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py@@ -21,8 +21,11 @@ from .....order.error_codes import OrderErrorCodefrom .....order.models import OrderEventfrom .....order.utils import update_discount_for_order_linefrom .....payment.model_helpers import get_subtotal+from .....shipping.models import ShippingMethodfrom .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from ....core.utils import snake_to_camel_casefrom ....tests.utils import assert_no_permission, get_graphql_content+from ...mutations.draft_order_create import DraftOrderInputDRAFT_ORDER_UPDATE_MUTATION = """mutation draftUpdate(@@ -3259,3 +3262,359 @@ def test_draft_order_update_with_language_code(order.refresh_from_db()assert order.language_code == "pl"+++@patch(+ "saleor.graphql.order.mutations.draft_order_update.call_order_event",+ wraps=call_order_event,+)+@patch(+ "saleor.graphql.order.mutations.draft_order_update.DraftOrderUpdate._save_order_instance"+)+def test_draft_order_update_no_changes(+ save_order_mock,+ call_event_mock,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ voucher,+ address,+):+ # given+ order = order_with_lines+ order.status = OrderStatus.DRAFT+ order_id = graphene.Node.to_global_id("Order", order.id)++ key = "some_key"+ value = "some_value"+ address.metadata = {key: value}+ address.save(update_fields=["metadata"])++ order.metadata = {key: value}+ order.private_metadata = {key: value}+ order.shipping_address = address+ order.billing_address = address+ order.draft_save_billing_address = True+ order.draft_save_shipping_address = True+ order.voucher = voucher+ order.voucher_code = voucher.codes.first().code+ order.customer_note = "some note"+ order.redirect_url = "https://www.example.com"+ order.external_reference = "some_reference_string"+ order.language_code = "pl"+ order.save()++ shipping_method_id = graphene.Node.to_global_id(+ "ShippingMethod", order.shipping_method_id+ )+ user_id = graphene.Node.to_global_id("User", order.user_id)++ address_input = {+ snake_to_camel_case(key): value for key, value in address.as_data().items()+ }+ address_input["metadata"] = [{"key": key, "value": value}]+ address_input.pop("privateMetadata")+ skip_validation = address_input.pop("validationSkipped")+ address_input["skipValidation"] = skip_validation++ input_fields = [+ snake_to_camel_case(key) for key in DraftOrderInput._meta.fields.keys()+ ]++ # `discount` field is unused and deprecated+ input_fields.remove("discount")+ # `voucher` and `voucherCode` fields can't be combined+ input_fields.remove("voucher")+ # `channel` can't be updated when is not None+ input_fields.remove("channelId")++ input = {+ "billingAddress": address_input,+ "saveBillingAddress": True,+ "shippingAddress": address_input,+ "saveShippingAddress": True,+ "shippingMethod": shipping_method_id,+ "user": user_id,+ "userEmail": order.user_email,+ "voucherCode": order.voucher_code,+ "customerNote": order.customer_note,+ "redirectUrl": order.redirect_url,+ "externalReference": order.external_reference,+ "metadata": [{"key": key, "value": value}],+ "privateMetadata": [{"key": key, "value": value}],+ "languageCode": "PL",+ }+ assert set(input_fields) == set(input.keys())++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {"id": order_id, "input": input}++ # when+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_UPDATE_MUTATION,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["draftOrderUpdate"]["errors"]+ order.refresh_from_db()+ save_order_mock.assert_not_called()+ call_event_mock.assert_not_called()+++@patch(+ "saleor.graphql.order.mutations.draft_order_update.call_order_event",+ wraps=call_order_event,+)+@patch(+ "saleor.graphql.order.mutations.draft_order_update.DraftOrderUpdate._save_order_instance"+)+def test_draft_order_update_emit_events(+ save_order_mock,+ call_event_mock,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ graphql_address_data,+ voucher,+):+ # given+ order = order_with_lines+ order.status = OrderStatus.DRAFT+ order_id = graphene.Node.to_global_id("Order", order.id)++ key = "some_key"+ value = "some_value"+ order.metadata = {key: value}+ order.private_metadata = {key: value}+ order.draft_save_billing_address = True+ order.draft_save_shipping_address = True+ order.voucher = voucher+ order.voucher_code = voucher.codes.first().code+ order.customer_note = "some note"+ order.redirect_url = "http://localhost:8000/redirect"+ order.external_reference = "some_reference_string"+ order.language_code = "de"+ order.save()++ new_shipping_method = ShippingMethod.objects.create(+ shipping_zone=order.shipping_method.shipping_zone,+ name="new_method",+ )+ new_shipping_method.channel_listings.create(+ channel=order.channel, currency=order.currency+ )+ new_shipping_method_id = graphene.Node.to_global_id(+ "ShippingMethod", new_shipping_method.id+ )++ assert order.user_id != staff_api_client.user.id+ user_id = graphene.Node.to_global_id("User", staff_api_client.user.id)++ input_fields = [+ snake_to_camel_case(key) for key in DraftOrderInput._meta.fields.keys()+ ]++ # `discount` field is unused and deprecated+ input_fields.remove("discount")+ # `voucher` and `voucherCode` fields can't be combined+ input_fields.remove("voucher")+ # `channel` can't be updated when is not None+ input_fields.remove("channelId")+ # `saveBillingAddress` can't be provided without billingAddress+ input_fields.remove("saveBillingAddress")+ # `saveShippingAddress` can't be provided without shippingAddress+ input_fields.remove("saveShippingAddress")++ assert graphql_address_data["lastName"] != order.shipping_address.last_name+ assert graphql_address_data["lastName"] != order.billing_address.last_name++ input = {+ "billingAddress": graphql_address_data,+ "shippingAddress": graphql_address_data,+ "shippingMethod": new_shipping_method_id,+ "user": user_id,+ "userEmail": "new_" + order.user_email,+ "voucherCode": voucher.codes.last().code,+ "customerNote": order.customer_note + "_new",+ "redirectUrl": "https://www.example.com",+ "externalReference": order.external_reference + "_new",+ "metadata": [{"key": key, "value": "new_value"}],+ "privateMetadata": [{"key": "new_key", "value": value}],+ "languageCode": "PL",+ }+ assert set(input_fields) == set(input.keys())++ # fields making changes to related models (other than order)+ non_base_model_fields = ["billingAddress", "shippingAddress"]+ permission_group_manage_orders.user_set.add(staff_api_client.user)++ for key, value in input.items():+ variables = {"id": order_id, "input": {key: value}}++ # when+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_UPDATE_MUTATION,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["draftOrderUpdate"]["errors"]+ if key not in non_base_model_fields:+ save_order_mock.assert_called()+ save_order_mock.reset_mock()+ call_event_mock.assert_called()+ call_event_mock.reset_mock()+++@patch(+ "saleor.graphql.order.mutations.draft_order_update.call_order_event",+ wraps=call_order_event,+)+def test_draft_order_update_address_not_changed_save_flag_changed(+ call_event_mock,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ address,+):+ """Address input doesn't introduce any changes, but address save flag has changed."""+ # given+ order = order_with_lines+ order.status = OrderStatus.DRAFT+ order_id = graphene.Node.to_global_id("Order", order.id)++ order.shipping_address = address+ order.billing_address = address+ order.draft_save_billing_address = False+ order.draft_save_shipping_address = False+ order.save(+ update_fields=[+ "shipping_address",+ "billing_address",+ "draft_save_billing_address",+ "draft_save_shipping_address",+ "status",+ ]+ )++ address_input = {+ snake_to_camel_case(key): value for key, value in address.as_data().items()+ }+ address_input.pop("privateMetadata")+ skip_validation = address_input.pop("validationSkipped")+ address_input["skipValidation"] = skip_validation++ input = {+ "billingAddress": address_input,+ "saveBillingAddress": True,+ "shippingAddress": address_input,+ "saveShippingAddress": True,+ }++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {"id": order_id, "input": input}++ # when+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_UPDATE_MUTATION,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["draftOrderUpdate"]["errors"]+ order.refresh_from_db()+ assert order.draft_save_billing_address is True+ assert order.draft_save_shipping_address is True+ call_event_mock.assert_called()+++@patch(+ "saleor.graphql.order.mutations.draft_order_update.call_order_event",+ wraps=call_order_event,+)+def test_draft_order_update_address_not_set(+ call_event_mock,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+ graphql_address_data,+):+ # given+ order = order_with_lines+ order.status = OrderStatus.DRAFT+ order.shipping_address = None+ order.billing_address = None+ order.save(update_fields=["shipping_address", "billing_address", "status"])++ order_id = graphene.Node.to_global_id("Order", order.id)++ input = {+ "billingAddress": graphql_address_data,+ "shippingAddress": graphql_address_data,+ }+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {"id": order_id, "input": input}++ # when+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_UPDATE_MUTATION,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["draftOrderUpdate"]["errors"]+ order.refresh_from_db()+ assert order.shipping_address+ assert order.billing_address+ call_event_mock.assert_called()+++@patch(+ "saleor.graphql.order.mutations.draft_order_update.call_order_event",+ wraps=call_order_event,+)+def test_draft_order_update_same_shipping_method_no_shipping_price_set(+ call_event_mock,+ staff_api_client,+ permission_group_manage_orders,+ order_with_lines,+):+ """The shipping price may not be set even when the shipping method has been added.++ It can happen when shipping method is added to the order without lines+ or with lines that do not require shipping.++ In such a case we should process shipping method no matter it hasn't changed.+ """++ # given+ order = order_with_lines+ order.status = OrderStatus.DRAFT+ order.undiscounted_base_shipping_price_amount = 0+ order.save(update_fields=["undiscounted_base_shipping_price_amount", "status"])++ order_id = graphene.Node.to_global_id("Order", order.id)+ shipping_method_id = graphene.Node.to_global_id(+ "ShippingMethod", order.shipping_method_id+ )+ input = {"shippingMethod": shipping_method_id}+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ variables = {"id": order_id, "input": input}++ # when+ response = staff_api_client.post_graphql(+ DRAFT_ORDER_UPDATE_MUTATION,+ variables,+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["draftOrderUpdate"]["errors"]+ order.refresh_from_db()+ assert order.undiscounted_base_shipping_price_amount != 0+ call_event_mock.assert_called()