service.py 27 KB

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