upload project source code

This commit is contained in:
2026-04-30 18:49:43 +08:00
commit 9b394ba682
2277 changed files with 660945 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-

View File

@@ -0,0 +1,201 @@
# -*- coding: utf-8 -*-
from fastapi import APIRouter, Body, Depends, Path
from fastapi.responses import JSONResponse, StreamingResponse
from app.common.response import StreamResponse, SuccessResponse
from app.common.request import PaginationService
from app.core.router_class import OperationLogRoute
from app.utils.common_util import bytes2file_response
from app.core.base_params import PaginationQueryParam
from app.core.dependencies import AuthPermission
from app.core.base_schema import BatchSetAvailable
from app.core.logger import log
from ..auth.schema import AuthSchema
from .service import RoleService
from .schema import (
RoleCreateSchema,
RoleUpdateSchema,
RolePermissionSettingSchema,
RoleQueryParam
)
RoleRouter = APIRouter(route_class=OperationLogRoute, prefix="/role", tags=["角色管理"])
@RoleRouter.get("/list", summary="查询角色", description="查询角色")
async def get_obj_list_controller(
page: PaginationQueryParam = Depends(),
search: RoleQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_system:role:query"])),
) -> JSONResponse:
"""
查询角色
参数:
- page (PaginationQueryParam): 分页查询参数模型
- search (RoleQueryParam): 查询参数模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 分页查询结果JSON响应
"""
order_by = [{"order": "asc"}]
if page.order_by:
order_by = page.order_by
result_dict_list = await RoleService.get_role_list_service(search=search, auth=auth, order_by=order_by)
result_dict = await PaginationService.paginate(data_list= result_dict_list, page_no= page.page_no, page_size = page.page_size)
log.info(f"查询角色成功")
return SuccessResponse(data=result_dict, msg="查询角色成功")
@RoleRouter.get("/detail/{id}", summary="查询角色详情", description="查询角色详情")
async def get_obj_detail_controller(
id: int = Path(..., description="角色ID"),
auth: AuthSchema = Depends(AuthPermission(["module_system:role:query"])),
) -> JSONResponse:
"""
查询角色详情
参数:
- id (int): 角色ID
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 角色详情JSON响应
"""
result_dict = await RoleService.get_role_detail_service(id=id, auth=auth)
log.info(f"获取角色详情成功 {id}")
return SuccessResponse(data=result_dict, msg="获取角色详情成功")
@RoleRouter.post("/create", summary="创建角色", description="创建角色")
async def create_obj_controller(
data: RoleCreateSchema,
auth: AuthSchema = Depends(AuthPermission(["module_system:role:create"])),
) -> JSONResponse:
"""
创建角色
参数:
- data (RoleCreateSchema): 创建角色模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 创建角色JSON响应
"""
result_dict = await RoleService.create_role_service(data=data, auth=auth)
log.info(f"创建角色成功: {result_dict}")
return SuccessResponse(data=result_dict, msg="创建角色成功")
@RoleRouter.put("/update/{id}", summary="修改角色", description="修改角色")
async def update_obj_controller(
data: RoleUpdateSchema,
id: int = Path(..., description="角色ID"),
auth: AuthSchema = Depends(AuthPermission(["module_system:role:update"])),
) -> JSONResponse:
"""
修改角色
参数:
- data (RoleUpdateSchema): 修改角色模型
- id (int): 角色ID
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 修改角色JSON响应
"""
result_dict = await RoleService.update_role_service(id=id, data=data, auth=auth)
log.info(f"修改角色成功: {result_dict}")
return SuccessResponse(data=result_dict, msg="修改角色成功")
@RoleRouter.delete("/delete", summary="删除角色", description="删除角色")
async def delete_obj_controller(
ids: list[int] = Body(..., description="ID列表"),
auth: AuthSchema = Depends(AuthPermission(["module_system:role:delete"])),
) -> JSONResponse:
"""
删除角色
参数:
- ids (list[int]): ID列表
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 删除角色JSON响应
"""
await RoleService.delete_role_service(ids=ids, auth=auth)
log.info(f"删除角色成功: {ids}")
return SuccessResponse(msg="删除角色成功")
@RoleRouter.patch("/available/setting", summary="批量修改角色状态", description="批量修改角色状态")
async def batch_set_available_obj_controller(
data: BatchSetAvailable,
auth: AuthSchema = Depends(AuthPermission(["module_system:role:patch"])),
) -> JSONResponse:
"""
批量修改角色状态
参数:
- data (BatchSetAvailable): 批量修改角色状态模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 批量修改角色状态JSON响应
"""
await RoleService.set_role_available_service(data=data, auth=auth)
log.info(f"批量修改角色状态成功: {data.ids}")
return SuccessResponse(msg="批量修改角色状态成功")
@RoleRouter.patch("/permission/setting", summary="角色授权", description="角色授权")
async def set_role_permission_controller(
data: RolePermissionSettingSchema,
auth: AuthSchema = Depends(AuthPermission(["module_system:role:permission"])),
) -> JSONResponse:
"""
角色授权
参数:
- data (RolePermissionSettingSchema): 角色授权模型
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 角色授权JSON响应
"""
await RoleService.set_role_permission_service(data=data, auth=auth)
log.info(f"设置角色权限成功: {data}")
return SuccessResponse(msg="授权角色成功")
@RoleRouter.post('/export', summary="导出角色", description="导出角色")
async def export_obj_list_controller(
search: RoleQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_system:role:export"])),
) -> StreamingResponse:
"""
导出角色
参数:
- search (RoleQueryParam): 查询参数模型
- auth (AuthSchema): 认证信息模型
返回:
- StreamingResponse: 导出角色流响应
"""
role_query_result = await RoleService.get_role_list_service(search=search, auth=auth)
role_export_result = await RoleService.export_role_list_service(role_list=role_query_result)
log.info('导出角色成功')
return StreamResponse(
data=bytes2file_response(role_export_result),
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers = {
'Content-Disposition': 'attachment; filename=role.xlsx'
}
)

