mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-21 12:52:26 +00:00
style: 移除Python文件中的编码声明并优化代码格式
refactor: 重构前端组件和样式,添加AI助手功能 docs: 更新README文档,添加ruff代码检查说明 feat: 新增AI助手相关API和前端组件 chore: 更新.gitignore文件,添加ruff缓存配置 fix: 修复前端布局和设置相关的问题 perf: 优化代码结构和性能,移除冗余代码 test: 更新测试文件,移除编码声明 build: 更新依赖版本,调整requirements.txt
This commit is contained in:
@@ -1,2 +1 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
|
||||
@@ -1,66 +1,66 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import urllib.parse
|
||||
from fastapi import APIRouter, Depends, Body, Path, UploadFile, Request
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Path, Request, UploadFile
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.common.response import StreamResponse, SuccessResponse
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.common.request import PaginationService
|
||||
from app.core.router_class import OperationLogRoute
|
||||
from app.utils.common_util import bytes2file_response
|
||||
from app.core.dependencies import db_getter, get_current_user, AuthPermission
|
||||
from app.common.response import StreamResponse, SuccessResponse
|
||||
from app.core.base_params import PaginationQueryParam
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.dependencies import AuthPermission, db_getter, get_current_user
|
||||
from app.core.logger import log
|
||||
from app.core.router_class import OperationLogRoute
|
||||
from app.utils.common_util import bytes2file_response
|
||||
|
||||
from ..auth.schema import AuthSchema
|
||||
from .service import UserService
|
||||
from .schema import (
|
||||
CurrentUserUpdateSchema,
|
||||
ResetPasswordSchema,
|
||||
UserChangePasswordSchema,
|
||||
UserCreateSchema,
|
||||
UserForgetPasswordSchema,
|
||||
UserQueryParam,
|
||||
UserRegisterSchema,
|
||||
UserUpdateSchema,
|
||||
UserChangePasswordSchema,
|
||||
UserQueryParam
|
||||
)
|
||||
|
||||
from .service import UserService
|
||||
|
||||
UserRouter = APIRouter(route_class=OperationLogRoute, prefix="/user", tags=["用户管理"])
|
||||
|
||||
|
||||
@UserRouter.get("/current/info", summary="查询当前用户信息", description="查询当前用户信息")
|
||||
async def get_current_user_info_controller(
|
||||
auth: AuthSchema = Depends(get_current_user)
|
||||
auth: Annotated[AuthSchema, Depends(get_current_user)]
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
查询当前用户信息
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 当前用户信息JSON响应
|
||||
"""
|
||||
result_dict = await UserService.get_current_user_info_service(auth=auth)
|
||||
log.info(f"获取当前用户信息成功")
|
||||
log.info("获取当前用户信息成功")
|
||||
return SuccessResponse(data=result_dict, msg='获取当前用户信息成功')
|
||||
|
||||
|
||||
@UserRouter.post("/current/avatar/upload", summary="上传当前用户头像", dependencies=[Depends(get_current_user)])
|
||||
async def user_avatar_upload_controller(
|
||||
file: UploadFile,
|
||||
file: UploadFile,
|
||||
request: Request
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
上传当前用户头像
|
||||
|
||||
|
||||
参数:
|
||||
- file (UploadFile): 上传的文件
|
||||
- request (Request): 请求对象
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 上传头像JSON响应
|
||||
"""
|
||||
@@ -72,15 +72,15 @@ async def user_avatar_upload_controller(
|
||||
@UserRouter.put("/current/info/update", summary="更新当前用户基本信息", description="更新当前用户基本信息")
|
||||
async def update_current_user_info_controller(
|
||||
data: CurrentUserUpdateSchema,
|
||||
auth: AuthSchema = Depends(get_current_user)
|
||||
auth: Annotated[AuthSchema, Depends(get_current_user)]
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
更新当前用户基本信息
|
||||
|
||||
|
||||
参数:
|
||||
- data (CurrentUserUpdateSchema): 当前用户更新模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 更新当前用户基本信息JSON响应
|
||||
"""
|
||||
@@ -92,15 +92,15 @@ async def update_current_user_info_controller(
|
||||
@UserRouter.put("/current/password/change", summary="修改当前用户密码", description="修改当前用户密码")
|
||||
async def change_current_user_password_controller(
|
||||
data: UserChangePasswordSchema,
|
||||
auth: AuthSchema = Depends(get_current_user)
|
||||
auth: Annotated[AuthSchema, Depends(get_current_user)]
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
修改当前用户密码
|
||||
|
||||
|
||||
参数:
|
||||
- data (UserChangePasswordSchema): 用户密码修改模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 修改密码JSON响应
|
||||
"""
|
||||
@@ -108,18 +108,19 @@ async def change_current_user_password_controller(
|
||||
log.info(f"修改密码成功: {result_dict}")
|
||||
return SuccessResponse(data=result_dict, msg='修改密码成功, 请重新登录')
|
||||
|
||||
|
||||
@UserRouter.put("/reset/password", summary="重置密码", description="重置密码")
|
||||
async def reset_password_controller(
|
||||
data: ResetPasswordSchema,
|
||||
auth: AuthSchema = Depends(get_current_user)
|
||||
auth: Annotated[AuthSchema, Depends(get_current_user)]
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
重置密码
|
||||
|
||||
|
||||
参数:
|
||||
- data (ResetPasswordSchema): 重置密码模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 重置密码JSON响应
|
||||
"""
|
||||
@@ -127,18 +128,19 @@ async def reset_password_controller(
|
||||
log.info(f"重置密码成功: {result_dict}")
|
||||
return SuccessResponse(data=result_dict, msg='重置密码成功')
|
||||
|
||||
|
||||
@UserRouter.post('/register', summary="注册用户", description="注册用户")
|
||||
async def register_user_controller(
|
||||
data: UserRegisterSchema,
|
||||
db: AsyncSession = Depends(db_getter),
|
||||
data: UserRegisterSchema,
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
注册用户
|
||||
|
||||
|
||||
参数:
|
||||
- data (UserRegisterSchema): 用户注册模型
|
||||
- db (AsyncSession): 异步数据库会话
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 注册用户JSON响应
|
||||
"""
|
||||
@@ -150,16 +152,16 @@ async def register_user_controller(
|
||||
|
||||
@UserRouter.post('/forget/password', summary="忘记密码", description="忘记密码")
|
||||
async def forget_password_controller(
|
||||
data: UserForgetPasswordSchema,
|
||||
db: AsyncSession = Depends(db_getter),
|
||||
data: UserForgetPasswordSchema,
|
||||
db: Annotated[AsyncSession, Depends(db_getter)],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
忘记密码
|
||||
|
||||
|
||||
参数:
|
||||
- data (UserForgetPasswordSchema): 用户忘记密码模型
|
||||
- db (AsyncSession): 异步数据库会话
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 忘记密码JSON响应
|
||||
"""
|
||||
@@ -171,39 +173,39 @@ async def forget_password_controller(
|
||||
|
||||
@UserRouter.get("/list", summary="查询用户", description="查询用户")
|
||||
async def get_obj_list_controller(
|
||||
page: PaginationQueryParam = Depends(),
|
||||
search: UserQueryParam = Depends(),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_system:user:query"])),
|
||||
page: Annotated[PaginationQueryParam, Depends()],
|
||||
search: Annotated[UserQueryParam, Depends()],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:user:query"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
查询用户
|
||||
|
||||
|
||||
参数:
|
||||
- page (PaginationQueryParam): 分页查询参数模型
|
||||
- search (UserQueryParam): 查询参数模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 分页查询结果JSON响应
|
||||
"""
|
||||
result_dict_list = await UserService.get_user_list_service(search=search, auth=auth, order_by=page.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"查询用户成功")
|
||||
result_dict = await PaginationService.paginate(data_list=result_dict_list, page_no=page.page_no, page_size=page.page_size)
|
||||
log.info("查询用户成功")
|
||||
return SuccessResponse(data=result_dict, msg="查询用户成功")
|
||||
|
||||
|
||||
@UserRouter.get("/detail/{id}", summary="查询用户详情", description="查询用户详情")
|
||||
async def get_obj_detail_controller(
|
||||
id: int = Path(..., description="用户ID"),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_system:user:detail"])),
|
||||
id: Annotated[int, Path(description="用户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:user:detail"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
查询用户详情
|
||||
|
||||
|
||||
参数:
|
||||
- id (int): 用户ID
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 用户详情JSON响应
|
||||
"""
|
||||
@@ -215,19 +217,19 @@ async def get_obj_detail_controller(
|
||||
@UserRouter.post("/create", summary="创建用户", description="创建用户")
|
||||
async def create_obj_controller(
|
||||
data: UserCreateSchema,
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_system:user:create"])),
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:user:create"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
创建用户
|
||||
|
||||
|
||||
**注意**:
|
||||
- 创建用户时, 默认密码为: <PASSWORD>
|
||||
- 创建用户时, 默认用户状态为: 启用
|
||||
|
||||
|
||||
参数:
|
||||
- data (UserCreateSchema): 用户创建模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 创建用户JSON响应
|
||||
"""
|
||||
@@ -239,17 +241,17 @@ async def create_obj_controller(
|
||||
@UserRouter.put("/update/{id}", summary="修改用户", description="修改用户")
|
||||
async def update_obj_controller(
|
||||
data: UserUpdateSchema,
|
||||
id: int = Path(..., description="用户ID"),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_system:user:update"])),
|
||||
id: Annotated[int, Path(description="用户ID")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:user:update"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
修改用户
|
||||
|
||||
|
||||
参数:
|
||||
- data (UserUpdateSchema): 用户修改模型
|
||||
- id (int): 用户ID
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 修改用户JSON响应
|
||||
"""
|
||||
@@ -260,16 +262,16 @@ async def update_obj_controller(
|
||||
|
||||
@UserRouter.delete("/delete", summary="删除用户", description="删除用户")
|
||||
async def delete_obj_controller(
|
||||
ids: list[int] = Body(..., description="ID列表"),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_system:user:delete"])),
|
||||
ids: Annotated[list[int], Body(description="ID列表")],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:user:delete"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
删除用户
|
||||
|
||||
|
||||
参数:
|
||||
- ids (list[int]): 用户ID列表
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 删除用户JSON响应
|
||||
"""
|
||||
@@ -281,15 +283,15 @@ async def delete_obj_controller(
|
||||
@UserRouter.patch("/available/setting", summary="批量修改用户状态", description="批量修改用户状态")
|
||||
async def batch_set_available_obj_controller(
|
||||
data: BatchSetAvailable,
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_system:user:patch"])),
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:user:patch"]))],
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
批量修改用户状态
|
||||
|
||||
|
||||
参数:
|
||||
- data (BatchSetAvailable): 批量修改用户状态模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 批量修改用户状态JSON响应
|
||||
"""
|
||||
@@ -299,10 +301,10 @@ async def batch_set_available_obj_controller(
|
||||
|
||||
|
||||
@UserRouter.post('/import/template', summary="获取用户导入模板", description="获取用户导入模板", dependencies=[Depends(AuthPermission(["module_system:user:download"]))])
|
||||
async def export_obj_template_controller()-> StreamingResponse:
|
||||
async def export_obj_template_controller() -> StreamingResponse:
|
||||
"""
|
||||
获取用户导入模板
|
||||
|
||||
|
||||
返回:
|
||||
- StreamingResponse: 用户导入模板流响应
|
||||
"""
|
||||
@@ -312,7 +314,7 @@ async def export_obj_template_controller()-> StreamingResponse:
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(user_import_template_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
headers={
|
||||
'Content-Disposition': f'attachment; filename={urllib.parse.quote("用户导入模板.xlsx")}',
|
||||
'Access-Control-Expose-Headers': 'Content-Disposition'
|
||||
}
|
||||
@@ -321,18 +323,18 @@ async def export_obj_template_controller()-> StreamingResponse:
|
||||
|
||||
@UserRouter.post('/export', summary="导出用户", description="导出用户")
|
||||
async def export_obj_list_controller(
|
||||
page: PaginationQueryParam = Depends(),
|
||||
search: UserQueryParam = Depends(),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_system:user:export"])),
|
||||
page: Annotated[PaginationQueryParam, Depends()],
|
||||
search: Annotated[UserQueryParam, Depends()],
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:user:export"]))],
|
||||
) -> StreamingResponse:
|
||||
"""
|
||||
导出用户
|
||||
|
||||
|
||||
参数:
|
||||
- page (PaginationQueryParam): 分页查询参数模型
|
||||
- search (UserQueryParam): 查询参数模型
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- StreamingResponse: 用户导出模板流响应
|
||||
"""
|
||||
@@ -343,7 +345,7 @@ async def export_obj_list_controller(
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(user_export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers = {
|
||||
headers={
|
||||
'Content-Disposition': 'attachment; filename=user.xlsx'
|
||||
}
|
||||
)
|
||||
@@ -352,15 +354,15 @@ async def export_obj_list_controller(
|
||||
@UserRouter.post('/import/data', summary="导入用户", description="导入用户")
|
||||
async def import_obj_list_controller(
|
||||
file: UploadFile,
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_system:user:import"]))
|
||||
auth: Annotated[AuthSchema, Depends(AuthPermission(["module_system:user:import"]))]
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
导入用户
|
||||
|
||||
|
||||
参数:
|
||||
- file (UploadFile): 用户导入文件
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- JSONResponse: 导入用户JSON响应
|
||||
"""
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Sequence, Any
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.base_crud import CRUDBase
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.api.v1.module_system.position.crud import PositionCRUD
|
||||
from app.api.v1.module_system.role.crud import RoleCRUD
|
||||
from app.core.base_crud import CRUDBase
|
||||
|
||||
from .model import UserModel
|
||||
from .schema import UserCreateSchema, UserForgetPasswordSchema, UserUpdateSchema
|
||||
from ..role.crud import RoleCRUD
|
||||
from ..position.crud import PositionCRUD
|
||||
|
||||
|
||||
class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
@@ -17,7 +17,7 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
def __init__(self, auth: AuthSchema) -> None:
|
||||
"""
|
||||
初始化用户CRUD
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
"""
|
||||
@@ -27,11 +27,11 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def get_by_id_crud(self, id: int, preload: list[str | Any] | None = None) -> UserModel | None:
|
||||
"""
|
||||
根据id获取用户信息
|
||||
|
||||
|
||||
参数:
|
||||
- id (int): 用户ID
|
||||
- preload (list[str | Any] | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
|
||||
返回:
|
||||
- UserModel | None: 用户信息,如果不存在则为None
|
||||
"""
|
||||
@@ -43,11 +43,11 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def get_by_username_crud(self, username: str, preload: list[str | Any] | None = None) -> UserModel | None:
|
||||
"""
|
||||
根据用户名获取用户信息
|
||||
|
||||
|
||||
参数:
|
||||
- username (str): 用户名
|
||||
- preload (list[str | Any] | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
|
||||
返回:
|
||||
- UserModel | None: 用户信息,如果不存在则为None
|
||||
"""
|
||||
@@ -55,15 +55,15 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
preload=preload,
|
||||
username=username,
|
||||
)
|
||||
|
||||
|
||||
async def get_by_mobile_crud(self, mobile: str, preload: list[str | Any] | None = None) -> UserModel | None:
|
||||
"""
|
||||
根据手机号获取用户信息
|
||||
|
||||
|
||||
参数:
|
||||
- mobile (str): 手机号
|
||||
- preload (list[str | Any] | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
|
||||
返回:
|
||||
- UserModel | None: 用户信息,如果不存在则为None
|
||||
"""
|
||||
@@ -75,12 +75,12 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def get_list_crud(self, search: dict | None = None, order_by: list[dict[str, str]] | None = None, preload: list[str | Any] | None = None) -> Sequence[UserModel]:
|
||||
"""
|
||||
获取用户列表
|
||||
|
||||
|
||||
参数:
|
||||
- search (dict | None): 查询参数对象。
|
||||
- order_by (list[dict[str, str]] | None): 排序参数列表。
|
||||
- preload (list[str | Any] | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
|
||||
返回:
|
||||
- Sequence[UserModel]: 用户列表
|
||||
"""
|
||||
@@ -93,10 +93,10 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def update_last_login_crud(self, id: int) -> UserModel | None:
|
||||
"""
|
||||
更新用户最后登录时间
|
||||
|
||||
|
||||
参数:
|
||||
- id (int): 用户ID
|
||||
|
||||
|
||||
返回:
|
||||
- UserModel | None: 更新后的用户信息
|
||||
"""
|
||||
@@ -105,11 +105,11 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def set_available_crud(self, ids: list[int], status: str) -> None:
|
||||
"""
|
||||
批量设置用户可用状态
|
||||
|
||||
|
||||
参数:
|
||||
- ids (list[int]): 用户ID列表
|
||||
- status (bool): 可用状态
|
||||
|
||||
|
||||
返回:
|
||||
- None:
|
||||
"""
|
||||
@@ -118,11 +118,11 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def set_user_roles_crud(self, user_ids: list[int], role_ids: list[int]) -> None:
|
||||
"""
|
||||
批量设置用户角色
|
||||
|
||||
|
||||
参数:
|
||||
- user_ids (list[int]): 用户ID列表
|
||||
- role_ids (list[int]): 角色ID列表
|
||||
|
||||
|
||||
返回:
|
||||
- None:
|
||||
"""
|
||||
@@ -131,7 +131,7 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
role_objs = await RoleCRUD(self.auth).get_list_crud(search={"id": ("in", role_ids)})
|
||||
else:
|
||||
role_objs = []
|
||||
|
||||
|
||||
for obj in user_objs:
|
||||
relationship = obj.roles
|
||||
relationship.clear()
|
||||
@@ -141,11 +141,11 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def set_user_positions_crud(self, user_ids: list[int], position_ids: list[int]) -> None:
|
||||
"""
|
||||
批量设置用户岗位
|
||||
|
||||
|
||||
参数:
|
||||
- user_ids (list[int]): 用户ID列表
|
||||
- position_ids (list[int]): 岗位ID列表
|
||||
|
||||
|
||||
返回:
|
||||
- None:
|
||||
"""
|
||||
@@ -164,11 +164,11 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def change_password_crud(self, id: int, password_hash: str) -> UserModel:
|
||||
"""
|
||||
修改用户密码
|
||||
|
||||
|
||||
参数:
|
||||
- id (int): 用户ID
|
||||
- password_hash (str): 密码哈希值
|
||||
|
||||
|
||||
返回:
|
||||
- UserModel: 更新后的用户信息
|
||||
"""
|
||||
@@ -177,11 +177,11 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def forget_password_crud(self, id: int, password_hash: str) -> UserModel:
|
||||
"""
|
||||
重置密码
|
||||
|
||||
|
||||
参数:
|
||||
- id (int): 用户ID
|
||||
- password_hash (str): 密码哈希值
|
||||
|
||||
|
||||
返回:
|
||||
- UserModel: 更新后的用户信息
|
||||
"""
|
||||
@@ -190,11 +190,11 @@ class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]):
|
||||
async def register_user_crud(self, data: UserForgetPasswordSchema) -> UserModel:
|
||||
"""
|
||||
用户注册
|
||||
|
||||
|
||||
参数:
|
||||
- data (UserForgetPasswordSchema): 用户注册信息
|
||||
|
||||
|
||||
返回:
|
||||
- UserModel: 注册成功的用户信息
|
||||
"""
|
||||
return await self.create(data=UserCreateSchema(**data.model_dump()))
|
||||
return await self.create(data=UserCreateSchema(**data.model_dump()))
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Boolean, String, Integer, DateTime, ForeignKey
|
||||
from sqlalchemy.orm import relationship, Mapped, mapped_column
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.core.base_model import MappedBase, ModelMixin, UserMixin
|
||||
|
||||
@@ -16,7 +15,7 @@ if TYPE_CHECKING:
|
||||
class UserRolesModel(MappedBase):
|
||||
"""
|
||||
用户角色关联表
|
||||
|
||||
|
||||
定义用户与角色的多对多关系
|
||||
"""
|
||||
__tablename__: str = "sys_user_roles"
|
||||
@@ -39,7 +38,7 @@ class UserRolesModel(MappedBase):
|
||||
class UserPositionsModel(MappedBase):
|
||||
"""
|
||||
用户岗位关联表
|
||||
|
||||
|
||||
定义用户与岗位的多对多关系
|
||||
"""
|
||||
__tablename__: str = "sys_user_positions"
|
||||
@@ -76,35 +75,35 @@ class UserModel(ModelMixin, UserMixin):
|
||||
avatar: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="头像URL地址")
|
||||
is_superuser: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, comment="是否超管")
|
||||
last_login: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, comment="最后登录时间")
|
||||
|
||||
|
||||
gitee_login: Mapped[str | None] = mapped_column(String(32), nullable=True, comment="Gitee登录")
|
||||
github_login: Mapped[str | None] = mapped_column(String(32), nullable=True, comment="Github登录")
|
||||
wx_login: Mapped[str | None] = mapped_column(String(32), nullable=True, comment="微信登录")
|
||||
qq_login: Mapped[str | None] = mapped_column(String(32), nullable=True, comment="QQ登录")
|
||||
|
||||
|
||||
dept_id: Mapped[int | None] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey('sys_dept.id', ondelete="SET NULL", onupdate="CASCADE"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
Integer,
|
||||
ForeignKey('sys_dept.id', ondelete="SET NULL", onupdate="CASCADE"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
comment="部门ID"
|
||||
)
|
||||
dept: Mapped["DeptModel | None"] = relationship(
|
||||
back_populates="users",
|
||||
foreign_keys=[dept_id],
|
||||
back_populates="users",
|
||||
foreign_keys=[dept_id],
|
||||
lazy="selectin"
|
||||
)
|
||||
roles: Mapped[list["RoleModel"]] = relationship(
|
||||
secondary="sys_user_roles",
|
||||
back_populates="users",
|
||||
secondary="sys_user_roles",
|
||||
back_populates="users",
|
||||
lazy="selectin"
|
||||
)
|
||||
positions: Mapped[list["PositionModel"]] = relationship(
|
||||
secondary="sys_user_positions",
|
||||
back_populates="users",
|
||||
secondary="sys_user_positions",
|
||||
back_populates="users",
|
||||
lazy="selectin"
|
||||
)
|
||||
|
||||
|
||||
# 覆盖 UserMixin 的关系定义,显式指定 foreign_keys 避免自引用混淆
|
||||
created_by: Mapped["UserModel | None"] = relationship(
|
||||
"UserModel",
|
||||
@@ -114,7 +113,7 @@ class UserModel(ModelMixin, UserMixin):
|
||||
uselist=False,
|
||||
viewonly=True # 防止级联操作
|
||||
)
|
||||
|
||||
|
||||
updated_by: Mapped["UserModel | None"] = relationship(
|
||||
"UserModel",
|
||||
foreign_keys="UserModel.updated_id",
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from fastapi import Query
|
||||
from pydantic import BaseModel, ConfigDict, Field, EmailStr, field_validator, model_validator
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from app.core.validator import DateTimeStr, email_validator, mobile_validator
|
||||
from app.core.base_schema import BaseSchema, CommonSchema, UserBySchema
|
||||
from app.core.validator import DateTimeStr
|
||||
from fastapi import Query
|
||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator, model_validator
|
||||
|
||||
from app.api.v1.module_system.menu.schema import MenuOutSchema
|
||||
from app.api.v1.module_system.role.schema import RoleOutSchema
|
||||
from app.core.base_schema import BaseSchema, CommonSchema, UserBySchema
|
||||
from app.core.validator import DateTimeStr, email_validator, mobile_validator
|
||||
|
||||
|
||||
class CurrentUserUpdateSchema(BaseModel):
|
||||
@@ -23,7 +21,7 @@ class CurrentUserUpdateSchema(BaseModel):
|
||||
@classmethod
|
||||
def validate_mobile(cls, value: str | None):
|
||||
return mobile_validator(value)
|
||||
|
||||
|
||||
@field_validator("email")
|
||||
@classmethod
|
||||
def validate_email(cls, value: str | None):
|
||||
@@ -40,7 +38,7 @@ class CurrentUserUpdateSchema(BaseModel):
|
||||
if parsed.scheme in ("http", "https") and parsed.netloc:
|
||||
return value
|
||||
raise ValueError("头像地址需为有效的HTTP/HTTPS URL")
|
||||
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_model(self):
|
||||
if self.name and len(self.name) > 32:
|
||||
@@ -57,12 +55,12 @@ class UserRegisterSchema(BaseModel):
|
||||
role_ids: list[int] | None = Field(default=[1], description='角色ID')
|
||||
created_id: int | None = Field(default=1, description='创建人ID')
|
||||
description: str | None = Field(default=None, max_length=255, description="备注")
|
||||
|
||||
|
||||
@field_validator("mobile")
|
||||
@classmethod
|
||||
def validate_mobile(cls, value: str | None):
|
||||
return mobile_validator(value)
|
||||
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def validate_username(cls, value: str):
|
||||
@@ -74,7 +72,7 @@ class UserRegisterSchema(BaseModel):
|
||||
if not re.match(r"^[A-Za-z][A-Za-z0-9_.-]{2,31}$", v):
|
||||
raise ValueError("账号需字母开头,3-32位,仅含字母/数字/_ . -")
|
||||
return v
|
||||
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_model(self):
|
||||
if self.name and len(self.name) > 32:
|
||||
@@ -93,7 +91,7 @@ class UserForgetPasswordSchema(BaseModel):
|
||||
username: str = Field(..., max_length=32, description="用户名")
|
||||
new_password: str = Field(..., max_length=128, description="新密码")
|
||||
mobile: str | None = Field(default=None, description="手机号")
|
||||
|
||||
|
||||
@field_validator("mobile")
|
||||
@classmethod
|
||||
def validate_mobile(cls, value: str | None):
|
||||
@@ -115,7 +113,7 @@ class ResetPasswordSchema(BaseModel):
|
||||
class UserCreateSchema(CurrentUserUpdateSchema):
|
||||
"""新增"""
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
username: str | None = Field(default=None, max_length=32, description="用户名")
|
||||
password: str | None = Field(default=None, max_length=128, description="密码哈希值")
|
||||
status: str = Field(default="0", description="是否可用")
|
||||
@@ -125,6 +123,7 @@ class UserCreateSchema(CurrentUserUpdateSchema):
|
||||
role_ids: list[int] | None = Field(default=[], description='角色ID')
|
||||
position_ids: list[int] | None = Field(default=[], description='岗位ID')
|
||||
|
||||
|
||||
class UserUpdateSchema(UserCreateSchema):
|
||||
"""更新"""
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
@@ -145,6 +144,7 @@ class UserOutSchema(UserUpdateSchema, BaseSchema, UserBySchema):
|
||||
roles: list[RoleOutSchema] | None = Field(default=[], description='角色')
|
||||
menus: list[MenuOutSchema] | None = Field(default=[], description='菜单')
|
||||
|
||||
|
||||
class UserQueryParam:
|
||||
"""用户管理查询参数"""
|
||||
|
||||
@@ -153,7 +153,7 @@ class UserQueryParam:
|
||||
username: str | None = Query(None, description="用户名"),
|
||||
name: str | None = Query(None, description="名称"),
|
||||
mobile: str | None = Query(None, description="手机号", pattern=r'^1[3-9]\d{9}$'),
|
||||
email: str | None = Query(None, description="邮箱", pattern=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
|
||||
email: str | None = Query(None, description="邮箱", pattern=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'),
|
||||
dept_id: int | None = Query(None, description="部门ID"),
|
||||
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"]),
|
||||
@@ -161,7 +161,7 @@ class UserQueryParam:
|
||||
created_id: int | None = Query(None, description="创建人"),
|
||||
updated_id: int | None = Query(None, description="更新人"),
|
||||
) -> None:
|
||||
|
||||
|
||||
# 模糊查询字段
|
||||
self.username = ("like", username)
|
||||
self.name = ("like", name)
|
||||
@@ -173,10 +173,9 @@ class UserQueryParam:
|
||||
self.created_id = created_id
|
||||
self.updated_id = updated_id
|
||||
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]))
|
||||
|
||||
@@ -1,35 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import io
|
||||
|
||||
from typing import Any
|
||||
from fastapi import UploadFile
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from app.core.exceptions import CustomException
|
||||
from app.utils.hash_bcrpy_util import PwdUtil
|
||||
from fastapi import UploadFile
|
||||
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.api.v1.module_system.dept.crud import DeptCRUD
|
||||
from app.api.v1.module_system.menu.crud import MenuCRUD
|
||||
from app.api.v1.module_system.menu.schema import MenuOutSchema
|
||||
from app.api.v1.module_system.position.crud import PositionCRUD
|
||||
from app.api.v1.module_system.role.crud import RoleCRUD
|
||||
from app.core.base_schema import BatchSetAvailable, UploadResponseSchema
|
||||
from app.core.exceptions import CustomException
|
||||
from app.core.logger import log
|
||||
from app.utils.common_util import traversal_to_tree
|
||||
from app.utils.excel_util import ExcelUtil
|
||||
from app.utils.hash_bcrpy_util import PwdUtil
|
||||
from app.utils.upload_util import UploadUtil
|
||||
|
||||
from ..position.crud import PositionCRUD
|
||||
from ..role.crud import RoleCRUD
|
||||
from ..menu.crud import MenuCRUD
|
||||
from ..dept.crud import DeptCRUD
|
||||
from ..auth.schema import AuthSchema
|
||||
from ..menu.schema import MenuOutSchema
|
||||
from .crud import UserCRUD
|
||||
from .schema import (
|
||||
CurrentUserUpdateSchema,
|
||||
ResetPasswordSchema,
|
||||
UserOutSchema,
|
||||
UserCreateSchema,
|
||||
UserUpdateSchema,
|
||||
UserChangePasswordSchema,
|
||||
UserRegisterSchema,
|
||||
UserCreateSchema,
|
||||
UserForgetPasswordSchema,
|
||||
UserQueryParam
|
||||
UserOutSchema,
|
||||
UserQueryParam,
|
||||
UserRegisterSchema,
|
||||
UserUpdateSchema,
|
||||
)
|
||||
|
||||
|
||||
@@ -40,37 +41,37 @@ class UserService:
|
||||
async def get_detail_by_id_service(cls, auth: AuthSchema, id: int) -> dict:
|
||||
"""
|
||||
根据ID获取用户详情
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- id (int): 用户ID
|
||||
|
||||
|
||||
返回:
|
||||
- dict: 用户详情字典
|
||||
"""
|
||||
user = await UserCRUD(auth).get_by_id_crud(id=id)
|
||||
if not user:
|
||||
raise CustomException(msg="用户不存在")
|
||||
|
||||
|
||||
# 如果用户绑定了部门,则获取部门名称
|
||||
if user.dept_id:
|
||||
dept = await DeptCRUD(auth).get_by_id_crud(id=user.dept_id)
|
||||
UserOutSchema.dept_name = dept.name if dept else None
|
||||
else:
|
||||
UserOutSchema.dept_name = None
|
||||
|
||||
|
||||
return UserOutSchema.model_validate(user).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def get_user_list_service(cls, auth: AuthSchema, search: UserQueryParam | None = None, order_by: list[dict[str, str]] | None = None) -> list[dict]:
|
||||
"""
|
||||
获取用户列表
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- search (UserQueryParam | None): 查询参数对象。
|
||||
- order_by (list[dict[str, str]] | None): 排序参数列表。
|
||||
|
||||
|
||||
返回:
|
||||
- list[dict]: 用户详情字典列表
|
||||
"""
|
||||
@@ -86,11 +87,11 @@ class UserService:
|
||||
async def create_user_service(cls, data: UserCreateSchema, auth: AuthSchema) -> dict:
|
||||
"""
|
||||
创建用户
|
||||
|
||||
|
||||
参数:
|
||||
- data (UserCreateSchema): 用户创建信息
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- dict: 创建后的用户详情字典
|
||||
"""
|
||||
@@ -129,18 +130,18 @@ class UserService:
|
||||
async def update_user_service(cls, id: int, data: UserUpdateSchema, auth: AuthSchema) -> dict:
|
||||
"""
|
||||
更新用户
|
||||
|
||||
|
||||
参数:
|
||||
- id (int): 用户ID
|
||||
- data (UserUpdateSchema): 用户更新信息
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- Dict: 更新后的用户详情字典
|
||||
"""
|
||||
if not data.username:
|
||||
raise CustomException(msg="账号不能为空")
|
||||
|
||||
|
||||
# 检查用户是否存在
|
||||
user = await UserCRUD(auth).get_by_id_crud(id=id)
|
||||
if not user:
|
||||
@@ -171,7 +172,7 @@ class UserService:
|
||||
raise CustomException(msg='部门不存在')
|
||||
if dept.status == "1":
|
||||
raise CustomException(msg='部门已被禁用')
|
||||
|
||||
|
||||
# 更新用户 - 排除不应被修改的字段, 更新不更新密码
|
||||
user_dict = data.model_dump(exclude_unset=True, exclude={"role_ids", "position_ids", "last_login", "password"})
|
||||
new_user = await UserCRUD(auth).update(id=id, data=user_dict)
|
||||
@@ -202,11 +203,11 @@ class UserService:
|
||||
async def delete_user_service(cls, auth: AuthSchema, ids: list[int]) -> None:
|
||||
"""
|
||||
删除用户
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- ids (list[int]): 用户ID列表
|
||||
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
@@ -224,10 +225,10 @@ class UserService:
|
||||
raise CustomException(msg="不能删除当前登陆用户")
|
||||
# 删除用户角色关联数据
|
||||
await UserCRUD(auth).set_user_roles_crud(user_ids=ids, role_ids=[])
|
||||
|
||||
|
||||
# 删除用户岗位关联数据
|
||||
await UserCRUD(auth).set_user_positions_crud(user_ids=ids, position_ids=[])
|
||||
|
||||
|
||||
# 删除用户
|
||||
await UserCRUD(auth).delete(ids=ids)
|
||||
|
||||
@@ -235,10 +236,10 @@ class UserService:
|
||||
async def get_current_user_info_service(cls, auth: AuthSchema) -> dict:
|
||||
"""
|
||||
获取当前用户信息
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
|
||||
|
||||
返回:
|
||||
- Dict: 当前用户详情字典
|
||||
"""
|
||||
@@ -256,19 +257,19 @@ class UserService:
|
||||
# 使用树形结构查询,预加载children关系
|
||||
menu_all = await MenuCRUD(auth).get_tree_list_crud(search={'type': ('in', [1, 2, 4]), 'status': '0'}, order_by=[{"order": "asc"}])
|
||||
menus = [MenuOutSchema.model_validate(menu).model_dump() for menu in menu_all]
|
||||
|
||||
|
||||
else:
|
||||
# 收集用户所有角色的菜单ID,使用列表推导式优化代码
|
||||
menu_ids = {
|
||||
menu.id
|
||||
for role in auth.user.roles or []
|
||||
for menu in role.menus
|
||||
menu.id
|
||||
for role in auth.user.roles or []
|
||||
for menu in role.menus
|
||||
if menu.status == "0" and menu.type in [1, 2, 4]
|
||||
}
|
||||
|
||||
|
||||
# 使用树形结构查询,预加载children关系
|
||||
menus = [
|
||||
MenuOutSchema.model_validate(menu).model_dump()
|
||||
MenuOutSchema.model_validate(menu).model_dump()
|
||||
for menu in await MenuCRUD(auth).get_tree_list_crud(search={'id': ('in', list(menu_ids))}, order_by=[{"order": "asc"}])
|
||||
] if menu_ids else []
|
||||
user_dict["menus"] = traversal_to_tree(menus)
|
||||
@@ -278,11 +279,11 @@ class UserService:
|
||||
async def update_current_user_info_service(cls, auth: AuthSchema, data: CurrentUserUpdateSchema) -> dict:
|
||||
"""
|
||||
更新当前用户信息
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (CurrentUserUpdateSchema): 当前用户更新信息
|
||||
|
||||
|
||||
返回:
|
||||
- Dict: 更新后的当前用户详情字典
|
||||
"""
|
||||
@@ -311,11 +312,11 @@ class UserService:
|
||||
async def set_user_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
|
||||
"""
|
||||
设置用户状态
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (BatchSetAvailable): 批量设置用户状态数据
|
||||
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
@@ -331,16 +332,16 @@ class UserService:
|
||||
async def upload_avatar_service(cls, base_url: str, file: UploadFile) -> dict:
|
||||
"""
|
||||
上传用户头像
|
||||
|
||||
|
||||
参数:
|
||||
- base_url (str): 基础URL
|
||||
- file (UploadFile): 上传的文件
|
||||
|
||||
|
||||
返回:
|
||||
- Dict: 上传头像响应字典
|
||||
"""
|
||||
filename, filepath, file_url = await UploadUtil.upload_file(file=file, base_url=base_url)
|
||||
|
||||
|
||||
return UploadResponseSchema(
|
||||
file_path=f'{filepath}',
|
||||
file_name=filename,
|
||||
@@ -352,11 +353,11 @@ class UserService:
|
||||
async def change_user_password_service(cls, auth: AuthSchema, data: UserChangePasswordSchema) -> dict:
|
||||
"""
|
||||
修改用户密码
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (UserChangePasswordSchema): 用户密码修改数据
|
||||
|
||||
|
||||
返回:
|
||||
- Dict: 更新后的当前用户详情字典
|
||||
"""
|
||||
@@ -376,16 +377,16 @@ class UserService:
|
||||
new_password_hash = PwdUtil.set_password_hash(password=data.new_password)
|
||||
new_user = await UserCRUD(auth).change_password_crud(id=user.id, password_hash=new_password_hash)
|
||||
return UserOutSchema.model_validate(new_user).model_dump()
|
||||
|
||||
|
||||
@classmethod
|
||||
async def reset_user_password_service(cls, auth: AuthSchema, data: ResetPasswordSchema) -> dict:
|
||||
"""
|
||||
重置用户密码
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (ResetPasswordSchema): 用户密码重置数据
|
||||
|
||||
|
||||
返回:
|
||||
- Dict: 更新后的当前用户详情字典
|
||||
"""
|
||||
@@ -396,7 +397,7 @@ class UserService:
|
||||
user = await UserCRUD(auth).get_by_id_crud(id=data.id)
|
||||
if not user:
|
||||
raise CustomException(msg="用户不存在")
|
||||
|
||||
|
||||
# 检查是否是超级管理员
|
||||
if user.is_superuser:
|
||||
raise CustomException(msg="超级管理员密码不能重置")
|
||||
@@ -410,11 +411,11 @@ class UserService:
|
||||
async def register_user_service(cls, auth: AuthSchema, data: UserRegisterSchema) -> dict:
|
||||
"""
|
||||
用户注册
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (UserRegisterSchema): 用户注册数据
|
||||
|
||||
|
||||
返回:
|
||||
- Dict: 注册后的用户详情字典
|
||||
"""
|
||||
@@ -426,11 +427,11 @@ class UserService:
|
||||
data.password = PwdUtil.set_password_hash(password=data.password)
|
||||
data.name = data.username
|
||||
create_dict = data.model_dump(exclude_unset=True, exclude={"role_ids", "position_ids"})
|
||||
|
||||
|
||||
# 设置创建人ID
|
||||
if auth.user and auth.user.id:
|
||||
create_dict["created_id"] = auth.user.id
|
||||
|
||||
|
||||
result = await UserCRUD(auth).create(data=create_dict)
|
||||
if data.role_ids:
|
||||
await UserCRUD(auth).set_user_roles_crud(user_ids=[result.id], role_ids=data.role_ids)
|
||||
@@ -440,11 +441,11 @@ class UserService:
|
||||
async def forget_password_service(cls, auth: AuthSchema, data: UserForgetPasswordSchema) -> dict:
|
||||
"""
|
||||
用户忘记密码
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- data (UserForgetPasswordSchema): 用户忘记密码数据
|
||||
|
||||
|
||||
返回:
|
||||
- Dict: 更新后的当前用户详情字典
|
||||
"""
|
||||
@@ -453,7 +454,7 @@ class UserService:
|
||||
raise CustomException(msg="用户不存在")
|
||||
if user.status == "1":
|
||||
raise CustomException(msg="用户已停用")
|
||||
|
||||
|
||||
# 检查是否是超级管理员
|
||||
if user.is_superuser:
|
||||
raise CustomException(msg="超级管理员密码不能重置")
|
||||
@@ -466,16 +467,16 @@ class UserService:
|
||||
async def batch_import_user_service(cls, auth: AuthSchema, file: UploadFile, update_support: bool = False) -> str:
|
||||
"""
|
||||
批量导入用户
|
||||
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
- file (UploadFile): 上传的Excel文件
|
||||
- update_support (bool, optional): 是否支持更新已存在用户. 默认值为False.
|
||||
|
||||
|
||||
返回:
|
||||
- str: 导入结果消息
|
||||
"""
|
||||
|
||||
|
||||
header_dict = {
|
||||
'部门编号': 'dept_id',
|
||||
'用户名': 'username',
|
||||
@@ -491,43 +492,43 @@ class UserService:
|
||||
contents = await file.read()
|
||||
df = pd.read_excel(io.BytesIO(contents))
|
||||
await file.close()
|
||||
|
||||
|
||||
if df.empty:
|
||||
raise CustomException(msg="导入文件为空")
|
||||
|
||||
|
||||
# 检查表头是否完整
|
||||
missing_headers = [header for header in header_dict.keys() if header not in df.columns]
|
||||
if missing_headers:
|
||||
raise CustomException(msg=f"导入文件缺少必要的列: {', '.join(missing_headers)}")
|
||||
|
||||
|
||||
# 重命名列名
|
||||
df.rename(columns=header_dict, inplace=True)
|
||||
|
||||
|
||||
# 验证必填字段
|
||||
required_fields = ['username', 'name', 'dept_id']
|
||||
errors = []
|
||||
for field in required_fields:
|
||||
missing_rows = df[df[field].isnull()].index.tolist()
|
||||
if missing_rows:
|
||||
field_name = [k for k,v in header_dict.items() if v == field][0]
|
||||
rows_str = "、".join([str(i+1) for i in missing_rows])
|
||||
field_name = next(k for k, v in header_dict.items() if v == field)
|
||||
rows_str = "、".join([str(i + 1) for i in missing_rows])
|
||||
errors.append(f"{field_name}不能为空,第{rows_str}行")
|
||||
|
||||
|
||||
if errors:
|
||||
raise CustomException(msg=";".join(errors))
|
||||
|
||||
|
||||
error_msgs = []
|
||||
success_count = 0
|
||||
count = 0
|
||||
|
||||
|
||||
# 处理每一行数据
|
||||
for index, row in df.iterrows():
|
||||
for _index, row in df.iterrows():
|
||||
try:
|
||||
count = count + 1
|
||||
# 数据转换
|
||||
gender = 1 if row['gender'] == '男' else (2 if row['gender'] == '女' else 1)
|
||||
status = "0" if row['status'] == '正常' else "1"
|
||||
|
||||
|
||||
# 构建用户数据
|
||||
user_data = {
|
||||
"username": str(row['username']).strip(),
|
||||
@@ -557,9 +558,9 @@ class UserService:
|
||||
user_create_data = UserCreateSchema(**user_data)
|
||||
await UserCRUD(auth).create(data=user_create_data)
|
||||
success_count += 1
|
||||
|
||||
|
||||
except Exception as e:
|
||||
error_msgs.append(f"第{count}行: 异常{str(e)}")
|
||||
error_msgs.append(f"第{count}行: 异常{e!s}")
|
||||
continue
|
||||
|
||||
# 返回详细的导入结果
|
||||
@@ -567,21 +568,21 @@ class UserService:
|
||||
if error_msgs:
|
||||
result += "\n错误信息:\n" + "\n".join(error_msgs)
|
||||
return result
|
||||
|
||||
|
||||
except Exception as e:
|
||||
log.error(f"批量导入用户失败: {str(e)}")
|
||||
raise CustomException(msg=f"导入失败: {str(e)}")
|
||||
log.error(f"批量导入用户失败: {e!s}")
|
||||
raise CustomException(msg=f"导入失败: {e!s}")
|
||||
|
||||
@classmethod
|
||||
async def get_import_template_user_service(cls) -> bytes:
|
||||
"""
|
||||
获取用户导入模板
|
||||
|
||||
|
||||
返回:
|
||||
- bytes: Excel文件字节流
|
||||
"""
|
||||
header_list = ['部门编号', '用户名', '名称', '邮箱', '手机号', '性别', '状态']
|
||||
selector_header_list = ['性别', '状态']
|
||||
selector_header_list = ['性别', '状态']
|
||||
option_list = [{'性别': ['男', '女', '未知']}, {'状态': ['正常', '停用']}]
|
||||
return ExcelUtil.get_excel_template(
|
||||
header_list=header_list,
|
||||
@@ -593,22 +594,22 @@ class UserService:
|
||||
async def export_user_list_service(cls, user_list: list[dict[str, Any]]) -> bytes:
|
||||
"""
|
||||
导出用户列表为Excel文件
|
||||
|
||||
|
||||
参数:
|
||||
- user_list (List[Dict[str, Any]]): 用户列表
|
||||
|
||||
|
||||
返回:
|
||||
- bytes: Excel文件字节流
|
||||
"""
|
||||
if not user_list:
|
||||
raise CustomException(msg="没有数据可导出")
|
||||
|
||||
|
||||
# 定义字段映射
|
||||
mapping_dict = {
|
||||
'id': '用户编号',
|
||||
'avatar': '头像',
|
||||
'username': '用户名称',
|
||||
'name': '用户昵称',
|
||||
'name': '用户昵称',
|
||||
'dept_name': '部门',
|
||||
'email': '邮箱',
|
||||
'mobile': '手机号',
|
||||
|
||||
Reference in New Issue
Block a user