Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Unified MenuItemMove to other reordering mutations
NyanKiyoshi31d352114802
diff --git a/saleor/graphql/core/utils/reordering.py b/saleor/graphql/core/utils/reordering.pyindex c341625540..c5a4ef0bac 100644--- a/saleor/graphql/core/utils/reordering.py+++ b/saleor/graphql/core/utils/reordering.py@@ -1,4 +1,3 @@-import warningsfrom collections import OrderedDictfrom dataclasses import dataclassfrom typing import Dict, Tuple@@ -90,11 +89,9 @@ class Reordering:# Skip if noting to doif move == 0:- warnings.warn(- f"Ignored node's reordering, did not find: {pk} "- f"(from {self.qs.model.__name__})"- )return+ if move is None:+ move = +1node_pos, target_pos, new_sort_order = self.calculate_new_sort_order(pk, move)diff --git a/saleor/graphql/menu/mutations.py b/saleor/graphql/menu/mutations.pyindex f1bbea193e..e02e09cda4 100644--- a/saleor/graphql/menu/mutations.py+++ b/saleor/graphql/menu/mutations.py@@ -1,10 +1,11 @@-from collections import namedtuple-from typing import List+from collections import defaultdict+from dataclasses import dataclass+from typing import Dict, List, Optionalimport graphenefrom django.core.exceptions import ValidationError-from django.db.models import Model-from graphql_relay import from_global_id+from django.db import transaction+from django.db.models import Model, QuerySetfrom ...menu import modelsfrom ...menu.error_codes import MenuErrorCode@@ -13,6 +14,8 @@ from ...page import models as page_modelsfrom ...product import models as product_modelsfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.types.common import MenuError+from ..core.utils import from_global_id_strict_type+from ..core.utils.reordering import perform_reorderingfrom ..page.types import Pagefrom ..product.types import Category, Collectionfrom .enums import NavigationType@@ -253,9 +256,12 @@ class MenuItemDelete(ModelDeleteMutation):return response-_MenuMoveOperation = namedtuple(- "_MenuMoveOperation", ("menu_item", "parent", "sort_order")-)+@dataclass(frozen=True)+class _MenuMoveOperation:+ menu_item: models.MenuItem+ parent_changed: bool+ new_parent: Optional[models.MenuItem]+ sort_order: intclass MenuItemMove(BaseMutation):@@ -274,13 +280,13 @@ class MenuItemMove(BaseMutation):error_type_field = "menu_errors"@staticmethod- def clean_move(move):+ def clean_move(move: MenuItemMoveInput):"""Validate if the given move could be possibly possible."""if move.parent_id:if move.item_id == move.parent_id:raise ValidationError({- "parent": ValidationError(+ "parent_id": ValidationError("Cannot assign a node to itself.",code=MenuErrorCode.CANNOT_ASSIGN_NODE,)@@ -291,11 +297,11 @@ class MenuItemMove(BaseMutation):def clean_operation(operation: _MenuMoveOperation):"""Validate if the given move will be actually possible."""- if operation.parent:- if operation.menu_item.is_ancestor_of(operation.parent):+ if operation.new_parent is not None:+ if operation.menu_item.is_ancestor_of(operation.new_parent):raise ValidationError({- "parent": ValidationError(+ "parent_id": ValidationError(("Cannot assign a node as child of ""one of its descendants."@@ -306,66 +312,87 @@ class MenuItemMove(BaseMutation):)@classmethod- def get_operation(cls, info, menu_id: int, move) -> _MenuMoveOperation:- parent_node = None-- _type, menu_item_id = from_global_id(move.item_id) # type: str, int- assert _type == "MenuItem", "The menu item node must be of type MenuItem."-- menu_item = models.MenuItem.objects.get(pk=menu_item_id, menu_id=menu_id)+ def get_operation(+ cls, info, menu: models.Menu, move: MenuItemMoveInput+ ) -> _MenuMoveOperation:+ menu_item = cls.get_node_or_error(+ info, move.item_id, field="item", only_type="MenuItem", qs=menu.items+ )+ new_parent, parent_changed = None, Falseif move.parent_id is not None:- parent_node = cls.get_node_or_error(- info, move.parent_id, field="parent_id", only_type=MenuItem+ parent_pk = from_global_id_strict_type(+ move.parent_id, only_type=MenuItem, field="parent_id")+ if int(parent_pk) != menu_item.parent_id:+ new_parent = cls.get_node_or_error(+ info,+ move.parent_id,+ field="parent_id",+ only_type=MenuItem,+ qs=menu.items,+ )+ parent_changed = True+ elif move.parent_id is None and menu_item.parent_id is not None:+ parent_changed = Truereturn _MenuMoveOperation(- menu_item=menu_item, parent=parent_node, sort_order=move.sort_order+ menu_item=menu_item,+ new_parent=new_parent,+ parent_changed=parent_changed,+ sort_order=move.sort_order,)@classmethoddef clean_moves(- cls, info, menu_id: int, move_operations: List+ cls, info, menu: models.Menu, move_operations: List[MenuItemMoveInput]) -> List[_MenuMoveOperation]:operations = []for move in move_operations:cls.clean_move(move)- operation = cls.get_operation(info, menu_id, move)+ operation = cls.get_operation(info, menu, move)cls.clean_operation(operation)operations.append(operation)return operations@staticmethod- def perform_operation(operation: _MenuMoveOperation):+ def perform_change_parent_operation(operation: _MenuMoveOperation):menu_item = operation.menu_item # type: models.MenuItem- # Move the parent if provided- if operation.parent:- menu_item.move_to(operation.parent)- # Remove the menu item's parent if was set to none (root node)- elif menu_item.parent_id:- menu_item.parent_id = None-- # Move the menu item- if operation.sort_order is not None:- menu_item.sort_order = operation.sort_order+ if not operation.parent_changed:+ return+ # Move the parent+ menu_item.move_to(operation.new_parent)+ menu_item.sort_order = Nonemenu_item.save()@classmethod- def perform_mutation(cls, _root, info, menu, moves):- _type, menu_id = from_global_id(menu) # type: str, int- assert _type == "Menu", "Expected a menu of type Menu"+ @transaction.atomic+ def perform_mutation(cls, _root, info, menu: str, moves):+ qs = models.Menu.objects.prefetch_related("items")+ menu = cls.get_node_or_error(info, menu, only_type=Menu, field="menu", qs=qs)- operations = cls.clean_moves(info, menu_id, moves)+ operations = cls.clean_moves(info, menu, moves)+ sort_operations: Dict[Optional[int], Dict[int, int]] = defaultdict(dict)+ sort_querysets: Dict[Optional[int], QuerySet] = {}for operation in operations:- cls.perform_operation(operation)+ cls.perform_change_parent_operation(operation)++ menu_item = operation.menu_item+ parent_pk = operation.menu_item.parent_id++ sort_operations[parent_pk][menu_item.pk] = operation.sort_order+ sort_querysets[parent_pk] = menu_item.get_ordering_queryset()++ for parent_pk, operations in sort_operations.items():+ ordering_qs = sort_querysets[parent_pk]+ perform_reordering(ordering_qs, operations)- menu = models.Menu.objects.get(pk=menu_id)- update_menu(menu)- return cls(menu=menu)+ menu = qs.get(pk=menu.pk)+ return MenuItemMove(menu=menu)class AssignNavigation(BaseMutation):diff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex 564fa33c0b..875ba55a4a 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -202,8 +202,14 @@ class GraphQLView(View):if settings.DEBUG:lines = []- for line in traceback.format_exception(type(exc), exc, exc.__traceback__):- lines.extend(line.rstrip().splitlines())++ # FIXME: test :80+ if isinstance(exc, BaseException):+ for line in traceback.format_exception(+ type(exc), exc, exc.__traceback__+ ):+ lines.extend(line.rstrip().splitlines())+result["extensions"] = {"exception": {"code": type(exc).__name__, "stacktrace ": lines}}diff --git a/tests/api/test_menu.py b/tests/api/test_menu.pyindex 8d6ce9f4ca..58be6fe67e 100644--- a/tests/api/test_menu.py+++ b/tests/api/test_menu.py@@ -1,11 +1,8 @@import json-from random import shuffle-from typing import Dict, Listimport grapheneimport pytestfrom django.core.exceptions import ValidationError-from graphql_relay import from_global_idfrom saleor.graphql.menu.mutations import NavigationType, _validate_menu_item_instancefrom saleor.menu.models import Menu, MenuItem@@ -500,6 +497,9 @@ mutation menuItemMove($menu: ID!, $moves: [MenuItemMoveInput]!) {parent {id}+ children {+ id+ }}}}@@ -508,151 +508,196 @@ mutation menuItemMove($menu: ID!, $moves: [MenuItemMoveInput]!) {"""-def _assert_menu_is_exactly(menu_id: str, actual_data: dict, expected_data: List[Dict]):-- menu = actual_data.get("menu")- assert menu, "Expected to receive a valid menu to compare from"-- # Check the returned menu is actually the one we requested to change- assert menu["id"] == menu_id-- actual_menu_items = menu.get("items")- assert actual_menu_items, "Expected the menu to have items"-- for expected_item in expected_data:- the_item_was_found = False- expected_sort_order = expected_item.get("sortOrder")- expected_parent_id = expected_item.get("parentId")- expected_item_id = from_global_id(expected_item["itemId"])[1]-- for actual_item in actual_menu_items:- # Get the item that we want to compare, we retrieve by the database- # entry ID as the node id may have changed between the initial- # request and the one returned by the mutation- actual_item_id = from_global_id(actual_item["id"])[1]- if actual_item_id != expected_item_id:- # Append the children, to check, if any- children = actual_item.get("children")- if children:- actual_menu_items += children-- # Skip this node as it is not the one we are looking for- continue-- the_item_was_found = True-- if expected_sort_order:- assert (- actual_item["sortOrder"] == expected_sort_order- ), "The menu item did not have the expected sorting order"-- if "parentId" in expected_item:- if expected_parent_id:- assert actual_item[- "parent"- ], "Expected the menu item to have a parent"- assert (- actual_item["parent"]["id"] == expected_parent_id- ), "The menu item did not have the expected parent"- else:- assert not actual_item[- "parent"- ], "Expected the menu item to not have a parent"-- assert (- the_item_was_found- ), "The expected menu item was not found in the response"--def test_menu_reorder(staff_api_client, permission_manage_menus, menu_item_list):menu_item_list = list(menu_item_list)- menu_id = graphene.Node.to_global_id("Menu", menu_item_list[0].menu_id)+ menu_global_id = graphene.Node.to_global_id("Menu", menu_item_list[0].menu_id)- # Randomize the menu ordering- shuffle(menu_item_list)+ assert len(menu_item_list) == 3- moves = [- {- "itemId": graphene.Node.to_global_id("MenuItem", item.pk),- "parentId": None,- "sortOrder": pos,- }- for pos, item in enumerate(menu_item_list)+ items_global_ids = [+ graphene.Node.to_global_id("MenuItem", item.pk) for item in menu_item_list]+ moves_input = [+ {"itemId": items_global_ids[0], "parentId": None, "sortOrder": 0},+ {"itemId": items_global_ids[1], "parentId": None, "sortOrder": -1},+ {"itemId": items_global_ids[2], "parentId": None, "sortOrder": None},+ ]++ expected_data = {+ "id": menu_global_id,+ "items": [+ {"id": items_global_ids[1], "sortOrder": 0, "parent": None, "children": []},+ {"id": items_global_ids[0], "sortOrder": 1, "parent": None, "children": []},+ {"id": items_global_ids[2], "sortOrder": 2, "parent": None, "children": []},+ ],+ }+response = get_graphql_content(staff_api_client.post_graphql(QUERY_REORDER_MENU,- {"moves": moves, "menu": menu_id},+ {"moves": moves_input, "menu": menu_global_id},[permission_manage_menus],))["data"]["menuItemMove"]- assert not response.get("errors")++ menu_data = response["menu"]+ assert not response["errors"]+ assert menu_data# Ensure the order is right- _assert_menu_is_exactly(menu_id, response, moves)+ assert menu_data == expected_datadef test_menu_reorder_assign_parent(staff_api_client, permission_manage_menus, menu_item_list):+ """Assign a menu item as parent of given menu items. Ensure the menu items+ are properly pushed at the bottom of the item's children.+ """menu_item_list = list(menu_item_list)+ assert len(menu_item_list) == 3+menu_id = graphene.Node.to_global_id("Menu", menu_item_list[1].menu_id)root = menu_item_list[0]- moves = [+ item0 = MenuItem.objects.create(menu=root.menu, parent=root, name="Default Link")+ menu_item_list.insert(0, item0)++ parent_global_id = graphene.Node.to_global_id("MenuItem", root.pk)+ items_global_ids = [+ graphene.Node.to_global_id("MenuItem", item.pk) for item in menu_item_list+ ]++ moves_input = [{- "itemId": graphene.Node.to_global_id("MenuItem", item.pk),- "parentId": graphene.Node.to_global_id("MenuItem", root.pk),+ "itemId": items_global_ids[2],+ "parentId": parent_global_id,"sortOrder": None,- }- for item in menu_item_list[1:]+ },+ {+ "itemId": items_global_ids[3],+ "parentId": parent_global_id,+ "sortOrder": None,+ },]+ expected_data = {+ "id": menu_id,+ "items": [+ {+ "id": items_global_ids[1],+ "sortOrder": 0,+ "parent": None,+ "children": [+ {+ "id": items_global_ids[0],+ "sortOrder": 0,+ "parent": {"id": parent_global_id},+ "children": [],+ },+ {+ "id": items_global_ids[2],+ "sortOrder": 1,+ "parent": {"id": parent_global_id},+ "children": [],+ },+ {+ "id": items_global_ids[3],+ "sortOrder": 2,+ "parent": {"id": parent_global_id},+ "children": [],+ },+ ],+ }+ ],+ }+response = get_graphql_content(staff_api_client.post_graphql(QUERY_REORDER_MENU,- {"moves": moves, "menu": menu_id},+ {"moves": moves_input, "menu": menu_id},[permission_manage_menus],))["data"]["menuItemMove"]- assert not response.get("errors")- # Ensure the parent were assigned correctly- _assert_menu_is_exactly(menu_id, response, moves)+ menu_data = response["menu"]+ assert not response["errors"]+ assert menu_data++ # Ensure the parent and sort orders were assigned correctly+ assert menu_data == expected_datadef test_menu_reorder_assign_parent_to_top_level(staff_api_client, permission_manage_menus, menu_item_list):+ """Set the parent of an item to None, to put it as to the root level."""menu_item_list = list(menu_item_list)- menu_id = graphene.Node.to_global_id("Menu", menu_item_list[0].menu_id)+ menu_global_id = graphene.Node.to_global_id("Menu", menu_item_list[0].menu_id)- root = menu_item_list[0]- root_node_id = graphene.Node.to_global_id("MenuItem", root.pk)+ unchanged_item_global_id = graphene.Node.to_global_id(+ "MenuItem", menu_item_list[2].pk+ )++ root_candidate = menu_item_list[0]+ root_candidate_global_id = graphene.Node.to_global_id("MenuItem", root_candidate.pk)# Give to the item menu a parent- root.move_to(menu_item_list[1])- root.save()+ previous_parent = menu_item_list[1]+ previous_parent_global_id = graphene.Node.to_global_id(+ "MenuItem", previous_parent.pk+ )+ root_candidate.move_to(previous_parent)+ root_candidate.save()- assert root.parent+ assert root_candidate.parent- moves = [{"itemId": root_node_id, "parentId": None, "sortOrder": None}]+ moves_input = [+ {"itemId": root_candidate_global_id, "parentId": None, "sortOrder": None}+ ]+ expected_data = {+ "id": menu_global_id,+ "items": [+ {+ "id": previous_parent_global_id,+ "sortOrder": 1,+ "parent": None,+ "children": [],+ },+ {+ "id": unchanged_item_global_id,+ "sortOrder": 2,+ "parent": None,+ "children": [],+ },+ {+ "id": root_candidate_global_id,+ "sortOrder": 3,+ "parent": None,+ "children": [],+ },+ ],+ }response = get_graphql_content(staff_api_client.post_graphql(QUERY_REORDER_MENU,- {"moves": moves, "menu": menu_id},+ {"moves": moves_input, "menu": menu_global_id},[permission_manage_menus],))["data"]["menuItemMove"]- assert not response.get("errors")- # Ensure the order is right- _assert_menu_is_exactly(menu_id, response, moves)+ menu_data = response["menu"]+ assert not response["errors"]+ assert menu_data++ # Ensure the the item was successfully placed at the root+ # and is now at the bottom of the list (default)+ assert menu_data == expected_datadef test_menu_reorder_cannot_assign_to_ancestor(@@ -691,7 +736,7 @@ def test_menu_reorder_cannot_assign_to_ancestor(assert response["errors"] == [{- "field": "parent",+ "field": "parentId","message": "Cannot assign a node as child of " "one of its descendants.",}]@@ -714,7 +759,7 @@ def test_menu_reorder_cannot_assign_to_itself()["data"]["menuItemMove"]assert response["errors"] == [- {"field": "parent", "message": "Cannot assign a node to itself."}+ {"field": "parentId", "message": "Cannot assign a node to itself."}]@@ -734,9 +779,19 @@ def test_menu_cannot_get_menu_item_not_from_same_menu(QUERY_REORDER_MENU, {"moves": moves, "menu": menu_id}, [permission_manage_menus])- assert json.loads(response.content.decode("utf8"))["errors"][0]["message"] == (- "MenuItem matching query does not exist."- )+ assert json.loads(response.content) == {+ "data": {+ "menuItemMove": {+ "errors": [+ {+ "field": "item",+ "message": f"Couldn't resolve to a node: {node_id}",+ }+ ],+ "menu": None,+ }+ }+ }def test_menu_cannot_pass_an_invalid_menu_item_node_type(@@ -755,6 +810,11 @@ def test_menu_cannot_pass_an_invalid_menu_item_node_type(QUERY_REORDER_MENU, {"moves": moves, "menu": menu_id}, [permission_manage_menus])- assert json.loads(response.content.decode("utf8"))["errors"][0]["message"] == (- "The menu item node must be of type MenuItem."- )+ assert json.loads(response.content) == {+ "data": {+ "menuItemMove": {+ "errors": [{"field": "item", "message": f"Must receive a MenuItem id"}],+ "menu": None,+ }+ }+ }