View File

@@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-
from typing import Sequence
from app.core.base_crud import CRUDBase
from .model import RoleModel
from .schema import RoleCreateSchema, RoleUpdateSchema
from ..auth.schema import AuthSchema
from ..menu.crud import MenuCRUD
from ..dept.crud import DeptCRUD
class RoleCRUD(CRUDBase[RoleModel, RoleCreateSchema, RoleUpdateSchema]):
"""角色模块数据层"""
def __init__(self, auth: AuthSchema) -> None:
"""
初始化角色模块数据层
参数:
- auth (AuthSchema): 认证信息模型
"""
self.auth = auth
super().__init__(model=RoleModel, auth=auth)
async def get_by_id_crud(self, id: int, preload: list | None = None) -> RoleModel | None:
"""
根据id获取角色信息
参数:
- id (int): 角色ID
- preload (list | None): 预加载选项
返回:
- RoleModel | None: 角色模型对象
"""
return await self.get(id=id, preload=preload)
async def get_list_crud(self, search: dict | None = None, order_by: list | None = None, preload: list | None = None) -> Sequence[RoleModel]:
"""
获取角色列表
参数:
- search (dict | None): 查询参数
- order_by (list | None): 排序参数
- preload (list | None): 预加载选项
返回:
- Sequence[RoleModel]: 角色模型对象列表
"""
return await self.list(search=search, order_by=order_by, preload=preload)
async def set_role_menus_crud(self, role_ids: list[int], menu_ids: list[int]) -> None:
"""
设置角色的菜单权限
参数:
- role_ids (List[int]): 角色ID列表
- menu_ids (List[int]): 菜单ID列表
返回:
- None
"""
roles = await self.list(search={"id": ("in", role_ids)})
menus = await MenuCRUD(self.auth).get_list_crud(search={"id": ("in", menu_ids)})
for obj in roles:
relationship = obj.menus
relationship.clear()
relationship.extend(menus)
await self.auth.db.flush()
async def set_role_data_scope_crud(self, role_ids: list[int], data_scope: int) -> None:
"""
设置角色的数据范围
参数:
- role_ids (list[int]): 角色ID列表
- data_scope (int): 数据范围
返回:
- None
"""
await self.set(ids=role_ids, data_scope=data_scope)
async def set_role_depts_crud(self, role_ids: list[int], dept_ids: list[int]) -> None:
"""
设置角色的部门权限
参数:
- role_ids (list[int]): 角色ID列表
- dept_ids (list[int]): 部门ID列表
返回:
- None
"""
roles = await self.list(search={"id": ("in", role_ids)})
depts = await DeptCRUD(self.auth).get_list_crud(search={"id": ("in", dept_ids)})
for obj in roles:
relationship = obj.depts
relationship.clear()
relationship.extend(depts)
await self.auth.db.flush()
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)

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING
from sqlalchemy import String, Integer, ForeignKey
from sqlalchemy.orm import relationship, Mapped, mapped_column
from app.core.base_model import MappedBase, ModelMixin, UserMixin
if TYPE_CHECKING:
from app.api.v1.module_system.menu.model import MenuModel
from app.api.v1.module_system.dept.model import DeptModel
from app.api.v1.module_system.user.model import UserModel
class RoleMenusModel(MappedBase):
"""
角色菜单关联表
定义角色与菜单的多对多关系,用于权限控制
"""
__tablename__: str = "sys_role_menus"
__table_args__: dict[str, str] = ({'comment': '角色菜单关联表'})
role_id: Mapped[int] = mapped_column(
Integer,
ForeignKey("sys_role.id", ondelete="CASCADE", onupdate="CASCADE"),
primary_key=True,
comment="角色ID"
)
menu_id: Mapped[int] = mapped_column(
Integer,
ForeignKey("sys_menu.id", ondelete="CASCADE", onupdate="CASCADE"),
primary_key=True,
comment="菜单ID"
)
class RoleDeptsModel(MappedBase):
"""
角色部门关联表
定义角色与部门的多对多关系,用于数据权限控制
仅当角色的data_scope=5(自定义数据权限)时使用此表
"""
__tablename__: str = "sys_role_depts"
__table_args__: dict[str, str] = ({'comment': '角色部门关联表'})
role_id: Mapped[int] = mapped_column(
Integer,
ForeignKey("sys_role.id", ondelete="CASCADE", onupdate="CASCADE"),
primary_key=True,
comment="角色ID"
)
dept_id: Mapped[int] = mapped_column(
Integer,
ForeignKey("sys_dept.id", ondelete="CASCADE", onupdate="CASCADE"),
primary_key=True,
comment="部门ID"
)
class RoleModel(ModelMixin):
"""
角色模型
"""
__tablename__: str = "sys_role"
__table_args__: dict[str, str] = ({'comment': '角色表'})
__loader_options__: list[str] = ["menus", "depts"]
name: Mapped[str] = mapped_column(String(40), nullable=False, comment="角色名称")
code: Mapped[str | None] = mapped_column(String(20), nullable=True, index=True, comment="角色编码")
order: Mapped[int] = mapped_column(Integer, nullable=False, default=999, comment="显示排序")
data_scope: Mapped[int] = mapped_column(Integer, default=1, nullable=False, comment="数据权限范围(1:仅本人 2:本部门 3:本部门及以下 4:全部 5:自定义)")
# 关联关系 (继承自UserMixin)
menus: Mapped[list["MenuModel"]] = relationship(
secondary="sys_role_menus",
back_populates="roles",
lazy="selectin",
order_by="MenuModel.order"
)
depts: Mapped[list["DeptModel"]] = relationship(
secondary="sys_role_depts",
back_populates="roles",
lazy="selectin"
)
users: Mapped[list["UserModel"]] = relationship(
secondary="sys_user_roles",
back_populates="roles",
lazy="selectin"
)

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
from fastapi import Query
from pydantic import BaseModel, ConfigDict, Field, model_validator, field_validator
from app.core.validator import DateTimeStr
from app.core.base_schema import BaseSchema
from app.core.validator import role_permission_request_validator
from ..dept.schema import DeptOutSchema
from ..menu.schema import MenuOutSchema
class RoleCreateSchema(BaseModel):
"""角色创建模型"""
name: str = Field(..., max_length=40, description="角色名称")
code: str | None = Field(default=None, max_length=40, description="角色编码")
order: int | None = Field(default=1, ge=1, description='显示排序')
data_scope: int | None = Field(default=1, description='数据权限范围(1:仅本人 2:本部门 3:本部门及以下 4:全部 5:自定义)')
status: str = Field(default="0", description="是否启用")
description: str | None = Field(default=None, max_length=255, description="描述")
@field_validator("code")
@classmethod
def validate_code(cls, value: str | None):
if value is None:
return value
import re
v = value.strip()
if not re.match(r"^[A-Za-z][A-Za-z0-9_]{1,39}$", v):
raise ValueError("角色编码需字母开头,允许字母/数字/下划线长度2-40")
return v
class RolePermissionSettingSchema(BaseModel):
"""角色权限配置模型"""
data_scope: int = Field(default=1, description='数据权限范围(1:仅本人 2:本部门 3:本部门及以下 4:全部 5:自定义)')
role_ids: list[int] = Field(default_factory=list, description='角色ID列表')
menu_ids: list[int] = Field(default_factory=list, description='菜单ID列表')
dept_ids: list[int] = Field(default_factory=list, description='部门ID列表')
@model_validator(mode='after')
def validate_fields(self):
"""验证权限配置字段"""
return role_permission_request_validator(self)
class RoleUpdateSchema(RoleCreateSchema):
"""角色更新模型"""
...
class RoleOutSchema(RoleCreateSchema, BaseSchema):
"""角色信息响应模型"""
model_config = ConfigDict(from_attributes=True)
menus: list[MenuOutSchema] = Field(default_factory=list, description='角色菜单列表')
depts: list[DeptOutSchema] = Field(default_factory=list, description='角色部门列表')
class RoleQueryParam:
"""角色管理查询参数"""
def __init__(
self,
name: 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"]),
) -> None:
# 模糊查询字段
self.name = ("like", name)
# 精确查询字段
self.status = status
# 时间范围查询
if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1]))

