def move_node_to_parent()

in project/paperbench/paperbench/gui/app.py [0:0]


def move_node_to_parent():
    """Moves a node to become a child of another node."""
    with lock:
        data = sanitize_request_data(request.json)
        node_id = data.get("node_id")
        new_parent_id = data.get("new_parent_id")

        try:
            with open(app.config["PATH_TO_PAPER"] / app.config["RUBRIC_FILE_NAME"], "r") as f:
                rubric = json.load(f)

            root = app.config["NODE_TYPE"].from_dict(rubric)
            node_to_move = root.find(node_id)

            if not root.contains(node_id):
                return jsonify(
                    {"status": "error", "message": f"Node with ID '{node_id}' not found."}
                )
            if not root.contains(new_parent_id):
                return jsonify(
                    {
                        "status": "error",
                        "message": f"Parent node with ID '{new_parent_id}' not found.",
                    }
                )
            if root.id == node_id:
                return jsonify({"status": "error", "message": "Cannot move the root node."})
            if node_to_move.contains(new_parent_id):
                return jsonify(
                    {
                        "status": "error",
                        "message": "Cannot move a node to itself or to one of its descendants.",
                    }
                )

            new_root = root.delete(node_id)
            new_parent = new_root.find(new_parent_id)
            new_new_parent = new_parent.add_sub_task(node_to_move)
            new_root = new_root.replace(new_parent_id, new_new_parent)

            with open(app.config["PATH_TO_PAPER"] / app.config["RUBRIC_FILE_NAME"], "w") as f:
                json.dump(new_root.to_dict(), f, indent=4)

            return jsonify({"status": "success"})
        except Exception as e:
            return jsonify({"status": "error", "message": f"Error moving node {node_id}: {str(e)}"})