service.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. import io
  2. from typing import Any
  3. import pandas as pd
  4. from fastapi import UploadFile
  5. from app.api.v1.module_system.auth.schema import AuthSchema
  6. from app.api.v1.module_system.dept.crud import DeptCRUD
  7. from app.api.v1.module_system.menu.crud import MenuCRUD
  8. from app.api.v1.module_system.menu.schema import MenuOutSchema
  9. from app.api.v1.module_system.position.crud import PositionCRUD
  10. from app.api.v1.module_system.role.crud import RoleCRUD
  11. from app.core.base_schema import BatchSetAvailable, UploadResponseSchema
  12. from app.core.exceptions import CustomException
  13. from app.core.logger import log
  14. from app.utils.common_util import traversal_to_tree
  15. from app.utils.excel_util import ExcelUtil
  16. from app.utils.hash_bcrpy_util import PwdUtil
  17. from app.utils.upload_util import UploadUtil
  18. from .crud import UserCRUD
  19. from .schema import (
  20. CurrentUserUpdateSchema,
  21. ResetPasswordSchema,
  22. UserChangePasswordSchema,
  23. UserCreateSchema,
  24. UserForgetPasswordSchema,
  25. UserOutSchema,
  26. UserQueryParam,
  27. UserRegisterSchema,
  28. UserUpdateSchema,
  29. )
  30. from ..tenant.schema import TenantCreateSchema
  31. from ..tenant.service import TenantService
  32. class UserService:
  33. """用户模块服务层"""
  34. @classmethod
  35. async def get_detail_by_id_service(cls, auth: AuthSchema, id: int) -> dict:
  36. """
  37. 根据ID获取用户详情
  38. 参数:
  39. - auth (AuthSchema): 认证信息模型
  40. - id (int): 用户ID
  41. 返回:
  42. - dict: 用户详情字典
  43. """
  44. user = await UserCRUD(auth).get_by_id_crud(id=id)
  45. if not user:
  46. raise CustomException(msg="用户不存在")
  47. # 如果用户绑定了部门,则获取部门名称
  48. if user.dept_id:
  49. dept = await DeptCRUD(auth).get_by_id_crud(id=user.dept_id)
  50. UserOutSchema.dept_name = dept.name if dept else None
  51. else:
  52. UserOutSchema.dept_name = None
  53. return UserOutSchema.model_validate(user).model_dump()
  54. @classmethod
  55. async def get_user_list_service(
  56. cls,
  57. auth: AuthSchema,
  58. search: UserQueryParam | None = None,
  59. order_by: list[dict[str, str]] | None = None,
  60. ) -> list[dict]:
  61. """
  62. 获取用户列表
  63. 参数:
  64. - auth (AuthSchema): 认证信息模型
  65. - search (UserQueryParam | None): 查询参数对象。
  66. - order_by (list[dict[str, str]] | None): 排序参数列表。
  67. 返回:
  68. - list[dict]: 用户详情字典列表
  69. """
  70. user_list = await UserCRUD(auth).get_list_crud(search=search.__dict__, order_by=order_by)
  71. user_dict_list = []
  72. for user in user_list:
  73. user_dict = UserOutSchema.model_validate(user).model_dump()
  74. user_dict_list.append(user_dict)
  75. return user_dict_list
  76. @classmethod
  77. async def get_user_page_service(
  78. cls,
  79. auth: AuthSchema,
  80. page_no: int,
  81. page_size: int,
  82. search: UserQueryParam | None = None,
  83. order_by: list[dict[str, str]] | None = None,
  84. ) -> dict:
  85. """
  86. 分页查询用户(数据库 OFFSET/LIMIT)。
  87. 参数:
  88. - auth (AuthSchema): 认证信息模型
  89. - page_no (int): 页码(从 1 开始)
  90. - page_size (int): 每页条数
  91. - search (UserQueryParam | None): 查询条件
  92. - order_by (list[dict[str, str]] | None): 排序字段列表
  93. 返回:
  94. - dict: 分页结果(结构由 `CRUD.page` 返回约定)
  95. """
  96. offset = (page_no - 1) * page_size
  97. return await UserCRUD(auth).page(
  98. offset=offset,
  99. limit=page_size,
  100. order_by=order_by or [{"id": "asc"}],
  101. search=search.__dict__ if search else {},
  102. out_schema=UserOutSchema,
  103. )
  104. @classmethod
  105. async def create_user_service(cls, data: UserCreateSchema, auth: AuthSchema) -> dict:
  106. """
  107. 创建用户
  108. 参数:
  109. - data (UserCreateSchema): 用户创建信息
  110. - auth (AuthSchema): 认证信息模型
  111. 返回:
  112. - dict: 创建后的用户详情字典
  113. """
  114. if not data.username:
  115. raise CustomException(msg="用户名不能为空")
  116. # 检查是否试图创建超级管理员
  117. if data.is_superuser:
  118. raise CustomException(msg="不允许创建超级管理员")
  119. # 检查用户名是否存在
  120. user = await UserCRUD(auth).get_by_username_crud(username=data.username)
  121. if user:
  122. raise CustomException(msg="已存在相同用户名称的账号")
  123. # 检查部门是否存在
  124. if data.dept_id:
  125. dept = await DeptCRUD(auth).get_by_id_crud(id=data.dept_id)
  126. if not dept:
  127. raise CustomException(msg="部门不存在")
  128. # 创建用户
  129. if data.password:
  130. data.password = PwdUtil.set_password_hash(password=data.password)
  131. user_dict = data.model_dump(exclude_unset=True, exclude={"role_ids", "position_ids"})
  132. # 创建用户
  133. new_user = await UserCRUD(auth).create(data=user_dict)
  134. # 设置角色
  135. if data.role_ids and len(data.role_ids) > 0:
  136. await UserCRUD(auth).set_user_roles_crud(user_ids=[new_user.id], role_ids=data.role_ids)
  137. # 设置岗位
  138. if data.position_ids and len(data.position_ids) > 0:
  139. await UserCRUD(auth).set_user_positions_crud(
  140. user_ids=[new_user.id], position_ids=data.position_ids
  141. )
  142. new_user_dict = UserOutSchema.model_validate(new_user).model_dump()
  143. return new_user_dict
  144. @classmethod
  145. async def update_user_service(cls, id: int, data: UserUpdateSchema, auth: AuthSchema) -> dict:
  146. """
  147. 更新用户
  148. 参数:
  149. - id (int): 用户ID
  150. - data (UserUpdateSchema): 用户更新信息
  151. - auth (AuthSchema): 认证信息模型
  152. 返回:
  153. - Dict: 更新后的用户详情字典
  154. """
  155. if not data.username:
  156. raise CustomException(msg="账号不能为空")
  157. # 检查用户是否存在
  158. user = await UserCRUD(auth).get_by_id_crud(id=id)
  159. if not user:
  160. raise CustomException(msg="用户不存在")
  161. # 检查是否尝试修改超级管理员
  162. if user.is_superuser:
  163. raise CustomException(msg="超级管理员不允许修改")
  164. # 检查用户名是否重复
  165. exist_user = await UserCRUD(auth).get_by_username_crud(username=data.username)
  166. if exist_user and exist_user.id != id:
  167. raise CustomException(msg="已存在相同的账号")
  168. # 新增:检查手机号是否重复
  169. if data.mobile:
  170. exist_mobile_user = await UserCRUD(auth).get_by_mobile_crud(mobile=data.mobile)
  171. if exist_mobile_user and exist_mobile_user.id != id:
  172. raise CustomException(msg="更新失败,手机号已存在")
  173. # 新增:检查邮箱是否重复
  174. if data.email:
  175. exist_email_user = await UserCRUD(auth).get(email=data.email)
  176. if exist_email_user and exist_email_user.id != id:
  177. raise CustomException(msg="更新失败,邮箱已存在")
  178. # 检查部门是否存在且可用
  179. if data.dept_id:
  180. dept = await DeptCRUD(auth).get_by_id_crud(id=data.dept_id)
  181. if not dept:
  182. raise CustomException(msg="部门不存在")
  183. if dept.status == "1":
  184. raise CustomException(msg="部门已被禁用")
  185. # 更新用户 - 排除不应被修改的字段, 更新不更新密码
  186. user_dict = data.model_dump(
  187. exclude_unset=True,
  188. exclude={"role_ids", "position_ids", "last_login", "password"},
  189. )
  190. new_user = await UserCRUD(auth).update(id=id, data=user_dict)
  191. # 更新角色和岗位
  192. if data.role_ids and len(data.role_ids) > 0:
  193. # 检查角色是否都存在且可用
  194. roles = await RoleCRUD(auth).get_list_crud(search={"id": ("in", data.role_ids)})
  195. if len(roles) != len(data.role_ids):
  196. raise CustomException(msg="部分角色不存在")
  197. if not all(role.status for role in roles):
  198. raise CustomException(msg="部分角色已被禁用")
  199. await UserCRUD(auth).set_user_roles_crud(user_ids=[id], role_ids=data.role_ids)
  200. if data.position_ids and len(data.position_ids) > 0:
  201. # 检查岗位是否都存在且可用
  202. positions = await PositionCRUD(auth).get_list_crud(
  203. search={"id": ("in", data.position_ids)}
  204. )
  205. if len(positions) != len(data.position_ids):
  206. raise CustomException(msg="部分岗位不存在")
  207. if not all(position.status for position in positions):
  208. raise CustomException(msg="部分岗位已被禁用")
  209. await UserCRUD(auth).set_user_positions_crud(
  210. user_ids=[id], position_ids=data.position_ids
  211. )
  212. user_dict = UserOutSchema.model_validate(new_user).model_dump()
  213. return user_dict
  214. @classmethod
  215. async def delete_user_service(cls, auth: AuthSchema, ids: list[int]) -> None:
  216. """
  217. 删除用户
  218. 参数:
  219. - auth (AuthSchema): 认证信息模型
  220. - ids (list[int]): 用户ID列表
  221. 返回:
  222. - None
  223. """
  224. if len(ids) < 1:
  225. raise CustomException(msg="删除失败,删除对象不能为空")
  226. for id in ids:
  227. user = await UserCRUD(auth).get_by_id_crud(id=id)
  228. if not user:
  229. raise CustomException(msg="用户不存在")
  230. if user.is_superuser:
  231. raise CustomException(msg="超级管理员不能删除")
  232. if user.status == "0":
  233. raise CustomException(msg="用户已启用,不能删除")
  234. if auth.user and auth.user.id == id:
  235. raise CustomException(msg="不能删除当前登陆用户")
  236. # 删除用户角色关联数据
  237. await UserCRUD(auth).set_user_roles_crud(user_ids=ids, role_ids=[])
  238. # 删除用户岗位关联数据
  239. await UserCRUD(auth).set_user_positions_crud(user_ids=ids, position_ids=[])
  240. # 删除用户
  241. await UserCRUD(auth).delete(ids=ids)
  242. @classmethod
  243. async def get_current_user_info_service(cls, auth: AuthSchema) -> dict:
  244. """
  245. 获取当前用户信息
  246. 参数:
  247. - auth (AuthSchema): 认证信息模型
  248. 返回:
  249. - Dict: 当前用户详情字典
  250. """
  251. # 获取用户基本信息
  252. if not auth.user or not auth.user.id:
  253. raise CustomException(msg="用户不存在")
  254. user = await UserCRUD(auth).get_by_id_crud(id=auth.user.id)
  255. # 获取部门名称
  256. if user and user.dept:
  257. UserOutSchema.dept_name = user.dept.name
  258. user_dict = UserOutSchema.model_validate(user).model_dump()
  259. # 获取菜单权限
  260. if auth.user and auth.user.is_superuser:
  261. # 使用树形结构查询,预加载children关系
  262. menu_all = await MenuCRUD(auth).get_tree_list_crud(
  263. search={"type": ("in", [1, 2, 4]), "status": "0"},
  264. order_by=[{"order": "asc"}],
  265. )
  266. menus = [MenuOutSchema.model_validate(menu).model_dump() for menu in menu_all]
  267. else:
  268. # 收集用户所有角色的菜单ID,使用列表推导式优化代码
  269. menu_ids = {
  270. menu.id
  271. for role in auth.user.roles or []
  272. for menu in role.menus
  273. if menu.status == "0" and menu.type in [1, 2, 4]
  274. }
  275. # 使用树形结构查询,预加载children关系
  276. menus = (
  277. [
  278. MenuOutSchema.model_validate(menu).model_dump()
  279. for menu in await MenuCRUD(auth).get_tree_list_crud(
  280. search={"id": ("in", list(menu_ids))},
  281. order_by=[{"order": "asc"}],
  282. )
  283. ]
  284. if menu_ids
  285. else []
  286. )
  287. user_dict["menus"] = traversal_to_tree(menus)
  288. return user_dict
  289. @classmethod
  290. async def update_current_user_info_service(
  291. cls, auth: AuthSchema, data: CurrentUserUpdateSchema
  292. ) -> dict:
  293. """
  294. 更新当前用户信息
  295. 参数:
  296. - auth (AuthSchema): 认证信息模型
  297. - data (CurrentUserUpdateSchema): 当前用户更新信息
  298. 返回:
  299. - Dict: 更新后的当前用户详情字典
  300. """
  301. if not auth.user or not auth.user.id:
  302. raise CustomException(msg="用户不存在")
  303. user = await UserCRUD(auth).get_by_id_crud(id=auth.user.id)
  304. if not user:
  305. raise CustomException(msg="用户不存在")
  306. if user.is_superuser:
  307. raise CustomException(msg="超级管理员不能修改个人信息")
  308. # 新增:检查手机号是否重复
  309. if data.mobile:
  310. exist_mobile_user = await UserCRUD(auth).get_by_mobile_crud(mobile=data.mobile)
  311. if exist_mobile_user and exist_mobile_user.id != auth.user.id:
  312. raise CustomException(msg="更新失败,手机号已存在")
  313. # 新增:检查邮箱是否重复
  314. if data.email:
  315. exist_email_user = await UserCRUD(auth).get(email=data.email)
  316. if exist_email_user and exist_email_user.id != auth.user.id:
  317. raise CustomException(msg="更新失败,邮箱已存在")
  318. user_update_data = UserUpdateSchema(**data.model_dump())
  319. new_user = await UserCRUD(auth).update(id=auth.user.id, data=user_update_data)
  320. return UserOutSchema.model_validate(new_user).model_dump()
  321. @classmethod
  322. async def set_user_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
  323. """
  324. 设置用户状态
  325. 参数:
  326. - auth (AuthSchema): 认证信息模型
  327. - data (BatchSetAvailable): 批量设置用户状态数据
  328. 返回:
  329. - None
  330. """
  331. for id in data.ids:
  332. user = await UserCRUD(auth).get_by_id_crud(id=id)
  333. if not user:
  334. raise CustomException(msg=f"用户ID {id} 不存在")
  335. if user.is_superuser:
  336. raise CustomException(msg="超级管理员状态不能修改")
  337. await UserCRUD(auth).set_available_crud(ids=data.ids, status=data.status)
  338. @classmethod
  339. async def upload_avatar_service(cls, base_url: str, file: UploadFile) -> dict:
  340. """
  341. 上传用户头像
  342. 参数:
  343. - base_url (str): 基础URL
  344. - file (UploadFile): 上传的文件
  345. 返回:
  346. - Dict: 上传头像响应字典
  347. """
  348. filename, filepath, file_url = await UploadUtil.upload_file(file=file, base_url=base_url)
  349. return UploadResponseSchema(
  350. file_path=f"{filepath}",
  351. file_name=filename,
  352. origin_name=file.filename,
  353. file_url=f"{file_url}",
  354. ).model_dump()
  355. @classmethod
  356. async def change_user_password_service(
  357. cls, auth: AuthSchema, data: UserChangePasswordSchema
  358. ) -> dict:
  359. """
  360. 修改用户密码
  361. 参数:
  362. - auth (AuthSchema): 认证信息模型
  363. - data (UserChangePasswordSchema): 用户密码修改数据
  364. 返回:
  365. - Dict: 更新后的当前用户详情字典
  366. """
  367. if not auth.user or not auth.user.id:
  368. raise CustomException(msg="用户不存在")
  369. if not data.old_password or not data.new_password:
  370. raise CustomException(msg="密码不能为空")
  371. # 验证原密码
  372. user = await UserCRUD(auth).get_by_id_crud(id=auth.user.id)
  373. if not user:
  374. raise CustomException(msg="用户不存在")
  375. if not PwdUtil.verify_password(
  376. plain_password=data.old_password, password_hash=user.password
  377. ):
  378. raise CustomException(msg="原密码输入错误")
  379. # 更新密码
  380. new_password_hash = PwdUtil.set_password_hash(password=data.new_password)
  381. new_user = await UserCRUD(auth).change_password_crud(
  382. id=user.id, password_hash=new_password_hash
  383. )
  384. return UserOutSchema.model_validate(new_user).model_dump()
  385. @classmethod
  386. async def reset_user_password_service(cls, auth: AuthSchema, data: ResetPasswordSchema) -> dict:
  387. """
  388. 重置用户密码
  389. 参数:
  390. - auth (AuthSchema): 认证信息模型
  391. - data (ResetPasswordSchema): 用户密码重置数据
  392. 返回:
  393. - Dict: 更新后的当前用户详情字典
  394. """
  395. if not data.password:
  396. raise CustomException(msg="密码不能为空")
  397. # 验证用户
  398. user = await UserCRUD(auth).get_by_id_crud(id=data.id)
  399. if not user:
  400. raise CustomException(msg="用户不存在")
  401. # 检查是否是超级管理员
  402. if user.is_superuser:
  403. raise CustomException(msg="超级管理员密码不能重置")
  404. # 更新密码
  405. new_password_hash = PwdUtil.set_password_hash(password=data.password)
  406. new_user = await UserCRUD(auth).change_password_crud(
  407. id=data.id, password_hash=new_password_hash
  408. )
  409. return UserOutSchema.model_validate(new_user).model_dump()
  410. @classmethod
  411. async def register_user_service(cls, auth: AuthSchema, data: UserRegisterSchema) -> dict:
  412. """
  413. 用户注册
  414. 参数:
  415. - auth (AuthSchema): 认证信息模型
  416. - data (UserRegisterSchema): 用户注册数据
  417. 返回:
  418. - Dict: 注册后的用户详情字典
  419. """
  420. # 检查用户名是否存在
  421. data.username = data.mobile
  422. username_ok = await UserCRUD(auth).get_by_username_crud(username=data.username)
  423. if username_ok:
  424. raise CustomException(msg="账号已存在")
  425. # data.password = PwdUtil.set_password_hash(password=data.password)
  426. # data.name = data.username
  427. # create_dict = data.model_dump(exclude_unset=True, exclude={"role_ids", "position_ids"})
  428. #
  429. # # 设置创建人ID
  430. # if auth.user and auth.user.id:
  431. # create_dict["created_id"] = auth.user.id
  432. #
  433. # result = await UserCRUD(auth).create(data=create_dict)
  434. # if data.role_ids:
  435. # await UserCRUD(auth).set_user_roles_crud(user_ids=[result.id], role_ids=data.role_ids)
  436. # return UserOutSchema.model_validate(result).model_dump()
  437. tenant_data = TenantCreateSchema(
  438. name=data.mobile,
  439. code=data.mobile,
  440. )
  441. return await TenantService.create_service(auth=auth, data=tenant_data)
  442. @classmethod
  443. async def forget_password_service(
  444. cls, auth: AuthSchema, data: UserForgetPasswordSchema
  445. ) -> dict:
  446. """
  447. 用户忘记密码
  448. 参数:
  449. - auth (AuthSchema): 认证信息模型
  450. - data (UserForgetPasswordSchema): 用户忘记密码数据
  451. 返回:
  452. - Dict: 更新后的当前用户详情字典
  453. """
  454. user = await UserCRUD(auth).get_by_username_crud(username=data.username)
  455. if not user:
  456. raise CustomException(msg="用户不存在")
  457. if user.status == "1":
  458. raise CustomException(msg="用户已停用")
  459. # 检查是否是超级管理员
  460. if user.is_superuser:
  461. raise CustomException(msg="超级管理员密码不能重置")
  462. new_password_hash = PwdUtil.set_password_hash(password=data.new_password)
  463. new_user = await UserCRUD(auth).forget_password_crud(
  464. id=user.id, password_hash=new_password_hash
  465. )
  466. return UserOutSchema.model_validate(new_user).model_dump()
  467. @classmethod
  468. async def batch_import_user_service(
  469. cls, auth: AuthSchema, file: UploadFile, update_support: bool = False
  470. ) -> str:
  471. """
  472. 批量导入用户
  473. 参数:
  474. - auth (AuthSchema): 认证信息模型
  475. - file (UploadFile): 上传的Excel文件
  476. - update_support (bool, optional): 是否支持更新已存在用户. 默认值为False.
  477. 返回:
  478. - str: 导入结果消息
  479. """
  480. header_dict = {
  481. "部门编号": "dept_id",
  482. "账号": "username",
  483. "昵称": "name",
  484. "邮箱": "email",
  485. "手机号": "mobile",
  486. "性别": "gender",
  487. "状态": "status",
  488. }
  489. try:
  490. # 读取Excel文件
  491. contents = await file.read()
  492. df = pd.read_excel(io.BytesIO(contents))
  493. await file.close()
  494. if df.empty:
  495. raise CustomException(msg="导入文件为空")
  496. # 检查表头是否完整
  497. missing_headers = [header for header in header_dict.keys() if header not in df.columns]
  498. if missing_headers:
  499. raise CustomException(msg=f"导入文件缺少必要的列: {', '.join(missing_headers)}")
  500. # 重命名列名
  501. df.rename(columns=header_dict, inplace=True)
  502. # 验证必填字段
  503. required_fields = ["username", "name", "dept_id"]
  504. errors = []
  505. for field in required_fields:
  506. missing_rows = df[df[field].isnull()].index.tolist()
  507. if missing_rows:
  508. field_name = next(k for k, v in header_dict.items() if v == field)
  509. rows_str = "、".join([str(i + 1) for i in missing_rows])
  510. errors.append(f"{field_name}不能为空,第{rows_str}行")
  511. if errors:
  512. raise CustomException(msg=";".join(errors))
  513. error_msgs = []
  514. success_count = 0
  515. count = 0
  516. # 处理每一行数据
  517. for _index, row in df.iterrows():
  518. try:
  519. count = count + 1
  520. # 数据转换
  521. gender = "1" if row["gender"] == "男" else ("2" if row["gender"] == "女" else "1")
  522. status = "0" if row["status"] == "正常" else "1"
  523. # 构建用户数据
  524. user_data = {
  525. "username": str(row["username"]).strip(),
  526. "name": str(row["name"]).strip(),
  527. "email": str(row["email"]).strip(),
  528. "mobile": str(row["mobile"]).strip(),
  529. "gender": gender,
  530. "status": status,
  531. "dept_id": int(row["dept_id"]),
  532. "password": PwdUtil.set_password_hash(password="123456"), # 设置默认密码
  533. }
  534. # 处理用户导入
  535. exists_user = await UserCRUD(auth).get_by_username_crud(
  536. username=user_data["username"]
  537. )
  538. if exists_user:
  539. # 检查是否是超级管理员
  540. if exists_user.is_superuser:
  541. error_msgs.append(f"第{count}行: 超级管理员不允许修改")
  542. continue
  543. if update_support:
  544. user_update_data = UserUpdateSchema(**user_data)
  545. await UserCRUD(auth).update(id=exists_user.id, data=user_update_data)
  546. success_count += 1
  547. else:
  548. error_msgs.append(f"第{count}行: 用户 {user_data['username']} 已存在")
  549. else:
  550. user_create_schema = UserCreateSchema(**user_data)
  551. user_create_data = user_create_schema.model_dump(
  552. exclude_unset=True, exclude={"role_ids", "position_ids"}
  553. )
  554. new_user = await UserCRUD(auth).create(data=user_create_data)
  555. if user_create_schema.role_ids and len(user_create_schema.role_ids) > 0:
  556. await UserCRUD(auth).set_user_roles_crud(
  557. user_ids=[new_user.id], role_ids=user_create_schema.role_ids
  558. )
  559. if user_create_schema.position_ids and len(user_create_schema.position_ids) > 0:
  560. await UserCRUD(auth).set_user_positions_crud(
  561. user_ids=[new_user.id], position_ids=user_create_schema.position_ids
  562. )
  563. success_count += 1
  564. except Exception as e:
  565. error_msgs.append(f"第{count}行: 异常{e!s}")
  566. continue
  567. # 返回详细的导入结果
  568. result = f"成功导入 {success_count} 条数据"
  569. if error_msgs:
  570. result += "\n错误信息:\n" + "\n".join(error_msgs)
  571. return result
  572. except Exception as e:
  573. log.error(f"批量导入用户失败: {e!s}")
  574. raise CustomException(msg=f"导入失败: {e!s}")
  575. @classmethod
  576. async def get_import_template_user_service(cls) -> bytes:
  577. """
  578. 获取用户导入模板
  579. 返回:
  580. - bytes: Excel文件字节流
  581. """
  582. header_list = [
  583. "部门编号",
  584. "账号",
  585. "昵称",
  586. "邮箱",
  587. "手机号",
  588. "性别",
  589. "状态",
  590. ]
  591. selector_header_list = ["性别", "状态"]
  592. option_list = [
  593. {"性别": ["男", "女", "未知"]},
  594. {"状态": ["正常", "停用"]},
  595. ]
  596. return ExcelUtil.get_excel_template(
  597. header_list=header_list,
  598. selector_header_list=selector_header_list,
  599. option_list=option_list,
  600. )
  601. @classmethod
  602. async def export_user_list_service(cls, user_list: list[dict[str, Any]]) -> bytes:
  603. """
  604. 导出用户列表为Excel文件
  605. 参数:
  606. - user_list (list[dict[str, Any]]): 用户列表
  607. 返回:
  608. - bytes: Excel文件字节流
  609. """
  610. if not user_list:
  611. raise CustomException(msg="没有数据可导出")
  612. # 定义字段映射
  613. mapping_dict = {
  614. "id": "用户编号",
  615. "avatar": "头像",
  616. "username": "用户名称",
  617. "name": "用户昵称",
  618. "dept_name": "部门",
  619. "email": "邮箱",
  620. "mobile": "手机号",
  621. "gender": "性别",
  622. "status": "状态",
  623. "is_superuser": "是否超级管理员",
  624. "last_login": "最后登录时间",
  625. "description": "备注",
  626. "created_time": "创建时间",
  627. "updated_time": "更新时间",
  628. "updated_id": "更新者ID",
  629. }
  630. # 复制数据并转换
  631. # creator = {'id': 1, 'name': '管理员', 'username': 'admin'}
  632. data = user_list.copy()
  633. for item in data:
  634. item["status"] = "启用" if item.get("status") == "0" else "停用"
  635. gender = item.get("gender")
  636. item["gender"] = "男" if gender == "1" else ("女" if gender == "2" else "未知")
  637. item["is_superuser"] = "是" if item.get("is_superuser") else "否"
  638. item["creator"] = (
  639. item.get("creator", {}).get("name", "未知")
  640. if isinstance(item.get("creator"), dict)
  641. else "未知"
  642. )
  643. return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)