View File

@@ -0,0 +1,196 @@
# -*- coding: utf-8 -*-
from typing import Any
from app.core.base_schema import BatchSetAvailable
from app.core.exceptions import CustomException
from app.utils.excel_util import ExcelUtil
from ..auth.schema import AuthSchema
from .crud import RoleCRUD
from .schema import (
RoleCreateSchema,
RoleUpdateSchema,
RolePermissionSettingSchema,
RoleOutSchema,
RoleQueryParam
)
class RoleService:
"""角色模块服务层"""
@classmethod
async def get_role_detail_service(cls, auth: AuthSchema, id: int) -> dict:
"""
获取角色详情
参数:
- auth (AuthSchema): 认证信息模型
- id (int): 角色ID
返回:
- dict: 角色详情字典
"""
role = await RoleCRUD(auth).get_by_id_crud(id=id)
return RoleOutSchema.model_validate(role).model_dump()
@classmethod
async def get_role_list_service(cls, auth: AuthSchema, search: RoleQueryParam | None = None, order_by: list[dict[str, str]] | None = None) -> list[dict]:
"""
获取角色列表
参数:
- auth (AuthSchema): 认证信息模型
- search (RoleQueryParam | None): 查询参数模型
- order_by (list[dict[str, str]] | None): 排序参数列表
返回:
- list[dict]: 角色详情字典列表
"""
role_list = await RoleCRUD(auth).get_list_crud(search=search.__dict__, order_by=order_by)
return [RoleOutSchema.model_validate(role).model_dump() for role in role_list]
@classmethod
async def create_role_service(cls, auth: AuthSchema, data: RoleCreateSchema) -> dict:
"""
创建角色
参数:
- auth (AuthSchema): 认证信息模型
- data (RoleCreateSchema): 创建角色模型
返回:
- dict: 新创建的角色详情字典
"""
role = await RoleCRUD(auth).get(name=data.name)
if role:
raise CustomException(msg='创建失败,该角色已存在')
obj = await RoleCRUD(auth).get(code=data.code)
if obj:
raise CustomException(msg='创建失败,编码已存在')
new_role = await RoleCRUD(auth).create(data=data)
return RoleOutSchema.model_validate(new_role).model_dump()
@classmethod
async def update_role_service(cls, auth: AuthSchema, id: int, data: RoleUpdateSchema) -> dict:
"""
更新角色
参数:
- auth (AuthSchema): 认证信息模型
- id (int): 角色ID
- data (RoleUpdateSchema): 更新角色模型
返回:
- dict: 更新后的角色详情字典
"""
role = await RoleCRUD(auth).get_by_id_crud(id=id)
if not role:
raise CustomException(msg='更新失败,该角色不存在')
exist_role = await RoleCRUD(auth).get(name=data.name)
if exist_role and exist_role.id != id:
raise CustomException(msg='更新失败,角色名称重复')
updated_role = await RoleCRUD(auth).update(id=id, data=data)
return RoleOutSchema.model_validate(updated_role).model_dump()
@classmethod
async def delete_role_service(cls, auth: AuthSchema, ids: list[int]) -> None:
"""
删除角色
参数:
- auth (AuthSchema): 认证信息模型
- ids (list[int]): 角色ID列表
返回:
- None
"""
if len(ids) < 1:
raise CustomException(msg='删除失败,删除对象不能为空')
for id in ids:
role = await RoleCRUD(auth).get_by_id_crud(id=id)
if not role:
raise CustomException(msg='删除失败,该角色不存在')
await RoleCRUD(auth).delete(ids=ids)
@classmethod
async def set_role_permission_service(cls, auth: AuthSchema, data: RolePermissionSettingSchema) -> None:
"""
设置角色权限
参数:
- auth (AuthSchema): 认证信息模型
- data (RolePermissionSettingSchema): 角色权限设置模型
返回:
- None
"""
# 设置角色菜单权限
await RoleCRUD(auth).set_role_menus_crud(role_ids=data.role_ids, menu_ids=data.menu_ids)
# 设置数据权限范围
await RoleCRUD(auth).set_role_data_scope_crud(role_ids=data.role_ids, data_scope=data.data_scope)
# 设置自定义数据权限部门
if data.data_scope == 5 and data.dept_ids:
await RoleCRUD(auth).set_role_depts_crud(role_ids=data.role_ids, dept_ids=data.dept_ids)
else:
await RoleCRUD(auth).set_role_depts_crud(role_ids=data.role_ids, dept_ids=[])
@classmethod
async def set_role_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
"""
设置角色可用状态
参数:
- auth (AuthSchema): 认证信息模型
- data (BatchSetAvailable): 批量设置可用状态模型
返回:
- None
"""
await RoleCRUD(auth).set_available_crud(ids=data.ids, status=data.status)
@classmethod
async def export_role_list_service(cls, role_list: list[dict[str, Any]]) -> bytes:
"""
导出角色列表
参数:
- role_list (list[dict[str, Any]]): 角色详情字典列表
返回:
- bytes: Excel文件字节流
"""
# 字段映射配置
mapping_dict = {
'id': '角色编号',
'name': '角色名称',
'order': '显示顺序',
'data_scope': '数据权限',
'status': '状态',
'description': '备注',
'created_time': '创建时间',
'updated_time': '更新时间',
'created_id': '创建者ID',
'updated_id': '更新者ID',
}
# 数据权限映射
data_scope_map = {
1: '仅本人数据权限',
2: '本部门数据权限',
3: '本部门及以下数据权限',
4: '全部数据权限',
5: '自定义数据权限'
}
# 处理数据
data = role_list.copy()
for item in data:
item['status'] = '启用' if item.get('status') == '0' else '停用'
item['data_scope'] = data_scope_map.get(item.get('data_scope', 1), '')
item['creator'] = item.get('creator', {}).get('name', '未知') if isinstance(item.get('creator'), dict) else '未知'
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)