refactor: 大规模代码整理与功能优化

1. 重构后端API路由、CRUD与模块结构,整合日志管理,移除废弃demo代码
2. 优化前端组件类型定义、样式与路由配置,修复权限判断逻辑
3. 调整默认排序规则、滚动条样式与工具类函数,更新依赖与配置文件
4. 修复多处类型不匹配与默认值问题,完善表单与菜单验证逻辑
This commit is contained in:
zhangtao
2026-06-17 01:56:31 +08:00
parent 17b3cd0a4c
commit 73f2823692
500 changed files with 40763 additions and 26616 deletions
@@ -0,0 +1,160 @@
from typing import Annotated
from fastapi import APIRouter, Body, Depends, Path
from fastapi.responses import JSONResponse
from fastapi_cache import FastAPICache
from fastapi_cache.decorator import cache
from app.common.response import ResponseSchema, SuccessResponse
from app.core.base_schema import AuthSchema, BatchSetAvailable
from app.core.dependencies import AuthPermission
from app.core.router_class import OperationLogRoute
from .schema import MenuCreateSchema, MenuOutSchema, MenuQueryParam, MenuUpdateSchema
from .service import MenuService
MenuRouter = APIRouter(route_class=OperationLogRoute, prefix="/menu", tags=["平台管理/菜单管理"])
_MENU_NS = "menu"
@MenuRouter.get(
"/tree",
summary="查询菜单树",
response_model=ResponseSchema[list[MenuOutSchema]],
)
@cache(expire=300, namespace=_MENU_NS)
async def get_menu_tree_controller(
search: Annotated[MenuQueryParam, Depends()],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_platform:menu:query']))],
) -> JSONResponse:
"""
查询菜单树。
参数:
- search (MenuQueryParam): 查询参数模型。
返回:
- JSONResponse: 包含菜单树的 JSON 响应。
"""
order_by = [{"order": "asc"}]
result_dict_list = await MenuService.get_menu_tree_service(
search=search, auth=auth, order_by=order_by
)
return SuccessResponse(data=result_dict_list, msg="查询菜单树成功")
@MenuRouter.get(
"/detail/{id}",
summary="查询菜单详情",
response_model=ResponseSchema[MenuOutSchema],
)
async def get_obj_detail_controller(
id: Annotated[int, Path(description="菜单ID")],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_platform:menu:detail']))],
) -> JSONResponse:
"""
查询菜单详情。
参数:
- id (int): 菜单ID。
返回:
- JSONResponse: 包含菜单详情的 JSON 响应。
"""
result_dict = await MenuService.get_menu_detail_service(id=id, auth=auth)
return SuccessResponse(data=result_dict, msg="查询菜单详情成功")
@MenuRouter.post(
"/create",
summary="创建菜单",
response_model=ResponseSchema[MenuOutSchema],
)
async def create_obj_controller(
data: MenuCreateSchema,
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_platform:menu:create']))],
) -> JSONResponse:
"""
创建菜单。
参数:
- data (MenuCreateSchema): 菜单创建模型。
返回:
- JSONResponse: 包含创建菜单的 JSON 响应。
"""
result_dict = await MenuService.create_menu_service(data=data, auth=auth)
await FastAPICache.clear(namespace=_MENU_NS)
return SuccessResponse(data=result_dict, msg="创建菜单成功")
@MenuRouter.put(
"/update/{id}",
summary="修改菜单",
response_model=ResponseSchema[MenuOutSchema],
)
async def update_obj_controller(
data: MenuUpdateSchema,
id: Annotated[int, Path(description="菜单ID")],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_platform:menu:update']))],
) -> JSONResponse:
"""
修改菜单。
参数:
- id (int): 菜单ID。
- data (MenuUpdateSchema): 菜单更新模型。
返回:
- JSONResponse: 包含修改菜单的 JSON 响应。
"""
result_dict = await MenuService.update_menu_service(id=id, data=data, auth=auth)
await FastAPICache.clear(namespace=_MENU_NS)
return SuccessResponse(data=result_dict, msg="修改菜单成功")
@MenuRouter.delete(
"/delete",
summary="删除菜单",
response_model=ResponseSchema[None],
)
async def delete_obj_controller(
ids: Annotated[list[int], Body(description="ID列表")],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_platform:menu:delete']))],
) -> JSONResponse:
"""
删除菜单。
参数:
- ids (list[int]): 菜单ID列表。
返回:
- JSONResponse: 包含删除菜单的 JSON 响应。
"""
await MenuService.delete_menu_service(ids=ids, auth=auth)
await FastAPICache.clear(namespace=_MENU_NS)
return SuccessResponse(msg="删除菜单成功")
@MenuRouter.patch(
"/status/batch",
summary="批量修改菜单状态",
response_model=ResponseSchema[None],
)
async def batch_set_available_obj_controller(
data: BatchSetAvailable,
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_platform:menu:patch']))],
) -> JSONResponse:
"""
批量修改菜单状态。
参数:
- data (BatchSetAvailable): 批量修改菜单状态模型。
返回:
- JSONResponse: 批量修改菜单状态的 JSON 响应。
"""
await MenuService.set_menu_available_service(data=data, auth=auth)
await FastAPICache.clear(namespace=_MENU_NS)
return SuccessResponse(msg="批量修改菜单状态成功")
@@ -0,0 +1,47 @@
from collections.abc import Sequence
from app.core.base_crud import CRUDBase
from app.core.base_schema import AuthSchema
from .model import MenuModel
from .schema import MenuCreateSchema, MenuUpdateSchema
class MenuCRUD(CRUDBase[MenuModel, MenuCreateSchema, MenuUpdateSchema]):
"""菜单模块数据层"""
def __init__(self, auth: AuthSchema) -> None:
"""
初始化菜单数据层。
参数:
- auth (AuthSchema): 认证信息模型(含 DB 会话等上下文)。
返回:
- None
"""
super().__init__(model=MenuModel, auth=auth)
async def get_tree_list(
self,
search: dict | None = None,
order_by: list[dict] | None = None,
preload: list[str] | None = None,
) -> Sequence[MenuModel]:
"""
获取菜单树形列表。
参数:
- search (dict | None): 搜索条件。
- order_by (list[dict] | None): 排序字段列表。
- preload (list[str] | None): 预加载关系,未提供时使用模型默认项
返回:
- Sequence[MenuModel]: 菜单树形列表。
"""
return await self.tree_list(
search=search,
order_by=order_by,
children_attr="children",
preload=preload,
)
@@ -0,0 +1,121 @@
from typing import TYPE_CHECKING
from sqlalchemy import JSON, Boolean, ForeignKey, Integer, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.common.enums import PermissionFilterStrategy
from app.core.base_model import ModelMixin
if TYPE_CHECKING:
from app.api.v1.module_system.role.model import RoleModel
class MenuModel(ModelMixin):
"""
菜单表 - 用于存储系统菜单资源定义
菜单类型说明:
- 1: 目录(一级菜单)
- 2: 菜单(二级菜单)
- 3: 按钮/权限(页面内按钮权限)
- 4: 外部链接
"""
__tablename__: str = "platform_menu"
__table_args__: dict[str, str] = {"comment": "平台菜单表"}
__loader_options__: list[str] = ["roles"]
__permission_strategy__: PermissionFilterStrategy = PermissionFilterStrategy.ROLE_BASED
name: Mapped[str] = mapped_column(String(50), nullable=False, comment="菜单名称")
type: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=2,
comment="菜单类型(1:目录 2:菜单 3:按钮/权限 4:链接)",
)
order: Mapped[int] = mapped_column(Integer, nullable=False, default=999, comment="显示排序")
permission: Mapped[str | None] = mapped_column(
String(100), comment="权限标识(如:module_system:user:query)"
)
icon: Mapped[str | None] = mapped_column(String(50), comment="菜单图标")
route_name: Mapped[str | None] = mapped_column(String(100), comment="路由名称")
route_path: Mapped[str | None] = mapped_column(String(200), comment="路由路径")
component_path: Mapped[str | None] = mapped_column(String(200), comment="组件路径")
redirect: Mapped[str | None] = mapped_column(String(200), comment="重定向地址")
hidden: Mapped[bool] = mapped_column(
Boolean,
default=False,
nullable=False,
comment="是否隐藏(True:隐藏 False:显示)",
)
keep_alive: Mapped[bool] = mapped_column(
Boolean,
default=True,
nullable=False,
comment="是否缓存(True:是 False:否)",
)
always_show: Mapped[bool] = mapped_column(
Boolean,
default=False,
nullable=False,
comment="是否始终显示(True:是 False:否)",
)
title: Mapped[str | None] = mapped_column(String(50), comment="菜单标题")
params: Mapped[list[dict[str, str]] | None] = mapped_column(JSON, comment="路由参数(JSON对象)")
affix: Mapped[bool] = mapped_column(
Boolean,
default=False,
nullable=False,
comment="是否固定标签页(True:是 False:否)",
)
client: Mapped[str] = mapped_column(
String(20),
nullable=False,
default="pc",
server_default="pc",
comment="终端(pc:管理端桌面 app:移动端)",
)
link: Mapped[str | None] = mapped_column(String(500), comment="外链地址(仅type=4)")
is_iframe: Mapped[bool] = mapped_column(
Boolean, default=False, nullable=False, comment="是否嵌入iframe(True:是 False:否)"
)
is_hide_tab: Mapped[bool] = mapped_column(
Boolean, default=False, nullable=False, comment="是否隐藏标签页(True:是 False:否)"
)
active_path: Mapped[str | None] = mapped_column(String(200), comment="激活菜单路径(用于高亮父级)")
show_badge: Mapped[bool] = mapped_column(
Boolean, default=False, nullable=False, comment="是否显示红点角标(True:是 False:否)"
)
show_text_badge: Mapped[str | None] = mapped_column(String(20), comment="文字角标内容")
scope: Mapped[str] = mapped_column(
String(20),
nullable=False,
default="tenant",
server_default="tenant",
comment="菜单可见范围(platform:仅平台 tenant:租户可用)",
)
# 树形结构
parent_id: Mapped[int | None] = mapped_column(
Integer,
ForeignKey("platform_menu.id", ondelete="SET NULL"),
default=None,
index=True,
comment="父菜单ID",
)
# 关联关系
parent: Mapped["MenuModel | None"] = relationship(
back_populates="children",
remote_side="MenuModel.id",
foreign_keys="MenuModel.parent_id",
uselist=False,
)
children: Mapped[list["MenuModel"] | None] = relationship(
back_populates="parent",
foreign_keys="MenuModel.parent_id",
order_by="MenuModel.order",
)
roles: Mapped[list["RoleModel"]] = relationship(
secondary="sys_role_menus", back_populates="menus", lazy="selectin"
)
@@ -0,0 +1,259 @@
from typing import Literal
from fastapi import Query
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from app.common.enums import QueueEnum
from app.core.base_schema import BaseSchema
from app.core.validator import DateTimeStr, menu_request_validator
class MenuCreateSchema(BaseModel):
"""菜单创建模型"""
name: str = Field(..., min_length=1, max_length=50, description="菜单名称")
type: int = Field(..., ge=1, le=4, description="菜单类型(1:目录 2:菜单 3:按钮 4:外链)")
order: int = Field(..., ge=0, description="显示顺序")
permission: str | None = Field(default=None, max_length=100, description="权限标识")
icon: str | None = Field(default=None, max_length=50, description="菜单图标")
route_name: str | None = Field(default=None, max_length=100, description="路由名称")
route_path: str | None = Field(default=None, max_length=200, description="路由地址")
component_path: str | None = Field(default=None, max_length=200, description="组件路径")
redirect: str | None = Field(default=None, max_length=200, description="重定向地址")
hidden: bool = Field(default=False, description="是否隐藏")
keep_alive: bool = Field(default=True, description="是否缓存")
always_show: bool = Field(default=False, description="是否始终显示")
title: str | None = Field(default=None, max_length=50, description="菜单标题")
params: list[dict[str, str]] | None = Field(
default=None,
description="路由参数,格式为[{key: string, value: string}]",
)
affix: bool = Field(default=False, description="是否固定标签页")
parent_id: int | None = Field(default=None, ge=1, description="父菜单ID")
status: int = Field(default=0, ge=0, le=1, description="状态(0:正常 1:禁用)")
description: str | None = Field(default=None, max_length=255, description="描述")
client: Literal["pc", "app"] = Field(
default="pc",
description="终端(pc:管理端桌面 app:移动端)",
)
link: str | None = Field(default=None, max_length=500, description="外链地址(仅type=4)")
is_iframe: bool = Field(default=False, description="是否嵌入iframe")
is_hide_tab: bool = Field(default=False, description="是否隐藏标签页")
active_path: str | None = Field(default=None, max_length=200, description="激活菜单路径")
show_badge: bool = Field(default=False, description="是否显示红点角标")
show_text_badge: str | None = Field(default=None, max_length=20, description="文字角标内容")
scope: Literal["platform", "tenant"] = Field(
default="tenant",
description="菜单可见范围(platform:仅平台 tenant:租户可用)",
)
@field_validator("status")
@classmethod
def _validate_status(cls, v: int) -> int:
if v not in {0, 1}:
raise ValueError("状态仅支持 0(正常) 或 1(禁用)")
return v
@model_validator(mode="before")
@classmethod
def _normalize(cls, values):
if isinstance(values, dict):
# 字符串去空格
for k in [
"name",
"icon",
"permission",
"route_name",
"route_path",
"component_path",
"redirect",
"title",
"description",
"link",
"active_path",
"show_text_badge",
]:
if k in values and isinstance(values[k], str):
values[k] = (
values[k].strip() or None if values[k].strip() == "" else values[k].strip()
)
if "client" in values and isinstance(values["client"], str):
cv = values["client"].strip()
values["client"] = cv if cv in ("pc", "app") else "pc"
# 父ID转整型
if "parent_id" in values and isinstance(values["parent_id"], str):
try:
values["parent_id"] = int(values["parent_id"].strip())
except (ValueError, TypeError):
pass # parent_id 不是有效整数,保留原值
# 组件路径规范
if "component_path" in values and isinstance(values["component_path"], str):
cp = values["component_path"]
if cp and cp.startswith("/"):
raise ValueError("组件路径不能以 / 开头")
return values
@model_validator(mode="after")
def validate_fields(self):
"""
统一校验菜单请求字段(委托到 `menu_request_validator`)。
返回:
- MenuCreateSchema: 校验后的同一实例。
异常:
- CustomException: 字段不满足菜单类型约束时抛出。
"""
return menu_request_validator(self)
class MenuUpdateSchema(BaseModel):
"""菜单更新模型 — 所有字段可选"""
name: str | None = Field(default=None, min_length=1, max_length=50, description="菜单名称")
type: int | None = Field(default=None, ge=1, le=4, description="菜单类型(1:目录 2:菜单 3:按钮 4:外链)")
order: int | None = Field(default=None, ge=0, description="显示顺序")
permission: str | None = Field(default=None, max_length=100, description="权限标识")
icon: str | None = Field(default=None, max_length=50, description="菜单图标")
route_name: str | None = Field(default=None, max_length=100, description="路由名称")
route_path: str | None = Field(default=None, max_length=200, description="路由地址")
component_path: str | None = Field(default=None, max_length=200, description="组件路径")
redirect: str | None = Field(default=None, max_length=200, description="重定向地址")
hidden: bool | None = Field(default=None, description="是否隐藏")
keep_alive: bool | None = Field(default=None, description="是否缓存")
always_show: bool | None = Field(default=None, description="是否始终显示")
title: str | None = Field(default=None, max_length=50, description="菜单标题")
params: list[dict[str, str]] | None = Field(default=None, description="路由参数")
affix: bool | None = Field(default=None, description="是否固定标签页")
parent_id: int | None = Field(default=None, ge=1, description="父菜单ID")
status: int | None = Field(default=None, ge=0, le=1, description="状态(0:正常 1:禁用)")
description: str | None = Field(default=None, max_length=255, description="描述")
client: Literal["pc", "app"] | None = Field(default=None, description="终端(pc:管理端桌面 app:移动端)")
link: str | None = Field(default=None, max_length=500, description="外链地址(仅type=4)")
is_iframe: bool | None = Field(default=None, description="是否嵌入iframe")
is_hide_tab: bool | None = Field(default=None, description="是否隐藏标签页")
active_path: str | None = Field(default=None, max_length=200, description="激活菜单路径")
show_badge: bool | None = Field(default=None, description="是否显示红点角标")
show_text_badge: str | None = Field(default=None, max_length=20, description="文字角标内容")
scope: Literal["platform", "tenant"] | None = Field(
default=None,
description="菜单可见范围(platform:仅平台 tenant:租户可用)",
)
parent_name: str | None = Field(default=None, max_length=50, description="父菜单名称")
@field_validator("status")
@classmethod
def _validate_status(cls, v: int | None) -> int | None:
if v is None:
return v
if v not in {0, 1}:
raise ValueError("状态仅支持 0(正常) 或 1(禁用)")
return v
@model_validator(mode="before")
@classmethod
def _normalize(cls, values):
if isinstance(values, dict):
for k in [
"name", "icon", "permission", "route_name", "route_path",
"component_path", "redirect", "title", "description",
"link", "active_path", "show_text_badge",
]:
if k in values and isinstance(values[k], str):
values[k] = values[k].strip() or None if values[k].strip() == "" else values[k].strip()
if "client" in values and isinstance(values["client"], str):
cv = values["client"].strip()
values["client"] = cv if cv in ("pc", "app") else None
if "parent_id" in values and isinstance(values["parent_id"], str):
try:
values["parent_id"] = int(values["parent_id"].strip())
except (ValueError, TypeError):
pass
if "component_path" in values and isinstance(values["component_path"], str) and values["component_path"]:
if values["component_path"].startswith("/"):
raise ValueError("组件路径不能以 / 开头")
return values
@model_validator(mode="after")
def validate_fields(self):
if self.type is None:
return self
return menu_request_validator(self)
class MenuOutSchema(MenuCreateSchema, BaseSchema):
"""菜单响应模型"""
model_config = ConfigDict(from_attributes=True)
parent_name: str | None = Field(default=None, max_length=50, description="父菜单名称")
children: list["MenuOutSchema"] | None = Field(default=None, description="子菜单列表")
class MenuQueryParam:
"""菜单管理查询参数"""
def __init__(
self,
name: str | None = Query(None, description="菜单名称"),
route_path: str | None = Query(None, description="路由地址"),
component_path: str | None = Query(None, description="组件路径"),
type: Literal[1, 2, 3, 4] | None = Query(
None, description="菜单类型(1:目录 2:菜单 3:按钮 4:外链)"
),
permission: str | None = Query(None, description="权限标识"),
description: str | None = Query(None, description="描述"),
status: str | None = Query(None, description="是否启用"),
created_time: list[DateTimeStr] | None = Query(
None,
description="创建时间范围",
examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"],
),
updated_time: list[DateTimeStr] | None = Query(
None,
description="更新时间范围",
examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"],
),
created_id: int | None = Query(None, description="创建人"),
updated_id: int | None = Query(None, description="更新人"),
menu_client: Literal["pc", "app"] | None = Query(
None,
description="管理端 Tab:pc=桌面端菜单 app=移动端菜单;不传则不过滤终端",
),
scope: Literal["tenant"] | None = Query(
None,
description="菜单范围过滤:tenant=仅租户可用菜单",
),
) -> None:
# 模糊查询字段
self.name = (QueueEnum.like.value, name)
self.route_path = (QueueEnum.like.value, route_path)
self.component_path = (QueueEnum.like.value, component_path)
self.permission = (QueueEnum.like.value, permission)
# 精确查询字段
self.type = type
# 模糊查询字段
if description:
self.description = (QueueEnum.like.value, description)
# 精确查询字段
if status:
self.status = (QueueEnum.eq.value, status)
# 时间范围查询
if created_time and len(created_time) == 2:
self.created_time = (QueueEnum.between.value, (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2:
self.updated_time = (QueueEnum.between.value, (updated_time[0], updated_time[1]))
# 关联查询字段
if created_id:
self.created_id = (QueueEnum.eq.value, created_id)
if updated_id:
self.updated_id = (QueueEnum.eq.value, updated_id)
if menu_client in ("pc", "app"):
self.client = (QueueEnum.eq.value, menu_client)
if scope == "tenant":
self.scope = (QueueEnum.eq.value, "tenant")
@@ -0,0 +1,248 @@
from typing import Any
from app.core.base_schema import AuthSchema, BatchSetAvailable
from app.core.exceptions import CustomException
from app.utils.common_util import (
get_child_id_map,
get_child_recursion,
get_parent_id_map,
get_parent_recursion,
traversal_to_tree,
)
from .crud import MenuCRUD
from .schema import (
MenuCreateSchema,
MenuOutSchema,
MenuQueryParam,
MenuUpdateSchema,
)
class MenuService:
"""
菜单模块服务层
"""
@classmethod
async def _validate_parent_child_type(
cls, auth: AuthSchema, parent_id: int | None, child_type: int
) -> None:
"""
父子类型约束:目录下仅允许目录/菜单/外链;菜单下仅允许按钮;按钮与外链下不可挂子级。
无父级时仅允许目录、菜单、外链(与前端一致)。
"""
if parent_id is None:
if child_type is None:
return
if child_type not in (1, 2, 4):
raise CustomException(msg="顶级菜单仅允许目录、菜单或外链类型")
return
parent = await MenuCRUD(auth).get(id=parent_id)
if not parent:
raise CustomException(msg="父级菜单不存在")
pt = parent.type
if pt == 1:
if child_type not in (1, 2, 4):
raise CustomException(msg="目录下仅允许新增目录、菜单或外链")
elif pt == 2:
if child_type != 3:
raise CustomException(msg="菜单下仅允许新增按钮")
else:
raise CustomException(msg="菜单或链接类型下不允许新增子菜单")
@classmethod
async def _validate_parent_child_client(
cls, auth: AuthSchema, parent_id: int | None, client: str
) -> None:
"""子菜单终端须与父菜单一致。"""
if parent_id is None or client is None:
return
parent = await MenuCRUD(auth).get(id=parent_id)
if not parent:
return
p_client = getattr(parent, "client", None) or "pc"
if p_client != client:
raise CustomException(msg="子菜单终端须与父菜单一致(均为 pc 或均为 app)")
@classmethod
async def get_menu_detail_service(cls, auth: AuthSchema, id: int) -> MenuOutSchema:
"""
获取菜单详情。
参数:
- auth (AuthSchema): 认证对象。
- id (int): 菜单ID。
返回:
- dict: 菜单详情对象。
"""
menu = await MenuCRUD(auth).get(id=id)
# 创建实例后再设置parent_name属性
menu_out = MenuOutSchema.model_validate(menu)
if menu and menu.parent_id:
parent = await MenuCRUD(auth).get(id=menu.parent_id)
if parent:
menu_out.parent_name = parent.name
return menu_out
@classmethod
async def get_menu_tree_service(
cls,
auth: AuthSchema,
search: MenuQueryParam | None = None,
order_by: list[dict] | None = None,
) -> list[dict]:
"""
获取菜单树形列表。
参数:
- auth (AuthSchema): 认证对象。
- search (MenuQueryParam | None): 查询参数对象。
- order_by (list[dict] | None): 排序参数列表。
返回:
- list[dict]: 菜单树形列表对象。
"""
# 使用树形结构查询,预加载children关系
menu_list = await MenuCRUD(auth).get_tree_list(
search=search.__dict__, order_by=order_by
)
# 转换为字典列表
menu_dict_list = [MenuOutSchema.model_validate(menu).model_dump() for menu in menu_list]
# 使用traversal_to_tree构建树形结构
return traversal_to_tree(menu_dict_list)
@classmethod
async def create_menu_service(cls, auth: AuthSchema, data: MenuCreateSchema) -> MenuOutSchema:
"""
创建菜单。
参数:
- auth (AuthSchema): 认证对象。
- data (MenuCreateSchema): 创建参数对象。
返回:
- dict: 创建的菜单对象。
"""
search: dict[str, Any] = {}
if data.title is not None:
search["title"] = data.title
if data.parent_id is not None:
search["parent_id"] = data.parent_id
menu = await MenuCRUD(auth).get(**search)
if menu:
raise CustomException(msg="创建失败,该菜单已存在")
await cls._validate_parent_child_type(auth, data.parent_id, data.type)
await cls._validate_parent_child_client(auth, data.parent_id, data.client)
new_menu = await MenuCRUD(auth).create(data=data)
new_menu_dict = MenuOutSchema.model_validate(new_menu)
return new_menu_dict
@classmethod
async def update_menu_service(cls, auth: AuthSchema, id: int, data: MenuUpdateSchema) -> MenuOutSchema:
"""
更新菜单。
参数:
- auth (AuthSchema): 认证对象。
- id (int): 菜单ID。
- data (MenuUpdateSchema): 更新参数对象。
返回:
- dict: 更新的菜单对象。
"""
menu = await MenuCRUD(auth).get(id=id)
if not menu:
raise CustomException(msg="更新失败,该菜单不存在")
await cls._validate_parent_child_type(auth, data.parent_id, data.type)
await cls._validate_parent_child_client(auth, data.parent_id, data.client)
if data.title is not None:
search: dict[str, Any] = {"title": data.title}
if data.parent_id is not None:
search["parent_id"] = data.parent_id
exist_menu = await MenuCRUD(auth).get(**search)
if exist_menu and exist_menu.id != id:
raise CustomException(msg="更新失败,菜单标题重复")
if data.parent_id:
parent_menu = await MenuCRUD(auth).get(id=data.parent_id)
if not parent_menu:
raise CustomException(msg="更新失败,父级菜单不存在")
new_menu = await MenuCRUD(auth).update(id=id, data=data)
if data.status is not None:
await cls.set_menu_available_service(
auth=auth, data=BatchSetAvailable(ids=[id], status=data.status)
)
new_menu_dict = MenuOutSchema.model_validate(new_menu)
return new_menu_dict
@classmethod
async def delete_menu_service(cls, auth: AuthSchema, ids: list[int]) -> None:
"""
删除菜单。
参数:
- auth (AuthSchema): 认证对象。
- ids (list[int]): 菜单ID列表。
返回:
- None
"""
if len(ids) < 1:
raise CustomException(msg="删除失败,删除对象不能为空")
# 获取所有菜单列表,用于构建树形关系
all_menus = await MenuCRUD(auth).list()
# 构建子菜单ID映射
child_id_map = get_child_id_map(model_list=all_menus)
# 收集所有需要删除的菜单ID,包括直接指定的ID和它们的所有子菜单ID
delete_ids_set = set()
for id in ids:
# 递归获取该ID的所有子菜单ID
all_descendants = get_child_recursion(id=id, id_map=child_id_map)
delete_ids_set.update(all_descendants)
# 将集合转换为列表
delete_ids = list(delete_ids_set)
# 执行批量删除操作
await MenuCRUD(auth).delete(ids=delete_ids)
@classmethod
async def set_menu_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
"""
递归获取所有父、子级菜单,然后批量修改菜单可用状态。
参数:
- auth (AuthSchema): 认证对象。
- data (BatchSetAvailable): 批量设置可用参数对象。
返回:
- None
"""
menu_list = await MenuCRUD(auth).list()
total_ids = []
if data.status == 0:
# 激活,则需要把所有父级菜单都激活
id_map = get_parent_id_map(model_list=menu_list)
for menu_id in data.ids:
enable_ids = get_parent_recursion(id=menu_id, id_map=id_map)
total_ids.extend(enable_ids)
else:
# 禁止,则需要把所有子级菜单都禁止
id_map = get_child_id_map(model_list=menu_list)
for menu_id in data.ids:
disable_ids = get_child_recursion(id=menu_id, id_map=id_map)
total_ids.extend(disable_ids)
await MenuCRUD(auth).set(ids=total_ids, status=data.status)