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
@@ -2,29 +2,31 @@ 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.api.v1.module_system.auth.schema import AuthSchema
from app.common.response import ResponseSchema, SuccessResponse
from app.core.base_schema import BatchSetAvailable
from app.core.base_schema import AuthSchema, BatchSetAvailable
from app.core.dependencies import AuthPermission
from app.core.logger import log
from app.core.router_class import OperationLogRoute
from .schema import DeptCreateSchema, DeptOutSchema, DeptQueryParam, DeptUpdateSchema
from .service import DeptService
DeptRouter = APIRouter(route_class=OperationLogRoute, prefix="/dept", tags=["部门管理"])
DeptRouter = APIRouter(route_class=OperationLogRoute, prefix="/dept", tags=["系统管理/部门管理"])
_DEPT_NS = "dept"
@DeptRouter.get(
"/tree",
summary="查询部门树",
description="查询部门树",
response_model=ResponseSchema[list[DeptOutSchema]],
)
@cache(expire=300, namespace=_DEPT_NS)
async def get_dept_tree_controller(
search: Annotated[DeptQueryParam, Depends()],
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:dept:query"]))],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_system:dept:query']))],
) -> JSONResponse:
"""
查询部门树
@@ -43,19 +45,17 @@ async def get_dept_tree_controller(
result_dict_list = await DeptService.get_dept_tree_service(
search=search, auth=auth, order_by=order_by
)
log.info("查询部门树成功")
return SuccessResponse(data=result_dict_list, msg="查询部门树成功")
@DeptRouter.get(
"/detail/{id}",
summary="查询部门详情",
description="查询部门详情",
response_model=ResponseSchema[DeptOutSchema],
)
async def get_obj_detail_controller(
id: Annotated[int, Path(description="部门ID")],
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:dept:detail"]))],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_system:dept:detail']))],
) -> JSONResponse:
"""
查询部门详情
@@ -71,19 +71,17 @@ async def get_obj_detail_controller(
- CustomException: 查询部门详情失败时抛出异常。
"""
result_dict = await DeptService.get_dept_detail_service(id=id, auth=auth)
log.info(f"查询部门详情成功 {id}")
return SuccessResponse(data=result_dict, msg="查询部门详情成功")
@DeptRouter.post(
"/create",
summary="创建部门",
description="创建部门",
response_model=ResponseSchema[DeptOutSchema],
)
async def create_obj_controller(
data: DeptCreateSchema,
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:dept:create"]))],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_system:dept:create']))],
) -> JSONResponse:
"""
创建部门
@@ -99,20 +97,19 @@ async def create_obj_controller(
- CustomException: 创建部门失败时抛出异常。
"""
result_dict = await DeptService.create_dept_service(data=data, auth=auth)
log.info(f"创建部门成功: {result_dict}")
await FastAPICache.clear(namespace=_DEPT_NS)
return SuccessResponse(data=result_dict, msg="创建部门成功")
@DeptRouter.put(
"/update/{id}",
summary="修改部门",
description="修改部门",
response_model=ResponseSchema[DeptOutSchema],
)
async def update_obj_controller(
data: DeptUpdateSchema,
id: Annotated[int, Path(description="部门ID")],
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:dept:update"]))],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_system:dept:update']))],
) -> JSONResponse:
"""
修改部门
@@ -129,19 +126,18 @@ async def update_obj_controller(
- CustomException: 修改部门失败时抛出异常。
"""
result_dict = await DeptService.update_dept_service(auth=auth, id=id, data=data)
log.info(f"修改部门成功: {result_dict}")
await FastAPICache.clear(namespace=_DEPT_NS)
return SuccessResponse(data=result_dict, msg="修改部门成功")
@DeptRouter.delete(
"/delete",
summary="删除部门",
description="删除部门",
response_model=ResponseSchema[None],
)
async def delete_obj_controller(
ids: Annotated[list[int], Body(description="ID列表")],
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:dept:delete"]))],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_system:dept:delete']))],
) -> JSONResponse:
"""
删除部门
@@ -157,19 +153,18 @@ async def delete_obj_controller(
- CustomException: 删除部门失败时抛出异常。
"""
await DeptService.delete_dept_service(ids=ids, auth=auth)
log.info(f"删除部门成功: {ids}")
await FastAPICache.clear(namespace=_DEPT_NS)
return SuccessResponse(msg="删除部门成功")
@DeptRouter.patch(
"/status/batch",
summary="批量修改部门状态",
description="批量修改部门状态",
response_model=ResponseSchema[None],
)
async def batch_set_available_obj_controller(
data: BatchSetAvailable,
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:dept:patch"]))],
auth: Annotated[AuthSchema, Depends(AuthPermission(['module_system:dept:patch']))],
) -> JSONResponse:
"""
批量修改部门状态
@@ -185,5 +180,5 @@ async def batch_set_available_obj_controller(
- CustomException: 批量修改部门状态失败时抛出异常。
"""
await DeptService.batch_set_available_service(data=data, auth=auth)
log.info(f"批量修改部门状态成功: {data.ids}")
await FastAPICache.clear(namespace=_DEPT_NS)
return SuccessResponse(msg="批量修改部门状态成功")
+2 -64
View File
@@ -1,7 +1,7 @@
from collections.abc import Sequence
from app.api.v1.module_system.auth.schema import AuthSchema
from app.core.base_crud import CRUDBase
from app.core.base_schema import AuthSchema
from .model import DeptModel
from .schema import DeptCreateSchema, DeptUpdateSchema
@@ -20,45 +20,9 @@ class DeptCRUD(CRUDBase[DeptModel, DeptCreateSchema, DeptUpdateSchema]):
返回:
- None
"""
self.auth = auth
super().__init__(model=DeptModel, auth=auth)
async def get_by_id_crud(self, id: int, preload: list | None = None) -> DeptModel | None:
"""
根据 id 获取部门信息。
参数:
- id (int): 部门 ID。
- preload (list | None): 预加载关系,未提供时使用模型默认项
返回:
- DeptModel | None: 部门信息,未找到返回 None。
"""
obj = await self.get(id=id, preload=preload)
if not obj:
return None
return obj
async def get_list_crud(
self,
search: dict | None = None,
order_by: list[dict] | None = None,
preload: list | None = None,
) -> Sequence[DeptModel]:
"""
获取部门列表。
参数:
- search (dict | None): 搜索条件。
- order_by (list[dict] | None): 排序字段列表。
- preload (list | None): 预加载关系,未提供时使用模型默认项
返回:
- Sequence[DeptModel]: 部门列表。
"""
return await self.list(search=search, order_by=order_by, preload=preload)
async def get_tree_list_crud(
async def get_tree_list(
self,
search: dict | None = None,
order_by: list[dict] | None = None,
@@ -81,29 +45,3 @@ class DeptCRUD(CRUDBase[DeptModel, DeptCreateSchema, DeptUpdateSchema]):
children_attr="children",
preload=preload,
)
async def set_available_crud(self, ids: list[int], status: str) -> None:
"""
批量设置部门可用状态。
参数:
- ids (list[int]): 部门 ID 列表。
- status (str): 可用状态。
返回:
- None
"""
await self.set(ids=ids, status=status)
async def get_name_crud(self, id: int) -> str | None:
"""
根据 id 获取部门名称。
参数:
- id (int): 部门 ID。
返回:
- str | None: 部门名称,未找到返回 None。
"""
obj = await self.get(id=id)
return obj.name if obj else None
@@ -16,7 +16,7 @@ class DeptCreateSchema(BaseModel):
phone: str | None = Field(default=None, max_length=20, description="联系电话")
email: str | None = Field(default=None, max_length=128, description="邮箱")
parent_id: int | None = Field(default=None, ge=0, description="父部门ID")
status: str = Field(default="0", max_length=1, description="状态(0:正常 1:禁用)")
status: int = Field(default=0, ge=0, le=1, description="状态(0:正常 1:禁用)")
description: str | None = Field(default=None, max_length=255, description="备注")
@field_validator("name")
@@ -35,9 +35,9 @@ class DeptCreateSchema(BaseModel):
@field_validator("status")
@classmethod
def validate_status(cls, value: str):
def validate_status(cls, value: int):
"""校验状态:仅支持 0(正常)、1(禁用)"""
if value not in {"0", "1"}:
if value not in {0, 1}:
raise ValueError("状态仅支持 0(正常) 或 1(禁用)")
return value
@@ -52,6 +52,7 @@ class DeptOutSchema(DeptCreateSchema, BaseSchema):
model_config = ConfigDict(from_attributes=True)
parent_name: str | None = Field(default=None, max_length=64, description="父部门名称")
children: list["DeptOutSchema"] | None = Field(default=None, description="子部门列表")
class DeptQueryParam:
@@ -1,12 +1,10 @@
from app.api.v1.module_system.auth.schema import AuthSchema
from app.core.base_schema import BatchSetAvailable
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 DeptCRUD
@@ -24,7 +22,7 @@ class DeptService:
"""
@classmethod
async def get_dept_detail_service(cls, auth: AuthSchema, id: int) -> dict:
async def get_dept_detail_service(cls, auth: AuthSchema, id: int) -> DeptOutSchema:
"""
获取部门详情。
@@ -35,13 +33,18 @@ class DeptService:
返回:
- dict: 部门详情对象。
"""
dept = await DeptCRUD(auth).get_by_id_crud(id=id)
result = DeptOutSchema.model_validate(dept).model_dump()
if dept and dept.parent_id:
dept = await DeptCRUD(auth).get(id=id)
if not dept:
raise CustomException(msg="部门不存在")
# 从列属性构建 dict,避免 Pydantic 访问 ORM 关系触发 async 惰性加载
dept_dict = {c.name: getattr(dept, c.name) for c in dept.__table__.columns}
dept_dict["children"] = None
dept_dict["parent_name"] = None
if dept.parent_id:
parent = await DeptCRUD(auth).get(id=dept.parent_id)
if parent:
result["parent_name"] = parent.name
return result
dept_dict["parent_name"] = parent.name
return DeptOutSchema(**dept_dict)
@classmethod
async def get_dept_tree_service(
@@ -62,16 +65,16 @@ class DeptService:
- list[dict]: 部门树形列表对象。
"""
# 使用树形结构查询,预加载children关系
dept_list = await DeptCRUD(auth).get_tree_list_crud(
search=search.__dict__, order_by=order_by
dept_list = await DeptCRUD(auth).get_tree_list(
search=search.__dict__ if search else {}, order_by=order_by
)
# 转换为字典列表
# 转换为字典列表tree_list 已通过 selectin 预加载 children
dept_dict_list = [DeptOutSchema.model_validate(dept).model_dump() for dept in dept_list]
# 使用traversal_to_tree构建树形结构
return traversal_to_tree(dept_dict_list)
# 仅保留根节点,子树已在 model_dump 中递归序列化
return [d for d in dept_dict_list if d.get("parent_id") is None]
@classmethod
async def create_dept_service(cls, auth: AuthSchema, data: DeptCreateSchema) -> dict:
async def create_dept_service(cls, auth: AuthSchema, data: DeptCreateSchema) -> DeptOutSchema:
"""
创建部门。
@@ -97,10 +100,10 @@ class DeptService:
await TenantService.check_quota_service(auth, auth.tenant_id, "dept")
dept = await DeptCRUD(auth).create(data=data)
return DeptOutSchema.model_validate(dept).model_dump()
return DeptOutSchema.model_validate(dept)
@classmethod
async def update_dept_service(cls, auth: AuthSchema, id: int, data: DeptUpdateSchema) -> dict:
async def update_dept_service(cls, auth: AuthSchema, id: int, data: DeptUpdateSchema) -> DeptOutSchema:
"""
更新部门。
@@ -115,7 +118,7 @@ class DeptService:
异常:
- CustomException: 当部门不存在或名称重复时抛出。
"""
dept = await DeptCRUD(auth).get_by_id_crud(id=id)
dept = await DeptCRUD(auth).get(id=id)
if not dept:
raise CustomException(msg="更新失败,该部门不存在")
exist_dept = await DeptCRUD(auth).get(name=data.name)
@@ -125,7 +128,7 @@ class DeptService:
if exist_code and exist_code.id != id:
raise CustomException(msg="更新失败,部门编码已存在")
dept = await DeptCRUD(auth).update(id=id, data=data)
return DeptOutSchema.model_validate(dept).model_dump()
return DeptOutSchema.model_validate(dept)
@classmethod
async def delete_dept_service(cls, auth: AuthSchema, ids: list[int]) -> None:
@@ -147,7 +150,7 @@ class DeptService:
raise CustomException(msg="删除失败,删除对象不能为空")
# 获取所有部门列表,用于构建树形关系
all_depts = await DeptCRUD(auth).get_list_crud()
all_depts = await DeptCRUD(auth).list()
# 构建子部门ID映射
child_id_map = get_child_id_map(model_list=all_depts)
@@ -172,10 +175,10 @@ class DeptService:
返回:
- None
"""
dept_list = await DeptCRUD(auth).get_list_crud()
dept_list = await DeptCRUD(auth).list()
total_ids = []
if data.status == "0":
if data.status == 0:
id_map = get_parent_id_map(model_list=dept_list)
for dept_id in data.ids:
enable_ids = get_parent_recursion(id=dept_id, id_map=id_map)
@@ -186,4 +189,4 @@ class DeptService:
disable_ids = get_child_recursion(id=dept_id, id_map=id_map)
total_ids.extend(disable_ids)
await DeptCRUD(auth).set_available_crud(ids=total_ids, status=data.status)
await DeptCRUD(auth).set(ids=total_ids, status=data.status)