def delete_node()

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


def delete_node():
    """Deletes the node with the given `node_id`."""

    with lock:  # Use lock to support concurrent requests
        node_id = sanitize_text(request.args.get("node_id"))

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

            old_root = app.config["NODE_TYPE"].from_dict(rubric)
            old_parent = old_root.get_parent(node_id)

            if old_root.id == node_id:
                return jsonify(
                    {
                        "status": "error",
                        "message": "Cannot delete the root node.",
                    }
                )

            # Handle the edge case where the parent of `node_id` is now a leaf node, after
            # having deleted `node_id`. We have to generate a new `task_category` since this is
            # required for all leaf nodes.
            if len(old_parent.sub_tasks) == 1:
                new_task_category = None

                if app.config["USE_API"]:
                    new_task_category = generate_task_category(old_parent)

                new_parent = replace(old_parent, task_category=new_task_category, sub_tasks=[])
                new_root = old_root.replace(old_parent.id, new_parent)
            else:
                new_root = old_root.delete(node_id)

            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 deleting node {node_id}: {e}",
                }
            )