init: 初始化 dpb 桃育种系统代码库
前后端 + 后端 FastAPI 全量源码、部署脚本与文档。
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Path, Query, Security, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.common.response import ResponseSchema, SuccessResponse
|
||||
from app.core.base_schema import AuthSchema, BatchSetAvailable
|
||||
from app.core.dependencies import AuthPermission, db_getter
|
||||
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=["菜单管理"])
|
||||
|
||||
|
||||
@MenuRouter.get("/tree", summary="查询菜单树", response_model=ResponseSchema[list[MenuOutSchema]])
|
||||
async def get_menu_tree_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:menu:query"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
search: Annotated[MenuQueryParam, Query()],
|
||||
) -> JSONResponse:
|
||||
order_by = [{"order": "asc"}]
|
||||
result_dict_tree = await MenuService(auth, db).tree(search=search, order_by=order_by)
|
||||
return SuccessResponse(data=result_dict_tree, msg="查询菜单树成功")
|
||||
|
||||
|
||||
@MenuRouter.get("/detail/{id}", summary="查询菜单详情", response_model=ResponseSchema[MenuOutSchema])
|
||||
async def get_obj_detail_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:menu:detail"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
id: Annotated[int, Path(description="菜单ID", ge=1)],
|
||||
) -> JSONResponse:
|
||||
result_dict = await MenuService(auth, db).detail(id=id)
|
||||
return SuccessResponse(data=result_dict, msg="查询菜单详情成功")
|
||||
|
||||
|
||||
@MenuRouter.post("/create", status_code=status.HTTP_201_CREATED, summary="创建菜单", response_model=ResponseSchema[MenuOutSchema])
|
||||
async def create_obj_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:menu:create"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
data: Annotated[MenuCreateSchema, Body(description="菜单创建参数")],
|
||||
) -> JSONResponse:
|
||||
result_dict = await MenuService(auth, db).create(data=data)
|
||||
return SuccessResponse(data=result_dict, msg="创建菜单成功")
|
||||
|
||||
|
||||
@MenuRouter.put("/update/{id}", summary="修改菜单", response_model=ResponseSchema[MenuOutSchema])
|
||||
async def update_obj_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:menu:update"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
id: Annotated[int, Path(description="菜单ID", ge=1)],
|
||||
data: Annotated[MenuUpdateSchema, Body(description="菜单修改参数")],
|
||||
) -> JSONResponse:
|
||||
result_dict = await MenuService(auth, db).update(id=id, data=data)
|
||||
return SuccessResponse(data=result_dict, msg="修改菜单成功")
|
||||
|
||||
|
||||
@MenuRouter.delete("/delete", summary="删除菜单", response_model=ResponseSchema[None])
|
||||
async def delete_obj_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:menu:delete"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
ids: Annotated[list[int], Body(description="菜单ID列表")],
|
||||
) -> JSONResponse:
|
||||
await MenuService(auth, db).delete(ids=ids)
|
||||
return SuccessResponse(msg="删除菜单成功")
|
||||
|
||||
|
||||
@MenuRouter.patch("/status/batch", summary="批量修改菜单状态", response_model=ResponseSchema[None])
|
||||
async def batch_set_available_obj_controller(
|
||||
auth: Annotated[AuthSchema, Security(AuthPermission(["module_system:menu:patch"]))],
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
data: Annotated[BatchSetAvailable, Body(description="状态设置")],
|
||||
) -> JSONResponse:
|
||||
await MenuService(auth, db).set_available(data=data)
|
||||
return SuccessResponse(msg="批量修改菜单状态成功")
|
||||
@@ -0,0 +1,14 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
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, db: AsyncSession) -> None:
|
||||
super().__init__(model=MenuModel, auth=auth, db=db)
|
||||
@@ -0,0 +1,52 @@
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import JSON, Boolean, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
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 = "sys_menu"
|
||||
__table_args__: dict[str, str] = {"comment": "系统菜单表"}
|
||||
|
||||
name: Mapped[str] = mapped_column(String(64), nullable=False, index=True, 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, index=True, 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), index=True, 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:否)")
|
||||
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="web", server_default="web", comment="菜单可见范围(web:管理端 desktop app:移动端)")
|
||||
status: Mapped[int] = mapped_column(Integer, default=0, nullable=False, comment="状态(0:启动 1:停用)")
|
||||
description: Mapped[str | None] = mapped_column(Text, default=None, nullable=True, comment="备注")
|
||||
parent_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("sys_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")
|
||||
@@ -0,0 +1,223 @@
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
from app.core.base_schema import BaseQueryParam, BaseSchema
|
||||
from app.core.validator import 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="描述")
|
||||
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["web", "app"] = Field(
|
||||
default="web",
|
||||
description="菜单可见范围(web:管理端 desktop app:移动端)",
|
||||
)
|
||||
|
||||
@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):
|
||||
stripped = values[k].strip()
|
||||
values[k] = stripped or 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):
|
||||
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="描述")
|
||||
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["web", "app"] | None = Field(
|
||||
default=None,
|
||||
description="菜单可见范围(web:管理端 app:移动端)",
|
||||
)
|
||||
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):
|
||||
stripped = values[k].strip()
|
||||
values[k] = stripped or 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):
|
||||
"""菜单详情响应模型(不含 children,用于详情和更新)。
|
||||
|
||||
输出模型与创建/更新校验刻意解耦:MenuCreateSchema 的 ``validate_fields`` 会执行
|
||||
``menu_request_validator``(如 type=2 菜单必须有 component_path)。若把同一套强校验
|
||||
用于输出,任何一条历史/脚本插入的「损坏」菜单(如组件路径为空)都会让菜单树、菜单管理页
|
||||
乃至登录后的 ``current/info`` 全部抛错,管理员将无法在页面看到并修复这条坏数据。
|
||||
故输出侧仅承载字段、不做业务级强校验(下方两个同名校验器覆盖为宽松实现)。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
parent_name: str | None = Field(default=None, max_length=50, description="父菜单名称")
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _normalize(cls, values):
|
||||
# 输出场景宽松归一化:不因组件路径以 / 开头等历史脏数据拒绝读取
|
||||
return values
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_fields(self):
|
||||
return self
|
||||
|
||||
|
||||
class MenuTreeOutSchema(MenuOutSchema):
|
||||
"""菜单树形响应模型(含 children,用于树形列表)"""
|
||||
|
||||
children: list["MenuTreeOutSchema"] | None = Field(default=None, description="子菜单列表")
|
||||
|
||||
|
||||
class MenuQueryParam(BaseQueryParam):
|
||||
"""菜单管理查询参数(菜单为平台级资源,无用户归属)"""
|
||||
|
||||
name: str | None = Field(None, description="菜单名称", json_schema_extra={"q": "like"})
|
||||
route_path: str | None = Field(None, description="路由地址", json_schema_extra={"q": "like"})
|
||||
component_path: str | None = Field(None, description="组件路径", json_schema_extra={"q": "like"})
|
||||
type: int | None = Field(None, description="菜单类型(1:目录 2:菜单 3:按钮 4:外链)", json_schema_extra={"q": "eq"})
|
||||
permission: str | None = Field(None, description="权限标识", json_schema_extra={"q": "eq"})
|
||||
description: str | None = Field(None, description="描述", json_schema_extra={"q": "like"})
|
||||
status: int | None = Field(None, description="是否启用", json_schema_extra={"q": "eq"})
|
||||
scope: str | None = Field(
|
||||
None,
|
||||
description="菜单范围过滤(web:管理端 desktop app:移动端)",
|
||||
json_schema_extra={"q": "eq"},
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
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,
|
||||
search_to_dict,
|
||||
traversal_to_tree,
|
||||
)
|
||||
|
||||
from .crud import MenuCRUD
|
||||
from .schema import (
|
||||
MenuCreateSchema,
|
||||
MenuOutSchema,
|
||||
MenuQueryParam,
|
||||
MenuUpdateSchema,
|
||||
)
|
||||
|
||||
|
||||
class MenuService:
|
||||
"""菜单管理服务(查询操作租户可见,写操作仅超级管理员可操作)"""
|
||||
|
||||
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
|
||||
self.auth = auth
|
||||
self.db = db
|
||||
|
||||
async def _validate_parent_child_type(self, parent_id: int | None, child_type: int | None) -> 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(self.auth, self.db).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="菜单或链接类型下不允许新增子菜单")
|
||||
|
||||
async def _validate_parent_child_scope(self, parent_id: int | None, scope: str | None) -> None:
|
||||
if parent_id is None or scope is None:
|
||||
return
|
||||
parent = await MenuCRUD(self.auth, self.db).get(id=parent_id)
|
||||
if not parent:
|
||||
return
|
||||
p_scope = getattr(parent, "scope", None) or "web"
|
||||
if p_scope != scope:
|
||||
raise CustomException(msg="子菜单可见范围须与父菜单一致")
|
||||
|
||||
async def detail(self, id: int) -> MenuOutSchema:
|
||||
menu = await MenuCRUD(self.auth, self.db).get(id=id, preload=["roles"])
|
||||
if not menu:
|
||||
raise CustomException(msg="菜单不存在")
|
||||
menu_out = MenuOutSchema.model_validate(menu)
|
||||
if menu.parent_id:
|
||||
parent = await MenuCRUD(self.auth, self.db).get(id=menu.parent_id)
|
||||
if parent:
|
||||
menu_out.parent_name = parent.name
|
||||
return menu_out
|
||||
|
||||
async def tree(
|
||||
self,
|
||||
search: MenuQueryParam | None = None,
|
||||
order_by: list[dict] | None = None,
|
||||
) -> list[dict]:
|
||||
menu_list = await MenuCRUD(self.auth, self.db).get_list(search=search_to_dict(search), order_by=order_by)
|
||||
menu_dict_list = [MenuOutSchema.model_validate(menu).model_dump() for menu in menu_list]
|
||||
return traversal_to_tree(menu_dict_list)
|
||||
|
||||
async def create(self, data: MenuCreateSchema) -> MenuOutSchema:
|
||||
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(self.auth, self.db).get(**search)
|
||||
if menu:
|
||||
raise CustomException(msg="创建失败,该菜单已存在")
|
||||
|
||||
await self._validate_parent_child_type(data.parent_id, data.type)
|
||||
await self._validate_parent_child_scope(data.parent_id, data.scope)
|
||||
|
||||
new_menu = await MenuCRUD(self.auth, self.db).create(data=data)
|
||||
return MenuOutSchema.model_validate(new_menu)
|
||||
|
||||
async def update(self, id: int, data: MenuUpdateSchema) -> MenuOutSchema:
|
||||
_ = await MenuCRUD(self.auth, self.db).get_or_404(id=id, msg="更新失败,该菜单不存在")
|
||||
await self._validate_parent_child_type(data.parent_id, data.type)
|
||||
await self._validate_parent_child_scope(data.parent_id, data.scope)
|
||||
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(self.auth, self.db).get(**search)
|
||||
if exist_menu and exist_menu.id != id:
|
||||
raise CustomException(msg="更新失败,菜单标题重复")
|
||||
|
||||
if data.parent_id:
|
||||
parent_menu = await MenuCRUD(self.auth, self.db).get(id=data.parent_id)
|
||||
if not parent_menu:
|
||||
raise CustomException(msg="更新失败,父级菜单不存在")
|
||||
|
||||
new_menu = await MenuCRUD(self.auth, self.db).update(id=id, data=data)
|
||||
|
||||
if data.status is not None:
|
||||
await self.set_available(data=BatchSetAvailable(ids=[id], status=data.status))
|
||||
|
||||
menu_out = MenuOutSchema.model_validate(new_menu)
|
||||
if menu_out.parent_id:
|
||||
parent = await MenuCRUD(self.auth, self.db).get(id=menu_out.parent_id)
|
||||
if parent:
|
||||
menu_out.parent_name = parent.name
|
||||
return menu_out
|
||||
|
||||
async def delete(self, ids: list[int]) -> None:
|
||||
if not ids:
|
||||
raise CustomException(msg="删除失败,删除对象不能为空")
|
||||
|
||||
all_menus = await MenuCRUD(self.auth, self.db).get_list()
|
||||
child_id_map = get_child_id_map(model_list=all_menus)
|
||||
|
||||
delete_ids_set = set()
|
||||
for mid in ids:
|
||||
all_descendants = get_child_recursion(id=mid, id_map=child_id_map)
|
||||
delete_ids_set.update(all_descendants)
|
||||
|
||||
delete_ids = list(delete_ids_set)
|
||||
await MenuCRUD(self.auth, self.db).delete(ids=delete_ids)
|
||||
|
||||
async def set_available(self, data: BatchSetAvailable) -> None:
|
||||
menu_list = await MenuCRUD(self.auth, self.db).get_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(self.auth, self.db).set(ids=total_ids, status=data.status)
|
||||
Reference in New Issue
Block a user